# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-mid-session-mcp-manifest-mutation-that-preserves-name-but-changes-inputschema-arity.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-mid-session-mcp-manifest-mutation-that-preserves-name-but-changes-inputschema-arity.warrant.json
# Markdown SHA-256:   6371ceea49581bae08080e4f446f4a7f480f78dcf715ca78c5b9aa637bd43e34
# Code AST SHA-256:   dbb09bc681972e476e6c39db7270611b6242551714f1aadfe5499ea813eb0fa6
# Verified Classes:   ManifestDriftError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class ManifestDriftError(RuntimeError):
    """Raised when a tool's inputSchema digest changes under a stable name."""


def _canonical(schema: dict[str, Any]) -> str:
    # Sorted keys + no whitespace so key reordering does not fake drift.
    return json.dumps(schema, sort_keys=True, separators=(",", ":"))


def schema_digest(tool: dict[str, Any]) -> str:
    return hashlib.sha256(_canonical(tool["inputSchema"]).encode()).hexdigest()


def detect_drift(
    cached: dict[str, dict[str, Any]],
    live: dict[str, dict[str, Any]],
    *,
    refetch_budget: dict[str, int],
    max_refetch: int = 2,
) -> dict[str, str]:
    """Return {tool_name: 'drift'|'stable'|'gone'} for every cached tool.

    Raises ManifestDriftError only when drift is detected on a tool whose
    re-fetch budget is already exhausted -- that is the point at which the
    agent must abort the task rather than re-plan again.
    """
    report: dict[str, str] = {}
    for name, cached_tool in cached.items():
        if name not in live:
            report[name] = "gone"
            continue
        if schema_digest(cached_tool) == schema_digest(live[name]):
            report[name] = "stable"
            continue
        report[name] = "drift"
        used = refetch_budget.get(name, 0)
        if used >= max_refetch:
            raise ManifestDriftError(
                f"tool {name!r} schema drift persisted across {used} re-fetches; "
                f"cached={schema_digest(cached_tool)[:12]} "
                f"live={schema_digest(live[name])[:12]} -- aborting task"
            )
        refetch_budget[name] = used + 1
    return report


def attribute_invalid_params(
    error_message: str,
    cached_schema: dict[str, Any],
) -> str:
    """Decide whether a -32602 is drift or agent error.

    Returns 'drift' | 'agent_error' | 'ambiguous'.
    """
    props = set(cached_schema.get("properties", {}))
    for token in error_message.replace("'", " ").split():
        if token in props:
            # Property exists in our cache -> we sent a bad value, not a stale schema.
            return "agent_error"
        if token and token[0].isalpha() and token not in props and token not in {
            "required", "property", "missing", "invalid", "params", "type", "value"
        }:
            # A named property we do not know about -> schema moved under us.
            return "drift"
    return "ambiguous"
