# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-drift-past-its-declared-capability-envelope-during-mid-session-skill-hot-swap-and-how-do-we-bound-the-leak.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-drift-past-its-declared-capability-envelope-during-mid-session-skill-hot-swap-and-how-do-we-bound-the-leak.warrant.json
# Markdown SHA-256:   a32c6af2d01c251c835014adf213f65dae6c9d48a49cb4e3d5645925ed8be78d
# Code AST SHA-256:   a5c12bf0782f85ca279e454bd9ac78976163932175969564c9d7b2728e7b266b
# Verified Classes:   CapabilityEnvelopeEscape, SkillScopedBroker
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class CapabilityEnvelopeEscape(RuntimeError):
    """Raised when a tool-call intent resolves to a capability outside the active skill's envelope."""
    pass


class SkillScopedBroker:
    """Enforces grants at call time, keyed by non-forgeable skill provenance."""

    def __init__(self, active_manifest: dict, schema_registry: dict, cache: dict):
        # active_manifest: {"skill_id": str, "grants": set[str]}
        # schema_registry: {tool_name: owning_skill_id}
        # cache: {key: {"payload": ..., "written_under_manifest": str}}
        self.active_manifest = active_manifest
        self.schema_registry = schema_registry
        self.cache = cache

    def _resolve_provenance(self, intent: dict) -> str:
        tool = intent.get("tool")
        claimed = intent.get("skill_id")
        owner = self.schema_registry.get(tool)
        # Provenance is inferred from the schema the model actually invoked,
        # never trusted from the model-supplied field alone.
        if owner is None:
            raise CapabilityEnvelopeEscape(
                f"intent invoked unregistered tool {tool!r}; no owning skill"
            )
        if claimed is not None and claimed != owner:
            raise CapabilityEnvelopeEscape(
                f"intent claims skill {claimed!r} but tool {tool!r} is owned by {owner!r}"
            )
        return owner

    def authorize(self, intent: dict) -> None:
        provenance = self._resolve_provenance(intent)
        if provenance != self.active_manifest["skill_id"]:
            # Default-deny: residue from a prior manifest is not a grant.
            raise CapabilityEnvelopeEscape(
                f"intent from skill {provenance!r} rejected; active manifest is "
                f"{self.active_manifest['skill_id']!r}"
            )
        grant = intent.get("grant")
        if grant not in self.active_manifest["grants"]:
            raise CapabilityEnvelopeEscape(
                f"grant {grant!r} not declared by active manifest "
                f"{self.active_manifest['skill_id']!r}"
            )

    def read_cache(self, key: str) -> object:
        entry = self.cache.get(key)
        if entry is None:
            return None
        if entry["written_under_manifest"] != self.active_manifest["skill_id"]:
            # A legal read resolving to a foreign-manifest payload is an escape.
            raise CapabilityEnvelopeEscape(
                f"cache key {key!r} was written under manifest "
                f"{entry['written_under_manifest']!r}; active is "
                f"{self.active_manifest['skill_id']!r}"
            )
        return entry["payload"]


def swap_skill(broker: SkillScopedBroker, incoming_manifest: dict, scratchpad: dict) -> SkillScopedBroker:
    """Hot-swap with mandatory quiesce/scrub/re-derive; refuse partial swaps."""
    if scratchpad.get("in_flight"):
        raise CapabilityEnvelopeEscape(
            "cannot hot-swap while intents are in flight; quiesce first"
        )
    # Scrub: evict schemas and namespace-clear scratchpad not owned by incoming manifest.
    for tool, owner in list(broker.schema_registry.items()):
        if owner != incoming_manifest["skill_id"]:
            del broker.schema_registry[tool]
    for k in list(scratchpad.keys()):
        if k != "in_flight":
            del scratchpad[k]
    return SkillScopedBroker(incoming_manifest, broker.schema_registry, broker.cache)
