# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-manifest-integrity-has-been-subverted-versus-merely-re-signed-the-tool-description-drift-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-manifest-integrity-has-been-subverted-versus-merely-re-signed-the-tool-description-drift-boundary.warrant.json
# Markdown SHA-256:   64489247a16717f7decdc3b45509bd1d12c25372e19d43aefb314a31111cf83b
# Code AST SHA-256:   dd79010b3b0e1d430a82ae25ab33f48eeaec2d7c73c17c098162006b9bb8cc5d
# Verified Classes:   ManifestIntegrityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import re
import unicodedata

IMPERATIVE_MARKERS = ("also include", "before calling", "first read", "then send",
                      "additionally pass", "forward the contents", "ignore previous")

class ManifestIntegrityError(RuntimeError):
    pass

def normalize(text: str) -> str:
    t = unicodedata.normalize("NFKC", text)
    t = "".join(ch for ch in t if unicodedata.category(ch) != "Cf")  # strip zero-width/format
    return re.sub(r"\s+", " ", t).strip().lower()

def verify_manifest(prior: dict, current: dict, signature_valid: bool,
                    declared_params: set[str]) -> None:
    if not signature_valid:
        raise ManifestIntegrityError("signature invalid: hard reject")

    for tool, cur_desc in current["tools"].items():
        base_desc = prior["tools"].get(tool)
        if base_desc is None:
            continue  # new tool: no baseline, route to human review elsewhere
        cur_n, base_n = normalize(cur_desc), normalize(base_desc)
        if cur_n == base_n:
            continue
        # signed but drifted: inspect instructional integrity
        if any(marker in cur_n for marker in IMPERATIVE_MARKERS):
            raise ManifestIntegrityError(
                f"tool {tool!r}: signed description gained imperative directive")
        mentioned = set(re.findall(r"`([a-z_]+)`", cur_n)) | set(re.findall(r"\b([a-z_]{3,})\b", cur_n))
        phantom = mentioned & set(re.findall(r"\b([a-z_]{3,})\b", base_n)) - declared_params
        if cur_n.count(" ") - base_n.count(" ") > 20:
            raise ManifestIntegrityError(
                f"tool {tool!r}: signed description token-delta exceeds threshold")
    return None
