# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reconciles-an-mcp-tool-manifest-against-a-behavioral-fingerprint-and-the-tool-surface-mutates-between-the-handshake-snap.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reconciles-an-mcp-tool-manifest-against-a-behavioral-fingerprint-and-the-tool-surface-mutates-between-the-handshake-snap.warrant.json
# Markdown SHA-256:   ec28442a1747cb80de82b234ffb6e6e5380778726110c45d2adfd77ad22deb63
# Code AST SHA-256:   ee4f6410c09d8af0c5e0fb95a515a0bc72b368804851c6dfd5a9cc40b7b163de
# Verified Classes:   TrustBoundaryError, ToolTrust, TrustRecord, DispatchRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class TrustBoundaryError(RuntimeError):
    """Raised when a tool dispatch would proceed on evidence that does not
    describe the live server instance and negotiation epoch."""


class ToolTrust(Enum):
    TRUSTED = "trusted"
    UNFINGERPRINTED = "unfingerprinted"
    DRIFTED = "drifted"
    CONTRADICTED = "contradicted"


@dataclass
class TrustRecord:
    manifest_hash_at_t0: str
    fingerprint_coverage: set[str] = field(default_factory=set)
    last_epoch_seen: str = ""


@dataclass
class DispatchRequest:
    tool_name: str
    args: dict[str, Any]
    live_manifest_hash: str
    live_epoch: str
    declared_annotations: dict[str, Any]
    observed_behavior: dict[str, Any] | None


def _hash_manifest(manifest: dict[str, Any]) -> str:
    return hashlib.sha256(
        json.dumps(manifest, sort_keys=True).encode()
    ).hexdigest()


def resolve_tool_trust(
    record: TrustRecord,
    req: DispatchRequest,
) -> ToolTrust:
    # Structural check: manifest must be unchanged AND epoch must match.
    if req.live_manifest_hash != record.manifest_hash_at_t0:
        return ToolTrust.DRIFTED
    if req.live_epoch != record.last_epoch_seen:
        return ToolTrust.DRIFTED

    # Behavioral check: if we never probed this tool, we cannot trust it.
    if req.tool_name not in record.fingerprint_coverage:
        return ToolTrust.UNFINGERPRINTED

    # Annotation contradiction: declared read-only but behavior wrote.
    if req.observed_behavior is not None:
        declared_ro = req.declared_annotations.get("readOnlyHint", False)
        observed_write = req.observed_behavior.get("side_effects", False)
        if declared_ro and observed_write:
            return ToolTrust.CONTRADICTED

    return ToolTrust.TRUSTED


def dispatch(
    record: TrustRecord,
    req: DispatchRequest,
    executor,
) -> Any:
    trust = resolve_tool_trust(record, req)

    if trust is ToolTrust.DRIFTED:
        raise TrustBoundaryError(
            f"tool {req.tool_name!r}: manifest/epoch drifted since "
            f"handshake (t0={record.manifest_hash_at_t0[:12]}, "
            f"live={req.live_manifest_hash[:12]}, "
            f"epoch {record.last_epoch_seen} -> {req.live_epoch}); "
            f"session must re-handshake and re-fingerprint before dispatch"
        )

    if trust is ToolTrust.CONTRADICTED:
        raise TrustBoundaryError(
            f"tool {req.tool_name!r}: behavioral fingerprint contradicts "
            f"declared annotation readOnlyHint=true but probe observed write; "
            f"quarantine server"
        )

    if trust is ToolTrust.UNFINGERPRINTED:
        # Restricted path: no side-effect annotations honored, output untrusted.
        return executor(req, restricted=True)

    return executor(req, restricted=False)
