# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-manifest-tampered-mcp-tools-when-the-poisoned-description-is-semantically-indistinguishable-from-the-legitimate-one-at-the.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-manifest-tampered-mcp-tools-when-the-poisoned-description-is-semantically-indistinguishable-from-the-legitimate-one-at-the.warrant.json
# Markdown SHA-256:   bcd47d2d1caf17348f38efd10f0c0a574689b17a70ca52ef926c9d88c48e95f2
# Code AST SHA-256:   88f71b280727cc4756189283afb06acd1c99f3ddf2ddee60f082560556530170
# Verified Classes:   ManifestContractViolation, ToolManifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass


class ManifestContractViolation(RuntimeError):
    """Raised when a refreshed tool description implies authority the schema cannot express."""


@dataclass(frozen=True)
class ToolManifest:
    name: str
    description: str
    input_schema: dict

    @property
    def digest(self) -> str:
        h = hashlib.sha256()
        h.update(self.name.encode())
        h.update(self.description.encode())
        h.update(repr(sorted(self.input_schema.items())).encode())
        return h.hexdigest()


# Clauses that smuggle conditional/imperative authority into a description.
AUTHORITY_CLAUSE = re.compile(
    r"\b(when|if|always|also|prepend|append|additionally|"
    r"before returning|after reading|for (the )?(caller|auditor|admin))\b",
    re.IGNORECASE,
)


def _schema_parameterizes(clause: str, schema: dict) -> bool:
    """A clause is schema-backed only if a declared field names its target."""
    fields = set((schema.get("properties") or {}).keys())
    lowered = clause.lower()
    return any(f.lower() in lowered for f in fields)


def validate_refresh(
    cached: ToolManifest,
    incoming: ToolManifest,
    pinned_digests: set[str],
) -> ToolManifest:
    if incoming.digest in pinned_digests:
        return incoming  # out-of-band signed manifest wins

    if incoming.input_schema != cached.input_schema:
        # Schema change is a legitimate, machine-checkable event; accept and re-pin.
        return incoming

    if incoming.description == cached.description:
        return incoming  # no-op refresh

    # Description-only change: every authority clause must be schema-backed.
    for clause in AUTHORITY_CLAUSE.finditer(incoming.description):
        window = incoming.description[clause.start(): clause.start() + 120]
        if not _schema_parameterizes(window, incoming.input_schema):
            raise ManifestContractViolation(
                f"Tool {incoming.name!r} refresh rejected: description clause "
                f"{window!r} implies behavior not expressible in input schema "
                f"{sorted((incoming.input_schema.get('properties') or {}).keys())}. "
                f"Retaining cached manifest {cached.digest[:12]}."
            )

    return incoming
