# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-dynamically-loaded-skill-whose-manifest-signature-is-valid-but-whose-declared-capability-surface-d.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-dynamically-loaded-skill-whose-manifest-signature-is-valid-but-whose-declared-capability-surface-d.warrant.json
# Markdown SHA-256:   a133f61d2376074f9a5cfc1725e4fca9a4d81b4289b8be2b6bda9584c3167773
# Code AST SHA-256:   3b585475d32abd19af05bdf64c87e71a37b22d8b9e3aed9254996d2b7bd33127
# Verified Classes:   CapabilityDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityDivergenceError(RuntimeError):
    """Raised when a skill invokes a tool outside its signed manifest surface."""
    pass


DECLARED_SURFACE = {
    "kb_summarizer@2.3.1": frozenset({"read_kb", "summarize_text", "emit_trace"}),
}
PROBATION_MIN_INVOCATIONS = 2
WRITE_CLASS = frozenset({"write_file", "delete_file", "spawn_subagent"})


def dispatch_tool_call(skill_id: str, tool: str, args: dict, invocation_index: int) -> dict:
    declared = DECLARED_SURFACE.get(skill_id)
    if declared is None:
        raise CapabilityDivergenceError(f"unknown skill {skill_id!r}: no manifest surface")

    # Deny-on-first-divergence: never execute an undeclared call, even on invocation 0.
    if tool not in declared:
        raise CapabilityDivergenceError(
            f"skill {skill_id!r} invoked undeclared tool {tool!r} "
            f"on invocation {invocation_index}; declared surface={sorted(declared)}"
        )

    # Probationary write/spawn calls are denied until the footprint is sampled.
    if tool in WRITE_CLASS and invocation_index < PROBATION_MIN_INVOCATIONS:
        raise CapabilityDivergenceError(
            f"skill {skill_id!r} requested write-class tool {tool!r} during probation "
            f"(invocation {invocation_index} < {PROBATION_MIN_INVOCATIONS}); quarantined"
        )

    return {"skill_id": skill_id, "tool": tool, "args": args, "status": "executed"}
