# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-signed-skill-manifest-that-authorizes-a-capability-set-wider-than-the-sandbox-it-runs-in.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-signed-skill-manifest-that-authorizes-a-capability-set-wider-than-the-sandbox-it-runs-in.warrant.json
# Markdown SHA-256:   6bf85e5cd15443e83fbf105e31d969110a8b534fc9228a5d6421765285437ee8
# Code AST SHA-256:   062e27d4aad7a2621b721f16bb4a516369a6689f25f5e0688d97f83d38162d81
# Verified Classes:   CapabilityReconciliationError, SignedGrant, RealizedSandbox
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityReconciliationError(RuntimeError):
    """Raised when a skill's realized sandbox exposes capabilities its signed grant did not authorize."""


@dataclass(frozen=True)
class SignedGrant:
    skill_id: str
    digest: str
    capabilities: FrozenSet[str]


@dataclass(frozen=True)
class RealizedSandbox:
    skill_id: str
    capabilities: FrozenSet[str] = field(default_factory=frozenset)


# Vocabulary mapping: sandbox capability tokens -> manifest capability tokens.
# Any sandbox token absent from this map is unmappable and therefore unauthorized.
SANDBOX_TO_MANIFEST = {
    "mount:./inputs:ro": "fs:read:./inputs",
    "mount:./outputs:rw": "fs:write:./outputs",
    "netns:empty": "net:egress:none",
    "seccomp:no-execve": "proc:spawn:none",
    # Deliberately absent: "mount:/etc/agent/secrets:ro", "socket:metadata.sock"
    # These are the baseline leaks the reconciliation must catch.
}


def reconcile(grant: SignedGrant, sandbox: RealizedSandbox) -> None:
    if grant.skill_id != sandbox.skill_id:
        raise CapabilityReconciliationError(
            f"identity mismatch: grant={grant.skill_id!r} sandbox={sandbox.skill_id!r}"
        )

    unauthorized = set()
    for sandbox_cap in sandbox.capabilities:
        manifest_cap = SANDBOX_TO_MANIFEST.get(sandbox_cap)
        if manifest_cap is None:
            # Sandbox exposes a capability the manifest vocabulary cannot name.
            unauthorized.add(f"unmappable:{sandbox_cap}")
        elif manifest_cap not in grant.capabilities:
            unauthorized.add(f"{sandbox_cap} (=> {manifest_cap})")

    if unauthorized:
        raise CapabilityReconciliationError(
            f"skill {grant.skill_id!r} digest {grant.digest[:12]}... "
            f"runs in a sandbox wider than its signed grant; "
            f"unauthorized capabilities: {sorted(unauthorized)}"
        )


def admit(grant: SignedGrant, sandbox: RealizedSandbox) -> None:
    # Signature and digest verification are assumed to have passed upstream.
    # The reconciliation is the gate that neither verifier performs alone.
    reconcile(grant, sandbox)


if __name__ == "__main__":
    grant = SignedGrant(
        skill_id="pdf-extract@2.3.1",
        digest="9f2c...e1",
        capabilities=frozenset({"fs:read:./inputs", "fs:write:./outputs",
                                "net:egress:none", "proc:spawn:none"}),
    )
    sandbox = RealizedSandbox(
        skill_id="pdf-extract@2.3.1",
        capabilities=frozenset({
            "mount:./inputs:ro",
            "mount:./outputs:rw",
            "netns:empty",
            "seccomp:no-execve",
            "mount:/etc/agent/secrets:ro",   # baseline leak
            "socket:metadata.sock",          # socket-layer egress bypass
        }),
    )
    admit(grant, sandbox)  # raises CapabilityReconciliationError
