# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-tool-poisoning-through-schema-drift-versus-benign-tool-evolution-and-where-behavioral-fingerprinting-fails-to-dis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-tool-poisoning-through-schema-drift-versus-benign-tool-evolution-and-where-behavioral-fingerprinting-fails-to-dis.warrant.json
# Markdown SHA-256:   a2b98d9ce404832222545042e32b329cd91f60b32aecee87abcec307ca628085
# Code AST SHA-256:   92f132fd70a14122282142a3b327acb8212d4535986896f8eeee99940ffda118
# Verified Classes:   FingerprintAttributionError, SchemaRevision, BehavioralFingerprint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import math
from dataclasses import dataclass, field
from typing import Callable


class FingerprintAttributionError(RuntimeError):
    """Raised when a fingerprint divergence cannot be attributed to schema changes
    and the residual exceeds the poisoning threshold."""


@dataclass
class SchemaRevision:
    schema_hash: str
    changed_elements: set[str]          # e.g. {"timezone", "notes.constraint"}
    description_embedding: list[float]


@dataclass
class BehavioralFingerprint:
    # axis name -> empirical frequency in [0,1]
    vector: dict[str, float] = field(default_factory=dict)
    seed: int = 0


def _cosine(a: list[float], b: list[float]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = math.sqrt(sum(x * x for x in a))
    nb = math.sqrt(sum(y * y for y in b))
    if na == 0 or nb == 0:
        return 0.0
    return dot / (na * nb)


def _axis_for_element(element: str) -> str:
    # map a schema element to the behavioral axis it should legitimately move
    return f"presence::{element.split('.')[0]}"


def compute_residual(
    baseline_fp: BehavioralFingerprint,
    current_fp: BehavioralFingerprint,
    changed_elements: set[str],
) -> float:
    """Residual = L1 divergence between fingerprints minus the projection onto
    axes attributable to the changed schema elements. Unattributed divergence
    is the poisoning signal."""
    axes = set(baseline_fp.vector) | set(current_fp.vector)
    total = 0.0
    attributed = 0.0
    attributable_axes = {_axis_for_element(e) for e in changed_elements}
    for axis in axes:
        delta = abs(
            current_fp.vector.get(axis, 0.0) - baseline_fp.vector.get(axis, 0.0)
        )
        total += delta
        if axis in attributable_axes:
            attributed += delta
    return max(0.0, total - attributed)


def evaluate_revision(
    pinned_baseline: BehavioralFingerprint,
    current_fp: BehavioralFingerprint,
    revision: SchemaRevision,
    residual_threshold: float,
    auto_repin: bool = False,
) -> str:
    """Evaluate a single tools/list refresh against the operator-pinned baseline.

    Returns 'accept' or 'quarantine'. Never auto-advances the baseline unless
    explicitly permitted, because auto-advance is exploitable by slow poisoning.
    """
    if auto_repin:
        raise FingerprintAttributionError(
            "auto_repin=True violates the cumulative-residual invariant; "
            "baseline advancement must be operator-gated"
        )

    residual = compute_residual(pinned_baseline, current_fp, revision.changed_elements)

    if residual > residual_threshold:
        raise FingerprintAttributionError(
            f"unattributed fingerprint residual {residual:.3f} exceeds "
            f"threshold {residual_threshold:.3f} for revision "
            f"{revision.schema_hash[:12]}; changed_elements="
            f"{sorted(revision.changed_elements)}; possible tool poisoning"
        )
    return "accept"


def cumulative_residual(
    pinned_baseline: BehavioralFingerprint,
    history: list[tuple[BehavioralFingerprint, SchemaRevision]],
    residual_threshold: float,
) -> float:
    """Slow-poisoning guard: evaluate each historical revision's fingerprint
    against the ORIGINAL pinned baseline, not against its predecessor."""
    worst = 0.0
    for fp, rev in history:
        r = compute_residual(pinned_baseline, fp, rev.changed_elements)
        worst = max(worst, r)
        if worst > residual_threshold:
            raise FingerprintAttributionError(
                f"cumulative residual {worst:.3f} exceeds threshold "
                f"{residual_threshold:.3f} at revision {rev.schema_hash[:12]}; "
                f"incremental poisoning suspected"
            )
    return worst
