# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-manifest-has-been-injected-with-capability-escalating-tool-descriptors.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-manifest-has-been-injected-with-capability-escalating-tool-descriptors.warrant.json
# Markdown SHA-256:   d6a41a50f365165a6bed27d3c25346397b1883e8b42b559659062f1dd382b185
# Code AST SHA-256:   56d7118e087902eecbbf473ffee939beff472c883960217dd94aec08aafc24cd
# Verified Classes:   CapabilityEscalationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json


class CapabilityEscalationError(RuntimeError):
    """Raised when a skill manifest mutates its capability surface after authorization."""
    pass


def _fingerprint(manifest: dict) -> str:
    # Bind only the safety-relevant surface, not description text.
    surface = {
        "params": sorted(manifest.get("parameters", {}).keys()),
        "scopes": sorted(manifest.get("required_scopes", [])),
        "side_effects": sorted(manifest.get("side_effects", [])),
    }
    return hashlib.sha256(json.dumps(surface, sort_keys=True).encode()).hexdigest()


def authorize(manifest: dict) -> dict:
    return {"tool_id": manifest["tool_id"], "schema_hash": _fingerprint(manifest)}


def invoke(manifest: dict, grant: dict, args: dict) -> object:
    if manifest["tool_id"] != grant["tool_id"]:
        raise CapabilityEscalationError("tool_id mismatch against authorization grant")
    current = _fingerprint(manifest)
    if current != grant["schema_hash"]:
        # Structural widening detected: refuse to honor the stale grant.
        raise CapabilityEscalationError(
            f"manifest surface changed after authorization "
            f"({grant['schema_hash'][:8]} -> {current[:8]}); re-authorization required"
        )
    # Safe to dispatch: schema bound to the approved contract.
    return dispatch(manifest, args)


def dispatch(manifest: dict, args: dict) -> object:  # placeholder for real tool runtime
    raise NotImplementedError
