# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-skill-manifest-whose-capability-declaration-diverges-from-its-runtime-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-skill-manifest-whose-capability-declaration-diverges-from-its-runtime-side-effects.warrant.json
# Markdown SHA-256:   760df18df8108f43526b81bb745a42e647009d95a17c54501ed3b5493c140680
# Code AST SHA-256:   20fc77a88e55e85b928d63f3e8ecf9baef0234718b85610906d64caab427df60
# Verified Classes:   CapabilityDivergence, Warrant, EffectEnvelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityDivergence(RuntimeError):
    """Raised when a tool's observed effect envelope exceeds its manifest warrant."""


@dataclass(frozen=True)
class Warrant:
    tool_name: str
    granted_effects: FrozenSet[str]
    sealed_at_load: bool = True


@dataclass
class EffectEnvelope:
    effects: set = field(default_factory=set)

    def observe(self, effect: str) -> None:
        self.effects.add(effect)


def invoke_tool(warrant: Warrant, envelope: EffectEnvelope, monitor_present: bool) -> str:
    # Tool body runs; envelope is populated by the synchronous monitor,
    # never by the tool itself.
    result = _run_tool_body()

    if not monitor_present:
        # No independent observation channel: the manifest is a hint, not a warrant.
        # We cannot accept a result whose effects are unverified under a grant.
        raise CapabilityDivergence(
            f"tool {warrant.tool_name!r} invoked without effect monitor; "
            "manifest annotations cannot authorize execution"
        )

    observed = frozenset(envelope.effects)
    if not observed.issubset(warrant.granted_effects):
        divergence = observed - warrant.granted_effects
        # Do not re-scope and continue. The manifest is falsified; quarantine.
        raise CapabilityDivergence(
            f"tool {warrant.tool_name!r} exceeded warrant: "
            f"unauthorized effects {sorted(divergence)}; "
            f"granted={sorted(warrant.granted_effects)}"
        )

    return result


def _run_tool_body() -> str:
    # Placeholder for the dynamically loaded skill body.
    return "summary generated"
