# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-loads-a-skill-from-a-live-registry-whose-manifest-hash-was-re-signed-between-negotiation-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-loads-a-skill-from-a-live-registry-whose-manifest-hash-was-re-signed-between-negotiation-and-invocation.warrant.json
# Markdown SHA-256:   9e0256006972b75ca47f387bc6c9a60fec04fea845cd91076c34408a36c9d9c5
# Code AST SHA-256:   3bf8d02197a4c0bb84d874f7e9b1c655234f9701231b7dbb4eaecf36c9a0ad68
# Verified Classes:   ScopeEscalationError, Manifest, DispatchEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeEscalationError(RuntimeError):
    """Raised when a live skill manifest grants scope the plan never authorized."""


@dataclass(frozen=True)
class Manifest:
    skill_id: str
    content_hash: str
    scope: FrozenSet[str]
    side_effects: FrozenSet[str]


@dataclass(frozen=True)
class DispatchEnvelope:
    """What the planner actually authorized, frozen at plan time."""
    skill_id: str
    pinned_hash: str
    authorized_scope: FrozenSet[str]
    authorized_side_effects: FrozenSet[str] = field(default_factory=frozenset)


def dispatch(envelope: DispatchEnvelope, live: Manifest, *, revalidate: bool) -> Manifest:
    """
    Resolve a skill call against the live registry.

    revalidate=False reproduces the vulnerable resolve-by-ID path: the pinned
    hash is advisory and a widened manifest is served silently. revalidate=True
    enforces the invariant that declared scope may not exceed authorized scope.
    """
    if live.skill_id != envelope.skill_id:
        raise ScopeEscalationError(
            f"id mismatch: envelope={envelope.skill_id!r} live={live.skill_id!r}"
        )

    if not revalidate:
        # Vulnerable path: hash ignored, widened scope passes through.
        return live

    # Pin-and-fail: a different content hash is a different contract.
    if live.content_hash != envelope.pinned_hash:
        raise ScopeEscalationError(
            f"manifest drift for {live.skill_id!r}: "
            f"pinned={envelope.pinned_hash} live={live.content_hash}; re-plan required"
        )

    widened_scope = live.scope - envelope.authorized_scope
    widened_effects = live.side_effects - envelope.authorized_side_effects
    if widened_scope or widened_effects:
        raise ScopeEscalationError(
            f"scope escalation for {live.skill_id!r}: "
            f"unauthorized_scope={sorted(widened_scope)} "
            f"unauthorized_side_effects={sorted(widened_effects)}"
        )
    return live
