# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-hot-loads-a-toolkit-skill-that-shadows-its-own-permission-checking-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-hot-loads-a-toolkit-skill-that-shadows-its-own-permission-checking-tool.warrant.json
# Markdown SHA-256:   cc161db1f9d14589c1d5a06332b12501a75539a6071274281b60c86a21c51402
# Code AST SHA-256:   e0093d5880e3089e88b35f1aa2b30655574f352e34f84259b5a8999e5502ae41
# Verified Classes:   PolicyNamespaceViolation, ProvenanceMismatch, ToolBinding, ToolRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Literal

Provenance = Literal["system", "plugin"]

RESERVED_POLICY_PREFIXES = ("check_", "verify_", "authorize_", "policy_")


class PolicyNamespaceViolation(RuntimeError):
    """Raised when an untrusted-provenance skill attempts to occupy a reserved policy name."""


class ProvenanceMismatch(RuntimeError):
    """Raised when a policy-shaped result arrives from a non-system source."""


@dataclass(frozen=True)
class ToolBinding:
    name: str
    provenance: Provenance
    fn: Callable[[dict], dict]


class ToolRegistry:
    def __init__(self) -> None:
        self._tools: dict[str, ToolBinding] = {}

    def register(self, binding: ToolBinding) -> None:
        # Admission boundary: reserved policy names are system-only.
        if binding.provenance != "system" and binding.name.startswith(RESERVED_POLICY_PREFIXES):
            raise PolicyNamespaceViolation(
                f"skill from provenance={binding.provenance!r} attempted to register "
                f"reserved policy tool {binding.name!r}; rejected at admission"
            )
        # Last-writer-wins is permitted ONLY within the same provenance tier.
        existing = self._tools.get(binding.name)
        if existing and existing.provenance != binding.provenance:
            raise PolicyNamespaceViolation(
                f"cross-provenance shadowing of {binding.name!r} "
                f"({existing.provenance} -> {binding.provenance}) refused"
            )
        self._tools[binding.name] = binding

    def resolve_policy_tool(self, name: str) -> ToolBinding:
        binding = self._tools.get(name)
        if binding is None:
            raise ProvenanceMismatch(f"policy tool {name!r} not registered")
        if binding.provenance != "system":
            raise ProvenanceMismatch(
                f"policy tool {name!r} resolved to provenance={binding.provenance!r}; "
                "policy decisions must originate from system tier"
            )
        return binding


def authorize_and_execute(
    registry: ToolRegistry,
    capability: ToolBinding,
    request: dict,
    policy_tool_name: str = "check_permission",
) -> dict:
    # Dispatcher-side gate: the agent cannot address or shadow this path.
    checker = registry.resolve_policy_tool(policy_tool_name)
    verdict = checker.fn(request)
    if verdict.get("source") != "system":
        raise ProvenanceMismatch(
            f"policy verdict for {request!r} carried source={verdict.get('source')!r}; "
            "refusing to trust a non-system authorization"
        )
    if not verdict.get("allowed", False):
        raise PermissionError(f"denied by {policy_tool_name}: {verdict.get('reason')}")
    return capability.fn(request)
