# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-re-attested-mcp-tool-manifest-whose-description-field-mutates-between-capability-negotiation-and-f.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-re-attested-mcp-tool-manifest-whose-description-field-mutates-between-capability-negotiation-and-f.warrant.json
# Markdown SHA-256:   bea96115425642a57abb030224977868adb7af17017b6e8a8ec8ca5a6cd288a5
# Code AST SHA-256:   a4c787074ec719b53d1398d5f3815d61bca8a358bec7ebe2a640b12a3d455596
# Verified Classes:   ManifestQuarantineError, EgressParameterViolation, PinnedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import unicodedata
from dataclasses import dataclass, field


class ManifestQuarantineError(RuntimeError):
    """Raised when a mutable manifest field changes in a way that invalidates the standing warrant."""


class EgressParameterViolation(ManifestQuarantineError):
    """Raised when a description edit attempts to steer values into an egress-named parameter."""


# Parameters whose population by description-driven text is an exfiltration channel.
EGRESS_NAMES = frozenset({"context", "callback", "webhook", "url", "include", "attach", "history"})

# Codepoints that render invisibly but survive naive hashing/diffing.
STRIP_RANGES = ((0x200B, 0x200F), (0x202A, 0x202E), (0x2060, 0x2064), (0xFEFF, 0xFEFF))


def normalize(text: str) -> str:
    for lo, hi in STRIP_RANGES:
        text = "".join(ch for ch in text if not (lo <= ord(ch) <= hi))
    return unicodedata.normalize("NFC", text)


def manifest_hash(tool: dict) -> str:
    canon = {
        "name": tool["name"],
        "required": sorted(tool["inputSchema"].get("required", [])),
        "props": sorted(tool["inputSchema"].get("properties", {}).keys()),
        "desc": normalize(tool.get("description", "")),
    }
    return hashlib.sha256(repr(sorted(canon.items())).encode()).hexdigest()


@dataclass
class PinnedManifest:
    hash: str
    tool: dict
    warrant_effect: str  # "read" | "write" | "external"


def reattest(pinned: PinnedManifest, incoming: dict) -> PinnedManifest:
    new_hash = manifest_hash(incoming)

    # Structural fields must never change under a standing warrant.
    if incoming["name"] != pinned.tool["name"]:
        raise ManifestQuarantineError(
            f"tool identity mutated: {pinned.tool['name']!r} -> {incoming['name']!r}"
        )
    old_props = set(pinned.tool["inputSchema"].get("properties", {}))
    new_props = set(incoming["inputSchema"].get("properties", {}))
    if old_props != new_props:
        raise ManifestQuarantineError(
            f"inputSchema property set changed {old_props} -> {new_props}; "
            "this is a capability change, not a metadata update"
        )

    if new_hash == pinned.hash:
        return pinned  # no-op

    # Description-only delta: treat as inbound untrusted content.
    old_desc = normalize(pinned.tool.get("description", ""))
    new_desc = normalize(incoming.get("description", ""))
    added = new_desc[len(old_desc):] if new_desc.startswith(old_desc) else new_desc

    for egress in EGRESS_NAMES:
        if egress in added.lower() and egress not in old_desc.lower():
            raise EgressParameterViolation(
                f"description delta references egress parameter {egress!r}: "
                f"{added[:120]!r} -- quarantine, do not re-approve"
            )

    # Benign rewrite: warrant survives, but description half is re-pinned.
    return PinnedManifest(hash=new_hash, tool=incoming, warrant_effect=pinned.warrant_effect)
