# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-signed-skill-manifest-from-being-silently-re-scoped-between-registry-publication-and-runtime-load.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-signed-skill-manifest-from-being-silently-re-scoped-between-registry-publication-and-runtime-load.warrant.json
# Markdown SHA-256:   0c379e3de3bdff2ffd0afcddda9a0ab41e2ce766f8c2bc83b1163ab02ff760e5
# Code AST SHA-256:   85e24f8216d27516643c8960f472d4c32f25a6c877741dd91f6b75a06e95b62f
# Verified Classes:   ManifestRescopeError, Manifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

"""Load-time guard for signed skill manifests.

Enforces the four invariants (I1-I4) that bound the re-scoping failure mode.
"""

from dataclasses import dataclass
from typing import Mapping


class ManifestRescopeError(RuntimeError):
    """Raised when a signed manifest's effective grant diverges from its declaration."""


@dataclass(frozen=True)
class Manifest:
    name: str
    version: str
    semantics_version: str
    declared_capabilities: frozenset[str]
    artifact_digest: str


# The runtime's capability table, keyed by (semantics_version, name) -> concrete grant.
# An exact-match lookup; there is no fallback and no prefix matching.
CAPABILITY_TABLE: Mapping[tuple[str, str], frozenset[str]] = {
    ("v3", "fs.read"): frozenset({"fs.read"}),
    ("v3", "fs.read.recursive"): frozenset({"fs.read", "fs.read.recursive"}),
    ("v3", "net.egress"): frozenset({"net.egress"}),
}

SUPPORTED_SEMANTICS = frozenset({"v3"})


def resolve_effective_grant(manifest: Manifest) -> frozenset[str]:
    effective: set[str] = set()
    for cap in manifest.declared_capabilities:
        key = (manifest.semantics_version, cap)
        if key not in CAPABILITY_TABLE:
            raise ManifestRescopeError(
                f"capability {cap!r} unresolvable under semantics "
                f"{manifest.semantics_version!r}; refusing to guess"
            )
        effective |= CAPABILITY_TABLE[key]
    return frozenset(effective)


def verify_and_bind(manifest: Manifest, trusted_digest: str) -> frozenset[str]:
    # I4: digest binds artifact + manifest + semantics as one blob (checked upstream).
    if manifest.artifact_digest != trusted_digest:
        raise ManifestRescopeError("artifact digest mismatch")

    # I1: exact semantics match, no compatibility fallback.
    if manifest.semantics_version not in SUPPORTED_SEMANTICS:
        raise ManifestRescopeError(
            f"semantics {manifest.semantics_version!r} not implemented identically"
        )

    # I2: effective grant must equal declared grant, not merely contain it.
    effective = resolve_effective_grant(manifest)
    if effective != manifest.declared_capabilities:
        # Aliasing (fs.read -> fs.read.recursive) or widening detected here.
        raise ManifestRescopeError(
            f"effective grant {sorted(effective)} != declared "
            f"{sorted(manifest.declared_capabilities)}; manifest was authored "
            f"against a different interpreter"
        )

    # I3: caller must hand this grant to the sandbox policy generator, which is
    # the authoritative enforcer; the runtime pre-check above is not sufficient.
    return effective
