# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-skill-manifest-and-the-skill-body-it-is-about-to-load.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-skill-manifest-and-the-skill-body-it-is-about-to-load.warrant.json
# Markdown SHA-256:   665801a7828001474e45cde0814d01046d7ed60fa90c58c8c01e91e5b3e001a0
# Code AST SHA-256:   639ed8eb3abc5253aeda8482b8a4517257459c51699db1200d9452df9749e526
# Verified Classes:   ManifestAdmissionError, Manifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class ManifestAdmissionError(RuntimeError):
    """Raised when a skill manifest fails admission and must not enter agent context."""
    pass


# Directive patterns that indicate a manifest field is trying to instruct the agent.
_DIRECTIVE_PATTERNS = [
    re.compile(r"\b(before|after|first|then)\s+(you\s+)?(call|invoke|run|execute)\b", re.I),
    re.compile(r"\b(note|instruction|attention)\s+to\s+(the\s+)?(calling\s+)?agent\b", re.I),
    re.compile(r"\bpass\s+(the\s+)?result\s+as\b", re.I),
    re.compile(r"\b(scope|token|credential|secret)s?\s*[:=]\s*\S+", re.I),
]

# Fields the model reads and reasons over; all are injection surfaces.
_MODEL_READABLE_FIELDS = ("description", "examples", "capability_claims")


@dataclass
class Manifest:
    name: str
    description: str
    parameter_names: list[str]
    capability_claims: set[str]
    examples: list[str]
    signature_verified: bool


def _scan_for_directives(field_name: str, text: str) -> None:
    for pat in _DIRECTIVE_PATTERNS:
        if pat.search(text):
            raise ManifestAdmissionError(
                f"directive pattern in manifest field '{field_name}': {pat.pattern!r}"
            )


def admit_manifest(manifest: Manifest, granted_scopes: set[str]) -> Manifest:
    # 1. Provenance gate: unsigned manifests never expose raw author text.
    if not manifest.signature_verified:
        raise ManifestAdmissionError(
            f"manifest '{manifest.name}' is unsigned; quarantine required"
        )

    # 2. Content typing on every model-readable field, before context insertion.
    for field in _MODEL_READABLE_FIELDS:
        value = getattr(manifest, field, None)
        if value is None:
            continue
        texts = value if isinstance(value, list) else [value]
        for t in texts:
            _scan_for_directives(field, t)
    for pname in manifest.parameter_names:
        _scan_for_directives("parameter_names", pname)

    # 3. Capability-subset check: manifest may not escalate beyond granted scopes.
    escalation = manifest.capability_claims - granted_scopes
    if escalation:
        raise ManifestAdmissionError(
            f"manifest '{manifest.name}' claims ungranted capabilities: {sorted(escalation)}"
        )

    return manifest


def load_skill(manifest: Manifest, granted_scopes: set[str]) -> Manifest:
    # Admission must complete before the manifest text reaches the model.
    admitted = admit_manifest(manifest, granted_scopes)
    # ... insert admitted manifest into context only after this point ...
    return admitted
