# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-post-registration-skill-mutation-in-a-dynamically-loaded-tool-registry-before-it-dispatches-a-poisoned-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-post-registration-skill-mutation-in-a-dynamically-loaded-tool-registry-before-it-dispatches-a-poisoned-call.warrant.json
# Markdown SHA-256:   345b00ec009c887adebe6aab8b6d4b0e9fb3deee54223fcccd3d32388845fc24
# Code AST SHA-256:   f1e011875d8df09432ae21e29e2af823e043c28279e119a6a69ba0bee460e358
# Verified Classes:   SkillMutationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json


class SkillMutationError(RuntimeError):
    """Raised when a skill's live schema digest diverges from its admitted digest."""
    pass


def canonical_digest(schema: dict) -> str:
    # Canonical form MUST include every field the model or executor reads,
    # including the natural-language description. Omitting prose here is the
    # classic canonicalization bug that re-opens the injection surface.
    canonical = json.dumps(
        {
            "name": schema["name"],
            "description": schema.get("description", ""),
            "parameters": schema.get("parameters", {}),
            "returns": schema.get("returns", {}),
        },
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
    )
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def dispatch_tool_call(admitted_state: dict, live_schema: dict, args: dict):
    name = live_schema["name"]
    admitted = admitted_state.get(name)
    if admitted is None:
        raise SkillMutationError(
            f"skill {name!r} was never admitted; refusing dispatch"
        )

    live_digest = canonical_digest(live_schema)
    if live_digest != admitted["digest"]:
        # Fail closed. Do NOT patch the plan; invalidate it and re-admit.
        raise SkillMutationError(
            f"skill {name!r} mutated post-admission: "
            f"admitted={admitted['digest'][:12]} live={live_digest[:12]} "
            f"(version string {live_schema.get('version')!r} is advisory only)"
        )

    # Only reached when digest equality holds.
    return {"skill": name, "args": args, "digest": live_digest}
