# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-an-mcp-tool-description-that-mutated-after-attestation-the-silent-schema-drift-window-between-capability-signing.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-an-mcp-tool-description-that-mutated-after-attestation-the-silent-schema-drift-window-between-capability-signing.warrant.json
# Markdown SHA-256:   b5d96bce2b2fc5e7f7ea574f44339b0090490434b12bf8d195cdf487249e0ae0
# Code AST SHA-256:   db625cfbc1e30eb3bc8c73e90ffc2e702c3495bd5ecb4af9befe18c692085411
# Verified Classes:   ManifestDriftError, AttestationMismatchError, ConditionedTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class ManifestDriftError(RuntimeError):
    """Raised when the manifest a planner was conditioned on no longer
    matches the manifest the server is enforcing at dispatch time."""


class AttestationMismatchError(RuntimeError):
    """Raised when the signature does not cover the manifest bytes."""


def canonical_manifest_hash(manifest: dict[str, Any]) -> str:
    # Canonical JSON: sorted keys, no whitespace, UTF-8. Must match the
    # server's canonicalization exactly or every call will false-positive.
    blob = json.dumps(manifest, sort_keys=True, separators=(",", ":"),
                      ensure_ascii=False).encode("utf-8")
    return "sha256:" + hashlib.sha256(blob).hexdigest()


@dataclass(frozen=True)
class ConditionedTool:
    name: str
    description: str
    input_schema: dict[str, Any]
    annotations: dict[str, Any]
    manifest_hash: str


def dispatch_tool_call(
    conditioned: ConditionedTool,
    live_manifest: dict[str, Any],
    arguments: dict[str, Any],
) -> dict[str, Any]:
    live_hash = canonical_manifest_hash(live_manifest)

    # 1. Bind the conditioned manifest to the live one BEFORE dispatch.
    #    A description-only or annotation-only drift is still a hard stop:
    #    the planner reasoned over the old bytes and the server enforces
    #    the new ones.
    if live_hash != conditioned.manifest_hash:
        raise ManifestDriftError(
            f"manifest drift for tool {conditioned.name!r}: "
            f"conditioned={conditioned.manifest_hash} live={live_hash}; "
            f"planner context is stale, invalidate session and re-condition"
        )

    # 2. Re-resolve the tool from the live manifest (not the cached copy)
    #    so schema validation runs against enforced bytes.
    live_tools = {t["name"]: t for t in live_manifest.get("tools", [])}
    live_tool = live_tools.get(conditioned.name)
    if live_tool is None:
        raise ManifestDriftError(
            f"tool {conditioned.name!r} absent from live manifest"
        )

    # 3. Validate arguments against the enforced schema. If the schema
    #    relaxed (pattern removed), this will NOT catch the escape --
    #    which is exactly why step 1 must run first.
    path = arguments.get("path")
    pattern = (
        live_tool.get("inputSchema", {})
        .get("properties", {})
        .get("path", {})
        .get("pattern")
    )
    if pattern is not None and path is not None:
        import re
        if not re.match(pattern, path):
            raise AttestationMismatchError(
                f"path {path!r} violates enforced pattern {pattern!r}"
            )

    return {"status": "dispatched", "manifest_hash": live_hash,
            "tool": conditioned.name, "arguments": arguments}


def replay_transcript(transcript: list[dict[str, Any]],
                      live_manifest: dict[str, Any]) -> list[str]:
    """Auditor replay: returns deterministic drift errors instead of
    misattributing divergence to agent nondeterminism."""
    errors: list[str] = []
    for step in transcript:
        try:
            dispatch_tool_call(step["conditioned"], live_manifest,
                               step["arguments"])
        except ManifestDriftError as exc:
            errors.append(f"step {step['index']}: {exc}")
    return errors
