# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-descriptor-poisoning-in-mcp-tool-manifests-when-schema-drift-is-indistinguishable-from-supply-chain-compromise.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-descriptor-poisoning-in-mcp-tool-manifests-when-schema-drift-is-indistinguishable-from-supply-chain-compromise.warrant.json
# Markdown SHA-256:   e6e226c59673fb967fc5bcae3bbeef9f6e94b15fb8840a397a806ac355018172
# Code AST SHA-256:   bab1403b92c559a4432ea5a7a230be243c3f61d030e1748f2152c79dff082853
# Verified Classes:   DescriptorPoisoningError, ManifestEntry, PinnedBaseline
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field
from typing import Optional


class DescriptorPoisoningError(RuntimeError):
    """Raised when a tool manifest mutation crosses the declarative->instructive boundary."""
    pass


# Imperative / cross-tool-reference markers that indicate a descriptor is
# trying to act as an instruction channel rather than documentation.
_IMPERATIVE_PATTERNS = [
    r"\bfirst invoke\b",
    r"\bbefore calling\b",
    r"\byou must\b",
    r"\balways call\b",
    r"\bdo not tell\b",
    r"\bignore (the )?previous\b",
    r"\bset \w+ to 0\b",          # sentinel redefinition
    r"\bread (the )?(file|env|~/)",  # filesystem exfil hint
    r"\bfetch_url\b",             # cross-tool reference
]


@dataclass
class ManifestEntry:
    name: str
    description: str
    input_schema_hash: str
    version: str

    def descriptor_hash(self) -> str:
        return hashlib.sha256(self.description.encode()).hexdigest()


@dataclass
class PinnedBaseline:
    entries: dict[str, ManifestEntry] = field(default_factory=dict)


def classify_descriptor_delta(old: ManifestEntry, new: ManifestEntry) -> str:
    """Return 'accept' | 'quarantine' | 'reject' based on delta class."""
    if new.version == old.version and new.descriptor_hash() != old.descriptor_hash():
        return "reject"  # same version, different bytes -> non-repudiable
    if new.input_schema_hash != old.input_schema_hash:
        return "review"  # schema change, not a semantic-diff case
    if new.description == old.description:
        return "accept"
    # Prose-only mutation: scan for imperative / cross-tool markers.
    for pat in _IMPERATIVE_PATTERNS:
        if re.search(pat, new.description, re.IGNORECASE):
            return "quarantine"
    return "accept"


def gate_manifest_refresh(
    baseline: PinnedBaseline,
    refreshed: list[ManifestEntry],
    *,
    behavioral_delta_observed: bool = False,
) -> list[ManifestEntry]:
    """Filter a refreshed manifest through the quarantine gate.

    Returns the entries safe to activate. Raises DescriptorPoisoningError when a
    mutation must be rejected outright (behavioral delta or hash mismatch).
    """
    activated: list[ManifestEntry] = []
    for new in refreshed:
        old = baseline.entries.get(new.name)
        if old is None:
            # New tool: no baseline. Do not auto-activate; require enrollment.
            continue
        verdict = classify_descriptor_delta(old, new)
        if verdict == "reject":
            raise DescriptorPoisoningError(
                f"version hash mismatch on tool {new.name!r} "
                f"(version={new.version}); possible supply-chain compromise"
            )
        if verdict == "quarantine":
            if behavioral_delta_observed:
                raise DescriptorPoisoningError(
                    f"descriptor poisoning on tool {new.name!r}: imperative prose "
                    f"mutation with observed behavioral change"
                )
            # Hold old descriptor active; do not activate new. Surface diff.
            activated.append(old)
            continue
        if verdict == "review":
            activated.append(old)  # hold old until human review
            continue
        activated.append(new)
    return activated
