# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-dynamically-loaded-agent-skill-whose-manifest-declares-capabilities-the-host-cannot-independently-veri.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-dynamically-loaded-agent-skill-whose-manifest-declares-capabilities-the-host-cannot-independently-veri.warrant.json
# Markdown SHA-256:   d9f7ba390d880d58072349fa9f1898cb4b2a0f6addcb2b7d0175ac1a0ef441de
# Code AST SHA-256:   7f6bd6697c126a41252c40ca3da7585b85c2dc7e3cb3da0e7f7ce1684e5c6e34
# Verified Classes:   UnverifiableCapabilityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnverifiableCapabilityError(RuntimeError):
    """Raised when a manifest declares a capability the host cannot enforce."""
    pass


# Capabilities the host can enforce at a boundary below the skill.
# Anything not in this map has no enforcement hook and is therefore
# unverifiable by construction.
ENFORCEABLE = {
    "filesystem:write": "mount-namespace",
    "mail:read": "rpc-authorizer",
    "llm:invoke": "egress-proxy",
}


def _selector_is_canonical(capability: str) -> bool:
    # Non-canonical selectors: env-var indirection, globs, bare prefixes.
    selector = capability.split(":", 2)[-1] if capability.count(":") >= 2 else ""
    if not selector:
        return False
    if "$" in selector or "*" in selector or "?" in selector:
        return False
    # A bare name like "HOME" is a prefix match, not a path.
    if ":" not in capability and "/" not in selector:
        return False
    return True


def validate_manifest(manifest: dict) -> list[str]:
    granted = []
    for cap in manifest.get("capabilities", []):
        kind = ":".join(cap.split(":")[:2])
        if kind not in ENFORCEABLE:
            raise UnverifiableCapabilityError(
                f"capability {cap!r} has no enforcement point; "
                f"host cannot hold skill to declared scope"
            )
        if not _selector_is_canonical(cap):
            raise UnverifiableCapabilityError(
                f"capability {cap!r} uses a non-canonical selector; "
                f"host cannot pre-resolve target set before execution"
            )
        granted.append(cap)
    return granted


def load_skill(manifest: dict) -> dict:
    caps = validate_manifest(manifest)
    return {"manifest": manifest, "granted": caps, "enforcement": ENFORCEABLE}
