# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-peer-s-capability-manifest-before-schema-binding-and-why-description-level-skill-injection-defeats-pos.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-peer-s-capability-manifest-before-schema-binding-and-why-description-level-skill-injection-defeats-pos.warrant.json
# Markdown SHA-256:   0584415b1ff26b790d7c45e93a59f75a1527bcbd65ace3d748ac674fd5c45b0b
# Code AST SHA-256:   569b5e8f4a9e321159b42983a991b71a4620cffbcaf12ee78ec7a8fc7d779588
# Verified Classes:   ManifestQuarantineError, Manifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass


class ManifestQuarantineError(RuntimeError):
    """Raised when a peer manifest must not be bound due to injection risk."""


IMPERATIVE_MARKERS = re.compile(
    r"\b(you must|you should|always first|before responding|do not mention|"
    r"silently|without telling)\b",
    re.IGNORECASE,
)


@dataclass(frozen=True)
class Manifest:
    peer_id: str
    declared_tools: frozenset[str]
    description: str
    raw: bytes


def _sha256(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def gate_manifest(manifest: Manifest) -> str:
    """Return pinned hash if the manifest is safe to bind, else quarantine."""
    if IMPERATIVE_MARKERS.search(manifest.description):
        raise ManifestQuarantineError(
            f"peer {manifest.peer_id!r}: imperative/concealment marker in "
            f"description; refusing to bind before schema binding"
        )

    referenced = set(re.findall(r"`([a-z_][a-z0-9_]*)`", manifest.description))
    undeclared = referenced - set(manifest.declared_tools)
    if undeclared:
        raise ManifestQuarantineError(
            f"peer {manifest.peer_id!r}: description references undeclared "
            f"capabilities {sorted(undeclared)}; possible skill injection"
        )

    # Pin the manifest so a later re-fetch cannot silently swap it (TOCTOU).
    return _sha256(manifest.raw)


def bind_if_cleared(manifest: Manifest, expected_hash: str | None = None) -> str:
    pinned = gate_manifest(manifest)
    if expected_hash is not None and pinned != expected_hash:
        raise ManifestQuarantineError(
            f"peer {manifest.peer_id!r}: manifest hash drift "
            f"({expected_hash} -> {pinned}); possible manifest swap"
        )
    return pinned
