# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-skill-whose-manifest-hash-matches-but-whose-declared-capability-set-drifted-the-capability-set-drift-boundary-in-dynami.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-skill-whose-manifest-hash-matches-but-whose-declared-capability-set-drifted-the-capability-set-drift-boundary-in-dynami.warrant.json
# Markdown SHA-256:   bec5e1a92529c36e09cca5d91ac3003533bf7c318a5177fc1b8251a177f0a114
# Code AST SHA-256:   3c9495ba5c51b3250e61e6d1a9095bbb6635486109e685a536fb00dc1e5fd82f
# Verified Classes:   CapabilityDriftError, AdmissionRecord, SkillManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, FrozenSet, Iterable


class CapabilityDriftError(RuntimeError):
    """Raised when a skill's effective capability closure exceeds its admitted closure."""


@dataclass(frozen=True)
class AdmissionRecord:
    manifest_sha256: str
    code_sha256: str
    admitted_capabilities: FrozenSet[str]


@dataclass
class SkillManifest:
    declared_capabilities: Iterable[str]
    dependencies: Iterable[str] = field(default_factory=tuple)


def expand_capabilities(
    declared: Iterable[str],
    alias_table: Dict[str, FrozenSet[str]],
) -> FrozenSet[str]:
    """Expand declared capability strings against the *current* alias table."""
    out = set()
    for cap in declared:
        if cap not in alias_table:
            # Unknown token: cannot be spoken to by any admission record.
            out.add(f"__unknown__:{cap}")
        else:
            out.update(alias_table[cap])
    return frozenset(out)


def effective_closure(
    manifest: SkillManifest,
    alias_table: Dict[str, FrozenSet[str]],
    dep_manifests: Dict[str, SkillManifest],
) -> FrozenSet[str]:
    """Closure over the skill's own declaration plus its transitive dependencies."""
    closure = set(expand_capabilities(manifest.declared_capabilities, alias_table))
    for dep_name in manifest.dependencies:
        dep = dep_manifests.get(dep_name)
        if dep is None:
            # A missing dependency is itself a widening risk: fail closed.
            closure.add(f"__unresolved_dep__:{dep_name}")
            continue
        closure.update(effective_closure(dep, alias_table, dep_manifests))
    return frozenset(closure)


def load_skill(
    manifest: SkillManifest,
    manifest_bytes: bytes,
    code_bytes: bytes,
    record: AdmissionRecord,
    alias_table: Dict[str, FrozenSet[str]],
    dep_manifests: Dict[str, SkillManifest],
    sha256,
) -> SkillManifest:
    # Step 1: integrity (necessary, not sufficient).
    if sha256(manifest_bytes).hexdigest() != record.manifest_sha256:
        raise CapabilityDriftError("manifest hash mismatch")
    if sha256(code_bytes).hexdigest() != record.code_sha256:
        raise CapabilityDriftError("code hash mismatch")

    # Step 2: recompute the effective closure under the *current* grammar/namespace.
    effective = effective_closure(manifest, alias_table, dep_manifests)

    # Step 3: containment against the admitted closure. This is the real guard.
    widening = effective - record.admitted_capabilities
    if widening:
        raise CapabilityDriftError(
            f"capability closure widened beyond admission: {sorted(widening)}"
        )
    return manifest
