# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-manifest-it-has-already-successfully-invoked-the-post-handshake-capability-drift-window-in-mcp-server-supply-cha.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-manifest-it-has-already-successfully-invoked-the-post-handshake-capability-drift-window-in-mcp-server-supply-cha.warrant.json
# Markdown SHA-256:   df9594135d9d220b183c9e5e379034e2242e492b84634aa76c03b987c4c62bd6
# Code AST SHA-256:   f5e5cfc2bd0a9e14b5410bfe84d5d2c378a772fc75b9093b8de3ef8bcbd01851
# Verified Classes:   CapabilityDriftError, ToolBinding, DriftBoundedRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any


class CapabilityDriftError(RuntimeError):
    """Raised when a bound tool's behavior or manifest no longer matches its verified contract."""


@dataclass
class ToolBinding:
    name: str
    manifest_digest: str          # digest of the tools/list entry at bind time
    implementation_digest: str    # digest of the server artifact actually executing
    output_schema: dict[str, Any] | None
    declared_authority: str       # e.g. "path:/workspace"
    bound_at: datetime
    last_verified_at: datetime
    ttl: timedelta = field(default_factory=lambda: timedelta(minutes=5))


class DriftBoundedRegistry:
    def __init__(self) -> None:
        self._bindings: dict[str, ToolBinding] = {}

    def bind(self, binding: ToolBinding) -> None:
        self._bindings[binding.name] = binding

    def _digest(self, payload: Any) -> str:
        return hashlib.sha256(repr(payload).encode()).hexdigest()

    def invoke(
        self,
        name: str,
        args: dict[str, Any],
        fetch_manifest: callable,
        fetch_implementation_digest: callable,
        execute: callable,
    ) -> Any:
        binding = self._bindings.get(name)
        if binding is None:
            raise CapabilityDriftError(f"tool {name!r} is not bound")

        now = datetime.utcnow()

        # 1. TTL: trust does not outlive the window it was granted for.
        if now - binding.last_verified_at > binding.ttl:
            raise CapabilityDriftError(
                f"tool {name!r} binding stale: last verified "
                f"{binding.last_verified_at.isoformat()}, ttl {binding.ttl}"
            )

        # 2. Manifest re-verification: catch tools/list swaps under a stable identity.
        live_manifest_digest = self._digest(fetch_manifest(name))
        if live_manifest_digest != binding.manifest_digest:
            raise CapabilityDriftError(
                f"tool {name!r} manifest drifted: "
                f"{binding.manifest_digest[:12]} -> {live_manifest_digest[:12]}"
            )

        # 3. Implementation digest: catch behavior swaps under a stable manifest.
        live_impl_digest = fetch_implementation_digest(name)
        if live_impl_digest != binding.implementation_digest:
            raise CapabilityDriftError(
                f"tool {name!r} implementation drifted: "
                f"{binding.implementation_digest[:12]} -> {live_impl_digest[:12]}"
            )

        result = execute(name, args)

        # 4. Output contract: a response that violates its declared schema is an injection, not data.
        if binding.output_schema is not None:
            if not _matches_schema(result, binding.output_schema):
                raise CapabilityDriftError(
                    f"tool {name!r} returned payload violating outputSchema "
                    f"(possible tool_use injection in result)"
                )

        # 5. Result-side authority: check what came back, not just what was asked.
        if binding.declared_authority.startswith("path:"):
            root = binding.declared_authority.removeprefix("path:")
            for path in _extract_paths(result):
                if not path.startswith(root):
                    raise CapabilityDriftError(
                        f"tool {name!r} escaped declared authority {root!r}: {path!r}"
                    )

        binding.last_verified_at = now
        return result


def _matches_schema(payload: Any, schema: dict[str, Any]) -> bool:
    # Minimal structural check; production uses jsonschema.
    expected = schema.get("type")
    if expected == "object":
        return isinstance(payload, dict)
    if expected == "string":
        return isinstance(payload, str)
    return True


def _extract_paths(payload: Any) -> list[str]:
    if isinstance(payload, str):
        return [payload] if payload.startswith("/") else []
    if isinstance(payload, dict):
        return [v for v in payload.values() if isinstance(v, str) and v.startswith("/")]
    if isinstance(payload, list):
        return [p for item in payload for p in _extract_paths(item)]
    return []
