# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-rug-pull-skill-before-its-manifest-mutation-poisons-the-next-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-rug-pull-skill-before-its-manifest-mutation-poisons-the-next-tool-call.warrant.json
# Markdown SHA-256:   9c27d6edf052f95905ac41ed3776d215453a5faa82168a908a779deab5709f47
# Code AST SHA-256:   2635d1103784d7fdd7ab4102500ace0c72113f70178e189df952b074ebabe0e6
# Verified Classes:   ManifestMutationError, ToolDescriptor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestMutationError(RuntimeError):
    """Raised when a tool's live manifest digest diverges from the digest the planner reasoned over."""
    pass


@dataclass(frozen=True)
class ToolDescriptor:
    name: str
    description: str
    input_schema: dict

    def digest(self) -> str:
        canonical = json.dumps(
            {"name": self.name,
             "description": self.description,
             "input_schema": self.input_schema},
            sort_keys=True, separators=(",", ":"),
        )
        return hashlib.sha256(canonical.encode()).hexdigest()


def invoke_tool(planned: ToolDescriptor,
                live: ToolDescriptor,
                args: dict,
                effect_class: str) -> dict:
    """Execute a tool call only if the live contract matches the planned contract."""
    if planned.digest() != live.digest():
        raise ManifestMutationError(
            f"tool {planned.name!r} mutated between planning and invocation: "
            f"planned={planned.digest()[:12]} live={live.digest()[:12]}"
        )
    if effect_class != "read-only":
        # Non-idempotent tools must be re-validated at the call boundary,
        # not trusted from a cached snapshot.
        if set(args) - set(live.input_schema.get("properties", {})):
            raise ManifestMutationError(
                f"args {set(args)} not covered by live schema for {live.name!r}"
            )
    return _execute(live, args)


def _execute(descriptor: ToolDescriptor, args: dict) -> dict:
    # Placeholder for the sandboxed transport call.
    return {"ok": True, "tool": descriptor.name}
