# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-dynamically-loaded-skill-whose-declared-capability-envelope-silently-widens-at-registration-time.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-dynamically-loaded-skill-whose-declared-capability-envelope-silently-widens-at-registration-time.warrant.json
# Markdown SHA-256:   c721ef7c7b33b12ae0443c34a884b009340718bcb54643340f835cb953fb950b
# Code AST SHA-256:   3a37d9453461a1ca35293234c70d8885c2e8ce03a55c56c5fb9675baccbb7ee8
# Verified Classes:   CapabilityEnvelopeMismatch, BoundTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class CapabilityEnvelopeMismatch(RuntimeError):
    """Raised when a skill's bound dispatch surface diverges from its manifest."""


@dataclass(frozen=True)
class BoundTool:
    name: str
    arg_signature: str          # normalized, includes defaults
    scope: str
    side_effect_class: str


def _normalize(tools) -> FrozenSet[BoundTool]:
    return frozenset(tools)


def bind_skill(
    manifest_tools: FrozenSet[BoundTool],
    module_exports: FrozenSet[BoundTool],
    live_table: FrozenSet[BoundTool],
    *,
    allow_readonly_additive: bool = False,
) -> FrozenSet[BoundTool]:
    """
    Enforce: bound surface == declared surface, and declared surface
    accounts for any live bindings retained from a prior load.
    """
    declared = _normalize(manifest_tools)
    bound = _normalize(module_exports)
    # Merge semantics: hot-reload must not silently retain dropped tools.
    effective_bound = bound | live_table

    undeclared = effective_bound - declared
    unbound = declared - effective_bound

    if undeclared or unbound:
        # Quarantine path: purely additive, read-only, side-effect-free deltas
        # may be loaded but marked non-dispatchable pending re-sign.
        additive_only = (
            allow_readonly_additive
            and not unbound
            and all(
                t.side_effect_class == "none" and t.scope == "read"
                for t in undeclared
            )
        )
        if additive_only:
            return declared  # expose only the sanctioned surface

        raise CapabilityEnvelopeMismatch(
            f"skill envelope divergence: "
            f"undeclared_bound={sorted(t.name for t in undeclared)} "
            f"declared_unbound={sorted(t.name for t in unbound)}"
        )

    return declared


def resume_plan(plan_tool_names, live_declared: FrozenSet[BoundTool]) -> None:
    """A resumed checkpoint must not dispatch tools outside the live manifest."""
    sanctioned = {t.name for t in live_declared}
    stale = [n for n in plan_tool_names if n not in sanctioned]
    if stale:
        raise CapabilityEnvelopeMismatch(
            f"checkpointed plan references tools no longer declared: {stale}"
        )
