# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-a-tool-registry-enforce-trust-boundaries-when-agent-skill-injection-crosses-the-marketplace-plugin-load-seam.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-a-tool-registry-enforce-trust-boundaries-when-agent-skill-injection-crosses-the-marketplace-plugin-load-seam.warrant.json
# Markdown SHA-256:   da240384e8a0cc43f6dad30b247fd66d2efd941c8af3be4a16c91cfa2feb8746
# Code AST SHA-256:   7983a22bd83d30adaf8c1bf2c355ef8476f69b1442378e94e242a8c01d2d0520
# Verified Classes:   SkillInjectionError, ResolutionKey, SkillGrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class SkillInjectionError(RuntimeError):
    """Raised when a resolved skill violates the authority invariant."""
    pass


@dataclass(frozen=True)
class ResolutionKey:
    namespace: str
    name: str
    publisher_id: str
    manifest_digest: str


@dataclass(frozen=True)
class SkillGrant:
    key: ResolutionKey
    capabilities: frozenset


RESERVED_NAMESPACES = frozenset({"core", "system"})


def resolve_skill(
    request_key: ResolutionKey,
    registry: Mapping,
    grants: Mapping,
    caller_capabilities: frozenset,
) -> SkillGrant:
    if request_key.namespace in RESERVED_NAMESPACES and request_key.publisher_id != "first-party":
        raise SkillInjectionError(
            f"publisher {request_key.publisher_id!r} attempted reserved namespace "
            f"{request_key.namespace!r} for tool {request_key.name!r}"
        )

    # Reject ambiguous resolution: exactly one registry entry per full key.
    matches = [
        entry for entry in registry.values()
        if (entry.namespace, entry.name) == (request_key.namespace, request_key.name)
    ]
    if len(matches) != 1:
        raise SkillInjectionError(
            f"ambiguous resolution for {request_key.namespace}/{request_key.name}: "
            f"{len(matches)} candidates; refusing last-writer-wins"
        )

    grant = grants.get(request_key)
    if grant is None:
        raise SkillInjectionError(
            f"no grant bound to manifest_digest {request_key.manifest_digest!r}; "
            "capability binding is stale or forged"
        )

    if not grant.capabilities.issubset(caller_capabilities):
        raise SkillInjectionError(
            f"skill {request_key.namespace}/{request_key.name} requests capabilities "
            f"{sorted(grant.capabilities - caller_capabilities)} not held by caller"
        )

    return grant
