# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-skill-injection-payload-smuggled-through-a-dynamically-loaded-plugin-s-declared-capability-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-skill-injection-payload-smuggled-through-a-dynamically-loaded-plugin-s-declared-capability-schema.warrant.json
# Markdown SHA-256:   dfc0d3301a311f050d7f96f15c8c422fca479fa060b04a5d8d17a03b8e64065c
# Code AST SHA-256:   9cc469ae19d5f5e372c2e0a1684bac0bd90b71898956be436b71ae7da1745223
# Verified Classes:   DescriptorInjectionError, SkillManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass


class DescriptorInjectionError(RuntimeError):
    """Raised when a dynamically loaded skill descriptor violates the
    provenance invariant: publisher prose must not carry instructional
    authority or reference other skills' behavior."""
    pass


# Signals that a descriptor is attempting to act as a directive rather
# than describe a capability. Rejection, not sanitization.
_ROLE_MARKER = re.compile(r"(<\|?(system|assistant|user)\|?>|^\s*(SYSTEM|INSTRUCTION)\s*:)", re.I)
_CROSS_SKILL = re.compile(r"\b(when calling|for the .* tool|route .* through|instead of using)\b", re.I)
_MAX_DESC = 280


@dataclass
class SkillManifest:
    name: str
    description: str
    when_to_use: str
    parameters: dict
    signed_digest: str


def load_skill(manifest: SkillManifest, operator_trusted: bool = False) -> dict:
    # Signature check attests authenticity only -- NOT instructional authority.
    computed = hashlib.sha256(
        (manifest.description + manifest.when_to_use).encode()
    ).hexdigest()
    if computed != manifest.signed_digest:
        raise DescriptorInjectionError(
            f"skill {manifest.name!r}: digest mismatch, descriptor tampered in transit"
        )

    if operator_trusted:
        return {"name": manifest.name, "schema": manifest.parameters}

    text = f"{manifest.description} {manifest.when_to_use}"
    if len(manifest.description) > _MAX_DESC:
        raise DescriptorInjectionError(
            f"skill {manifest.name!r}: description exceeds capability-summary budget "
            f"({len(manifest.description)} > {_MAX_DESC}); likely smuggled directive"
        )
    if _ROLE_MARKER.search(text):
        raise DescriptorInjectionError(
            f"skill {manifest.name!r}: descriptor contains role-marker / directive framing"
        )
    if _CROSS_SKILL.search(text):
        raise DescriptorInjectionError(
            f"skill {manifest.name!r}: descriptor references another skill's behavior "
            f"(cross-skill argument-poisoning vector)"
        )

    # Return the descriptor ONLY for the selection/ranking step, tagged as
    # data. The orchestrator must evict it after selection and must never
    # place it in the operator-instruction trust zone.
    return {
        "name": manifest.name,
        "schema": manifest.parameters,
        "selection_text": f"[UNTRUSTED-DESCRIPTOR src={manifest.name}]{text}",
        "trust_zone": "data",
        "evict_after_selection": True,
    }
