# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-manifest-injection-surface-at-the-load-boundary-rather-than-at-the-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-manifest-injection-surface-at-the-load-boundary-rather-than-at-the-tool-call-boundary.warrant.json
# Markdown SHA-256:   14ae9787de0d9e4cd47e807bc1aa9f51e93909a2710d2b2c8e53d6248405048d
# Code AST SHA-256:   4d81a4547474e9796d40cff2c7287ed755e61cc0ec5f3ccbbd1cdef9af986e20
# Verified Classes:   ManifestBoundaryError, FieldClass, VerifiedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ManifestBoundaryError(RuntimeError):
    """Raised when a skill manifest crosses the data/instruction boundary
    without a verified principal, or carries structurally hostile content."""


class FieldClass(Enum):
    INERT = "inert"
    DESCRIPTIVE = "descriptive"
    INSTRUCTIONAL = "instructional"


# Fields that may reach the model, but only inside a trust-labeled data envelope.
DESCRIPTIVE_FIELDS = {"description", "when_to_use", "examples", "parameter_hint"}
INERT_FIELDS = {"name", "version", "id", "hash", "permissions", "sync_url"}

# Codepoints and constructs that make the review surface and the tokenizer
# disagree about what the manifest says.
HOSTILE_PATTERNS = [
    re.compile(r"<!--.*?-->", re.DOTALL),      # HTML comments
    re.compile(r"[\u200b-\u200f\u202a-\u202e\u2060-\u206f]"),  # zero-width / bidi
]


@dataclass(frozen=True)
class VerifiedManifest:
    publisher_id: str
    signature_ok: bool
    raw: dict[str, Any]

    @property
    def origin_tag(self) -> str:
        # Derived from the verified bytes, never read from a manifest field.
        digest = hashlib.sha256(repr(sorted(self.raw.items())).encode()).hexdigest()[:16]
        return f"skill:{self.publisher_id}@{digest}"


def classify(field: str) -> FieldClass:
    if field in INERT_FIELDS:
        return FieldClass.INERT
    if field in DESCRIPTIVE_FIELDS:
        return FieldClass.DESCRIPTIVE
    return FieldClass.INSTRUCTIONAL


def assert_render_parity(value: str, field: str) -> None:
    for pat in HOSTILE_PATTERNS:
        if pat.search(value):
            raise ManifestBoundaryError(
                f"field {field!r} contains content invisible to the review "
                f"surface but present in the token stream: {pat.pattern!r}"
            )


def load_manifest(manifest: VerifiedManifest) -> dict[str, Any]:
    """Promote a manifest into the agent context under the boundary rule.

    Returns a dict of {field: promoted_value}. Descriptive fields are wrapped
    in a loader-generated trust envelope. Instructional fields are rejected
    unless the manifest carries a verified first-party signature.
    """
    promoted: dict[str, Any] = {}
    for field, value in manifest.raw.items():
        fc = classify(field)
        if fc is FieldClass.INERT:
            promoted[field] = value
            continue
        if not isinstance(value, str):
            raise ManifestBoundaryError(f"field {field!r} must be str, got {type(value).__name__}")
        assert_render_parity(value, field)
        if fc is FieldClass.INSTRUCTIONAL:
            if not manifest.signature_ok:
                raise ManifestBoundaryError(
                    f"unverified manifest from {manifest.publisher_id!r} attempted to "
                    f"write to the instruction plane via field {field!r}"
                )
            promoted[field] = value
        else:  # DESCRIPTIVE
            promoted[field] = (
                f'<tool_metadata origin="{manifest.origin_tag}" trust="untrusted">'
                f"{value}</tool_metadata>"
            )
    return promoted
