# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-late-bound-skill-injection-through-mcp-tool-description-mutation-before-dispatch-authorization.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-late-bound-skill-injection-through-mcp-tool-description-mutation-before-dispatch-authorization.warrant.json
# Markdown SHA-256:   95b341d830aa8a8f3f5c76c3254c15ee81949babfa0ccd4e81b366e9e635cd04
# Code AST SHA-256:   ea918c96edad8d46d6fb00dd491ddd7d99fa1edec6bab46df175c02e2e058b67
# Verified Classes:   SkillInjectionError, ToolDeclaration, RegistryEpoch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class SkillInjectionError(RuntimeError):
    """Raised when a registry tool declaration drifts between authorization and dispatch."""


@dataclass(frozen=True)
class ToolDeclaration:
    name: str
    description: str
    schema: dict
    side_effect_class: str

    def manifest_hash(self) -> str:
        # The trust surface is name + description + schema + side-effect class.
        # Hashing only the schema is the field-asymmetry bug this guard closes.
        payload = json.dumps(
            {
                "name": self.name,
                "description": self.description,
                "schema": self.schema,
                "side_effect_class": self.side_effect_class,
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        return hashlib.sha256(payload).hexdigest()


@dataclass
class RegistryEpoch:
    declarations: dict = field(default_factory=dict)  # name -> ToolDeclaration
    authorized: dict = field(default_factory=dict)     # name -> manifest_hash
    epoch_hash: str = ""

    @staticmethod
    def _epoch_hash(decls: dict) -> str:
        joined = "|".join(
            f"{name}:{d.manifest_hash()}" for name, d in sorted(decls.items())
        )
        return hashlib.sha256(joined.encode("utf-8")).hexdigest()

    def authorize(self, decls: dict) -> None:
        self.declarations = dict(decls)
        self.authorized = {n: d.manifest_hash() for n, d in decls.items()}
        self.epoch_hash = self._epoch_hash(decls)

    def refresh(self, fresh: dict, plan_references_drift: bool) -> None:
        """Called on reconnect / compaction re-fetch of tools/list."""
        if self._epoch_hash(fresh) == self.epoch_hash:
            return  # no drift, fast path

        drifted = [
            name
            for name, d in fresh.items()
            if self.authorized.get(name) != d.manifest_hash()
        ]
        # Newly appearing tools are also drift: they were never authorized.
        drifted += [name for name in fresh if name not in self.authorized]

        if not drifted:
            # epoch hash changed but per-tool hashes match: only ordering/whitespace
            self.declarations = dict(fresh)
            self.epoch_hash = self._epoch_hash(fresh)
            return

        if plan_references_drift:
            # A name-based dispatch block cannot rescue a plan that already
            # consumed the drifted description. Invalidate the trace.
            raise SkillInjectionError(
                f"declaration drift on {drifted} after plan emission; "
                f"plan contaminated, require checkpoint-resume from pre-drift state"
            )

        raise SkillInjectionError(
            f"registry epoch drift on {drifted}; quarantine and re-authorize before dispatch"
        )


def dispatch(
    epoch: RegistryEpoch,
    tool_name: str,
    allowlist: set,
) -> ToolDeclaration:
    if tool_name not in epoch.declarations:
        raise SkillInjectionError(f"tool {tool_name!r} not present in authorized epoch")
    if tool_name not in allowlist:
        raise SkillInjectionError(
            f"tool {tool_name!r} blocked by dispatch allowlist (side-effect gate)"
        )
    decl = epoch.declarations[tool_name]
    if epoch.authorized.get(tool_name) != decl.manifest_hash():
        raise SkillInjectionError(
            f"tool {tool_name!r} manifest hash mismatch at dispatch — refusing to bind"
        )
    return decl
