# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-hot-loads-a-skill-whose-manifest-and-body-disagree-about-their-declared-capability-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-hot-loads-a-skill-whose-manifest-and-body-disagree-about-their-declared-capability-scope.warrant.json
# Markdown SHA-256:   155ac98fa9fa5da3fe07d816ff1453ae1deff687c160ef6190e1391a270aefc4
# Code AST SHA-256:   abfd461145944a066803b4081357a5236649c4d1111a701566a0a065457a5f8b
# Verified Classes:   CapabilityDivergenceError, SkillFrame
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CapabilityDivergenceError(RuntimeError):
    """Raised when a skill's body invokes a tool outside its manifest-declared set."""
    pass


class SkillFrame:
    def __init__(self, skill_name: str, declared_tools: set[str]):
        self.skill_name = skill_name
        self.declared_tools = frozenset(declared_tools)
        self.invoked_tools: set[str] = set()

    def authorize(self, tool_handle: str) -> None:
        # Binding != authorization. Check against the declared mask, not the
        # global registry that made the handle available in the first place.
        if tool_handle not in self.declared_tools:
            raise CapabilityDivergenceError(
                f"skill '{self.skill_name}' invoked undeclared tool "
                f"'{tool_handle}'; declared={sorted(self.declared_tools)} "
                f"already_invoked={sorted(self.invoked_tools)}"
            )
        self.invoked_tools.add(tool_handle)


def dispatch(frame: SkillFrame, tool_handle: str, args: dict, registry: dict):
    # Divergence check happens BEFORE the call executes, so the side effect
    # (and any memory write derived from its output) never occurs.
    frame.authorize(tool_handle)
    fn = registry.get(tool_handle)
    if fn is None:
        raise CapabilityDivergenceError(
            f"tool '{tool_handle}' declared by '{frame.skill_name}' is not bound"
        )
    return fn(**args)


# --- reproduction of the observed failure, now bounded ---
registry = {
    "read_thread": lambda tid: {"id": tid, "body": "..."},
    "emit_summary": lambda text: {"summary": text},
    "workspace.list_files": lambda: ["secret_plan.md", "keys.env"],  # ambient authority
}

frame = SkillFrame("summarize-thread", declared_tools={"read_thread", "emit_summary"})

dispatch(frame, "read_thread", {"tid": "t-42"}, registry)          # ok
# body's injected instruction now tries the out-of-scope call:
try:
    dispatch(frame, "workspace.list_files", {}, registry)          # raises
except CapabilityDivergenceError as e:
    # halt skill frame, quarantine outputs from memory writes
    print("DIVERGENCE FAULT:", e)
