# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-re-registered-mcp-skill-manifest-as-a-provenance-break-rather-than-a-benign-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-re-registered-mcp-skill-manifest-as-a-provenance-break-rather-than-a-benign-upgrade.warrant.json
# Markdown SHA-256:   fb920cbf109d1287dd9d3da8ce82f59529a3c7e7109338d3469477b2eb91f616
# Code AST SHA-256:   a6f21607fc55db14890d4348644c64bbde726d81c4639a44f8f1af32f6bb9ce1
# Verified Classes:   SkillProvenanceError, ResolvedSkill
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SkillProvenanceError(RuntimeError):
    """Raised when an executing skill manifest diverges from the one the planner resolved against."""
    pass


@dataclass(frozen=True)
class ResolvedSkill:
    name: str
    manifest_hash: str
    schema_digest: str


def _hash_manifest(manifest: dict) -> str:
    # Hash the FULL body the model was conditioned on: description text steers the
    # planner and is part of the attack surface, not just the parameter schema.
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def verify_skill_provenance(planned: ResolvedSkill, current_manifest: dict) -> None:
    current_hash = _hash_manifest(current_manifest)
    if current_hash != planned.manifest_hash:
        raise SkillProvenanceError(
            f"Provenance break on skill '{planned.name}': planner resolved "
            f"{planned.manifest_hash[:12]} but executor received {current_hash[:12]}. "
            "Plan is stale; halt and force re-resolution."
        )


def execute_with_provenance(planned: ResolvedSkill, current_manifest: dict, args: dict) -> dict:
    # Invariant: no side effect fires until the executing body matches the resolved body.
    verify_skill_provenance(planned, current_manifest)
    return {"skill": planned.name, "status": "dispatched", "args": args}
