# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-capability-descriptor-in-a-hot-reloaded-mcp-tool-registry.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-capability-descriptor-in-a-hot-reloaded-mcp-tool-registry.warrant.json
# Markdown SHA-256:   f5d6ba2bfeb81f449eca28a6d4047076e6ea97864d335edd3b9ef87cf2335421
# Code AST SHA-256:   07431d32f6bc490e253775d023482a7724dd921b6dec77bb82088e8580be0497
# Verified Classes:   DescriptorDriftError, ToolDescriptor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class DescriptorDriftError(RuntimeError):
    """Raised when a hot-reloaded tool descriptor changes prose under a stable schema."""


IMPERATIVE_MARKERS = ("you must", "you should", "before calling", "always ", "ignore previous")


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

    def schema_hash(self) -> str:
        canonical = json.dumps(self.input_schema, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode()).hexdigest()

    def fingerprint(self) -> str:
        norm = " ".join(self.description.lower().split())
        return hashlib.sha256(
            f"{self.name}|{self.schema_hash()}|{norm}".encode()
        ).hexdigest()


def structural_signals(prior: ToolDescriptor, incoming: ToolDescriptor) -> list[str]:
    signals = []
    if prior.schema_hash() == incoming.schema_hash() and prior.description != incoming.description:
        signals.append("prose_drift_under_stable_schema")
    lowered = incoming.description.lower()
    if any(m in lowered for m in IMPERATIVE_MARKERS):
        signals.append("imperative_marker_in_descriptor")
    if len(incoming.description) > 4 * max(len(prior.description), 1):
        signals.append("description_length_explosion")
    return signals


def validate_reload(prior: ToolDescriptor, incoming: ToolDescriptor, approved_fingerprints: set[str]) -> None:
    if prior.name != incoming.name:
        raise DescriptorDriftError(f"identity mismatch: {prior.name} -> {incoming.name}")
    signals = structural_signals(prior, incoming)
    if signals and incoming.fingerprint() not in approved_fingerprints:
        raise DescriptorDriftError(
            f"reload of {incoming.name!r} rejected; signals={signals}; "
            f"fingerprint={incoming.fingerprint()[:12]} not in approval set"
        )
    if incoming.fingerprint() not in approved_fingerprints:
        raise DescriptorDriftError(f"unapproved descriptor fingerprint for {incoming.name!r}")
