# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-manifest-poisoned-skills-before-they-execute-in-a-dynamically-loaded-tool-registry.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-manifest-poisoned-skills-before-they-execute-in-a-dynamically-loaded-tool-registry.warrant.json
# Markdown SHA-256:   420ae6698e5abb37d5377a62285e612aa327fecd05ed78687b907aae8dfb4ffc
# Code AST SHA-256:   5c88b78db315eb56eb1d21513913222606242fa2b9aabe8301a6acddb829a36f
# Verified Classes:   ManifestQuarantineError, BindState, Manifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

import unicodedata
from dataclasses import dataclass, field
from enum import Enum


class ManifestQuarantineError(RuntimeError):
    """Raised when a dynamically loaded manifest fails bind-time trust checks."""


class BindState(Enum):
    BOUND = "bound"
    QUARANTINED = "quarantined"


# Unicode categories that have no place in a declarative manifest and are the
# primary carriers of visual-spoofing / instruction-hiding payloads.
_FORBIDDEN_CATEGORIES = {"Cf", "Zl", "Zp", "Cs", "Co"}


@dataclass
class Manifest:
    name: str
    version: str
    description: str
    schema: dict
    declared_capability_class: str
    signature: str | None = None
    state: BindState = BindState.QUARANTINED
    reasons: list[str] = field(default_factory=list)


def _has_forbidden_codepoints(text: str) -> list[str]:
    bad = []
    for ch in text:
        if unicodedata.category(ch) in _FORBIDDEN_CATEGORIES:
            bad.append(f"U+{ord(ch):04X}")
    return bad


def bind_manifest(
    manifest: Manifest,
    *,
    last_known_good: Manifest | None,
    injection_classifier_score: float,
    injection_threshold: float = 0.5,
) -> Manifest:
    """
    Bind a dynamically resolved manifest into the live tool namespace, or
    quarantine it. The invariant: no manifest bytes reach the planner prompt
    unless every check passes. A single failed check is a hard stop.
    """
    reasons: list[str] = []

    # 1. Reject (do not silently strip) format/control codepoints in free text.
    for field_name in ("name", "description"):
        bad = _has_forbidden_codepoints(getattr(manifest, field_name))
        if bad:
            reasons.append(f"forbidden codepoints in {field_name}: {bad}")

    # 2. Supply-chain tamper: prose changed on an unchanged version.
    if last_known_good is not None and last_known_good.version == manifest.version:
        if manifest.description != last_known_good.description:
            reasons.append("description mutated on unchanged version")

    # 3. Prose is instruction-bearing; gate it with a classifier.
    if injection_classifier_score >= injection_threshold:
        reasons.append(
            f"injection classifier score {injection_classifier_score:.2f} "
            f">= threshold {injection_threshold:.2f}"
        )

    # 4. Signature must cover the schema, not just the name.
    if not manifest.signature:
        reasons.append("unsigned manifest; schema integrity unverifiable")

    # 5. Capability class must be declared and non-empty.
    if not manifest.declared_capability_class:
        reasons.append("missing declared capability class")

    if reasons:
        manifest.state = BindState.QUARANTINED
        manifest.reasons = reasons
        raise ManifestQuarantineError(
            f"manifest {manifest.name}@{manifest.version} quarantined: "
            + "; ".join(reasons)
        )

    manifest.state = BindState.BOUND
    manifest.reasons = []
    return manifest
