# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-capability-manifest-the-post-registration-skill-injection-boundary-and-the-provenance-vs-behavior-split.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-capability-manifest-the-post-registration-skill-injection-boundary-and-the-provenance-vs-behavior-split.warrant.json
# Markdown SHA-256:   2ee7bd93091d7a0fa375fe4ed9ea1db181b7506f3c1fdee7cd5ae15e692829ce
# Code AST SHA-256:   2a47afb6d26301200b05edfd1d07ff3bb25e65c2171b30cbc3a2fa42c6c8a28c
# Verified Classes:   ManifestChannelViolation, Manifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class ManifestChannelViolation(RuntimeError):
    """Raised when a manifest field attempts instruction privilege it was not granted."""
    pass


# Imperative patterns that indicate a prose field is addressing the agent,
# not describing a parameter. Presence => quarantine, never sanitize.
_INSTRUCTION_PATTERNS = re.compile(
    r"(?i)\b(before calling|first read|always include|ignore (all )?previous|"
    r"you must|do not tell|pass (the )?(full )?contents|"
    r"~\/|\.\.\/|\/etc\/|credentials|secret|token)\b"
)

# Fields consumed as prose by the catalog renderer -> data privilege only.
_PROSE_FIELDS = ("description", "title", "examples")
# Fields consumed as structure by the validator -> safe after schema check.
_STRUCTURE_FIELDS = ("type", "required", "additionalProperties")


@dataclass
class Manifest:
    name: str
    publisher: str          # allowlisted + signature-verified upstream
    schema_verified: bool
    fields: dict            # flattened field name -> value as rendered


def gate_manifest(m: Manifest, prose_token_cap: int = 512) -> Manifest:
    # Gate 0: crypto + schema already passed upstream; we do NOT re-trust on that basis.
    if not m.schema_verified:
        raise ManifestChannelViolation(f"{m.name}: schema not verified; refusing")

    for field, value in m.fields.items():
        base = field.split(".")[-1]
        if base in _STRUCTURE_FIELDS:
            continue  # structure-consumed: validator gates it, fails closed
        if base not in _PROSE_FIELDS and not field.endswith("default"):
            continue  # unknown field: not rendered, not privileged

        text = str(value)

        # Prose-privilege gate: fires AFTER authenticity, BEFORE context assembly.
        if _INSTRUCTION_PATTERNS.search(text):
            raise ManifestChannelViolation(
                f"{m.name}.{field}: instruction-injection pattern from "
                f"verified publisher {m.publisher!r}; quarantine manifest"
            )
        if len(text) > prose_token_cap:
            raise ManifestChannelViolation(
                f"{m.name}.{field}: prose exceeds {prose_token_cap} chars; "
                f"truncation would be lossy, refuse"
            )
        if base == "default" and (".." in text or text.startswith("/")):
            raise ManifestChannelViolation(
                f"{m.name}.{field}: path-like default {text!r} is an argument-channel payload"
            )

    return m  # cleared for DATA privilege only; renderer must delimit, not privilege
