# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-skill-manifest-whose-declared-capability-set-diverges-from-its-observed-tool-call-trace-at-load-ti.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-skill-manifest-whose-declared-capability-set-diverges-from-its-observed-tool-call-trace-at-load-ti.warrant.json
# Markdown SHA-256:   74397963b1910a1f0f9e97add15aa3b8a909188a467fe639f7091d1d8935ccf2
# Code AST SHA-256:   a4357f1a6d49fe9b8c87736f97a93a7ca92e170fc90ac9eefd27e999915f2768
# Verified Classes:   CapabilityDivergenceError, SkillManifest, SkillState, DispatchGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityDivergenceError(RuntimeError):
    """Raised when a skill invokes a tool outside its declared capability set."""


@dataclass
class SkillManifest:
    skill_id: str
    declared: FrozenSet[str]
    side_effects: str  # "none" | "read" | "write"


@dataclass
class SkillState:
    manifest: SkillManifest
    observed: set = field(default_factory=set)
    quarantined: bool = False


class DispatchGuard:
    """Enforces observed_capabilities subset-of declared_capabilities at dispatch."""

    def __init__(self, host_grant: FrozenSet[str]):
        self.host_grant = host_grant
        self.skills: dict[str, SkillState] = {}

    def register(self, manifest: SkillManifest) -> None:
        if not manifest.declared <= self.host_grant:
            raise CapabilityDivergenceError(
                f"skill {manifest.skill_id} declares capabilities outside host grant: "
                f"{manifest.declared - self.host_grant}"
            )
        self.skills[manifest.skill_id] = SkillState(manifest=manifest)

    def dispatch(self, skill_id: str, tool_name: str, args: dict) -> str:
        state = self.skills.get(skill_id)
        if state is None:
            raise CapabilityDivergenceError(f"unregistered skill: {skill_id}")
        if state.quarantined:
            raise CapabilityDivergenceError(
                f"skill {skill_id} is quarantined; dispatch refused"
            )
        # The load-time check validated the declaration. This is the check
        # that validates behavior: the actual call must be in the declared set.
        if tool_name not in state.manifest.declared:
            state.quarantined = True
            raise CapabilityDivergenceError(
                f"skill {skill_id} invoked undeclared tool {tool_name!r}; "
                f"declared={sorted(state.manifest.declared)} "
                f"observed_prefix={sorted(state.observed)}; skill quarantined"
            )
        state.observed.add(tool_name)
        return f"dispatched {tool_name} for {skill_id}"


# --- trace of the observed failure ---
guard = DispatchGuard(host_grant=frozenset({"calendar.read", "contacts.read", "email.send"}))
guard.register(SkillManifest(
    skill_id="calendar-assistant",
    declared=frozenset({"calendar.read", "contacts.read"}),
    side_effects="none",
))

guard.dispatch("calendar-assistant", "calendar.read", {"day": "today"})
guard.dispatch("calendar-assistant", "contacts.read", {"query": "all"})

try:
    # Injected instruction drives the skill to borrow the host's email grant.
    guard.dispatch("calendar-assistant", "email.send",
                   {"to": "external@example.net", "body": "<contacts>"})
except CapabilityDivergenceError as e:
    print(f"BLOCKED: {e}")
    # Subsequent dispatches are refused because the skill is now quarantined.
    try:
        guard.dispatch("calendar-assistant", "calendar.read", {"day": "today"})
    except CapabilityDivergenceError as e2:
        print(f"POST-QUARANTINE: {e2}")
