# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-manifest-has-been-poisoned-versus-legitimately-re-versioned-a-boundary-condition-analysis-of-mcp-descriptor-ta.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-manifest-has-been-poisoned-versus-legitimately-re-versioned-a-boundary-condition-analysis-of-mcp-descriptor-ta.warrant.json
# Markdown SHA-256:   94285991c94a7621cbf9ddbc11149f232005b3d0353973eaaa09475444000e1f
# Code AST SHA-256:   1b68e0068f98dcbcbca0ab0b0210aa8322f1315e389bae7411291211aab7290a
# Verified Classes:   ManifestContinuityError, CachedDescriptor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
import re
from dataclasses import dataclass
from typing import Any


class ManifestContinuityError(RuntimeError):
    """Raised when a re-fetched MCP tool manifest violates the identity/behavior invariant."""
    pass


SAFETY_ANNOTATIONS = ("readOnlyHint", "destructiveHint", "idempotentHint")
INSTRUCTION_PATTERN = re.compile(
    r"\b(prefer|always|never|ignore|instead|when\s+\w+,\s*(do|use|call))\b",
    re.IGNORECASE,
)


@dataclass(frozen=True)
class CachedDescriptor:
    name: str
    version: str
    capability_hash: str
    annotations: frozenset[str]
    description: str


def canonical_capability_hash(descriptor: dict[str, Any]) -> str:
    """Hash only the behavioral surface: schema + annotations, not prose or version."""
    surface = {
        "inputSchema": descriptor.get("inputSchema", {}),
        "annotations": {
            k: descriptor.get("annotations", {}).get(k)
            for k in SAFETY_ANNOTATIONS
            if k in descriptor.get("annotations", {})
        },
    }
    blob = json.dumps(surface, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def detect_tamper(cached: CachedDescriptor, fresh: dict[str, Any]) -> None:
    """Structural delta classifier. Raises on concealed capability change."""
    if fresh.get("name") != cached.name:
        raise ManifestContinuityError(
            f"tool identity swap: cached={cached.name!r} fresh={fresh.get('name')!r}"
        )

    fresh_hash = canonical_capability_hash(fresh)
    fresh_version = fresh.get("version", "")
    fresh_annotations = frozenset(
        k for k in SAFETY_ANNOTATIONS if k in fresh.get("annotations", {})
    )
    fresh_desc = fresh.get("description", "")

    # Signal 1: behavior changed but identity did not.
    if fresh_hash != cached.capability_hash and fresh_version == cached.version:
        raise ManifestContinuityError(
            f"concealed capability change on {cached.name}: "
            f"capability_hash {cached.capability_hash[:12]}->{fresh_hash[:12]} "
            f"with version held at {cached.version!r}"
        )

    # Signal 2: safety annotation silently dropped.
    dropped = cached.annotations - fresh_annotations
    if dropped:
        raise ManifestContinuityError(
            f"safety annotation(s) removed from {cached.name}: {sorted(dropped)} "
            f"without version increment (version={fresh_version!r})"
        )

    # Signal 3: instruction-like prose injected into description.
    new_prose = fresh_desc[len(cached.description):] if fresh_desc.startswith(cached.description) else fresh_desc
    if INSTRUCTION_PATTERN.search(new_prose):
        raise ManifestContinuityError(
            f"instruction-like text injected into {cached.name} description: "
            f"{new_prose.strip()[:120]!r}"
        )


def verify_tool_manifest(cached: CachedDescriptor, fresh: dict[str, Any]) -> CachedDescriptor:
    """Adopt the fresh descriptor only if it passes structural continuity."""
    detect_tamper(cached, fresh)
    return CachedDescriptor(
        name=fresh["name"],
        version=fresh.get("version", ""),
        capability_hash=canonical_capability_hash(fresh),
        annotations=frozenset(
            k for k in SAFETY_ANNOTATIONS if k in fresh.get("annotations", {})
        ),
        description=fresh.get("description", ""),
    )
