# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-capability-manifest-drift-that-smuggles-post-registration-skill-injection-into-a-plugin-registry.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-capability-manifest-drift-that-smuggles-post-registration-skill-injection-into-a-plugin-registry.warrant.json
# Markdown SHA-256:   96ccd4d65234ae29ffe922cf127761437f8ee322d19b3aa707d1d2fd08f802b3
# Code AST SHA-256:   80670302a3fd0140ea869816704df436b93f0256ede4760f10be415ffaef9a31
# Verified Classes:   CapabilityManifestDriftError, ToolContract
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityManifestDriftError(RuntimeError):
    """Raised when a dispatched tool call's live contract diverges from the
    contract the planner validated at discovery time."""
    pass


@dataclass(frozen=True)
class ToolContract:
    tool_name: str
    plugin_name: str
    schema: dict
    side_effect_class: str

    def schema_hash(self) -> str:
        canonical = json.dumps(
            {"schema": self.schema, "side_effect_class": self.side_effect_class},
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def validate_dispatch(
    planned: ToolContract,
    live_manifest: dict,
    *,
    allow_repin: bool = False,
) -> ToolContract:
    """Enforce the continuity invariant: planner-validated contract must be
    byte-identical to the executor-enforced contract, or the call is refused."""
    live_tools = {t["name"]: t for t in live_manifest.get("tools", [])}
    live_entry = live_tools.get(planned.tool_name)

    if live_entry is None:
        raise CapabilityManifestDriftError(
            f"tool {planned.tool_name!r} from plugin {planned.plugin_name!r} "
            f"disappeared from live manifest after admission"
        )

    # Missing side_effect_class is NOT defaulted — it is a drift signal.
    if "side_effect_class" not in live_entry:
        raise CapabilityManifestDriftError(
            f"tool {planned.tool_name!r} live manifest omitted side_effect_class; "
            f"refusing to default (attacker-controlled field)"
        )

    live_contract = ToolContract(
        tool_name=live_entry["name"],
        plugin_name=planned.plugin_name,
        schema=live_entry["schema"],
        side_effect_class=live_entry["side_effect_class"],
    )

    if live_contract.schema_hash() != planned.schema_hash():
        if not allow_repin:
            raise CapabilityManifestDriftError(
                f"schema drift on {planned.tool_name!r}: "
                f"planned={planned.schema_hash()[:12]} "
                f"live={live_contract.schema_hash()[:12]} — "
                f"refuse and re-plan, or pin and quarantine"
            )
        # Explicit re-admission path: caller has accepted the new contract.
        return live_contract

    # Name-collision guard: a late-registered tool must not shadow a trusted one.
    if live_entry.get("plugin_name") != planned.plugin_name:
        raise CapabilityManifestDriftError(
            f"name collision: {planned.tool_name!r} resolved to plugin "
            f"{live_entry.get('plugin_name')!r}, planned against {planned.plugin_name!r}"
        )

    return live_contract
