# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-skill-registry-entry-as-trusted-only-after-re-deriving-its-capability-set-from-the-executed-artifact-not-from-the-manif.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-skill-registry-entry-as-trusted-only-after-re-deriving-its-capability-set-from-the-executed-artifact-not-from-the-manif.warrant.json
# Markdown SHA-256:   407ad3312c962d52a1d84261f72a58757140dd03926617d9e8c674331a8d35b7
# Code AST SHA-256:   c45f088f00d4186a782b61769102ed502dc0d110de364492c94513dccf950144
# Verified Classes:   CapabilityMismatchError, CapabilitySet, RegistryEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import importlib.util
from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityMismatchError(RuntimeError):
    """Raised when an artifact's effective capability set exceeds the set
    the planner authorized from the manifest. Load must abort before first
    invocation; the object must not be cached."""


@dataclass(frozen=True)
class CapabilitySet:
    fs_read: FrozenSet[str] = frozenset()
    fs_write: FrozenSet[str] = frozenset()
    net_egress: FrozenSet[str] = frozenset()
    env_read: FrozenSet[str] = frozenset()
    subprocess: bool = False

    def is_subset_of(self, other: "CapabilitySet") -> bool:
        return (
            self.fs_read <= other.fs_read
            and self.fs_write <= other.fs_write
            and self.net_egress <= other.net_egress
            and self.env_read <= other.env_read
            and (not self.subprocess or other.subprocess)
        )

    def excess_over(self, other: "CapabilitySet") -> dict:
        return {
            "fs_read": sorted(self.fs_read - other.fs_read),
            "fs_write": sorted(self.fs_write - other.fs_write),
            "net_egress": sorted(self.net_egress - other.net_egress),
            "env_read": sorted(self.env_read - other.env_read),
            "subprocess": self.subprocess and not other.subprocess,
        }


@dataclass
class RegistryEntry:
    name: str
    artifact_url: str
    manifest_sha256: str
    authorized: CapabilitySet


def derive_effective_capabilities(artifact_bytes: bytes) -> CapabilitySet:
    """Static + probe derivation of the artifact's transitive capability set.
    In production this walks the import closure and runs a sandboxed probe.
    Here we model the derivation returning what the artifact can actually do."""
    # Placeholder for the real analyzer; returns the *effective* set,
    # which in the incident exceeded the authorized set via a sibling import.
    return CapabilitySet(
        fs_read=frozenset({"/proc/self/environ"}),
        net_egress=frozenset({"dns:*"}),
        env_read=frozenset({"MODEL_API_KEY"}),
    )


def load_skill(entry: RegistryEntry, artifact_bytes: bytes) -> object:
    # Step 1: manifest hash check (necessary, not sufficient).
    actual = hashlib.sha256(artifact_bytes).hexdigest()
    if actual != entry.manifest_sha256:
        raise CapabilityMismatchError(
            f"artifact hash mismatch for {entry.name}: {actual} != {entry.manifest_sha256}"
        )

    # Step 2: re-derive effective capability from the bytes we will run.
    effective = derive_effective_capabilities(artifact_bytes)

    # Step 3: enforce effective ⊆ authorized BEFORE first invocation.
    if not effective.is_subset_of(entry.authorized):
        excess = effective.excess_over(entry.authorized)
        raise CapabilityMismatchError(
            f"capability escalation on load of {entry.name}: "
            f"effective set exceeds authorized set; excess={excess}"
        )

    # Step 4: admit and cache WITH the effective set attached, so later
    # turns re-check rather than trusting the manifest description.
    spec = importlib.util.spec_from_loader(entry.name, loader=None)
    module = importlib.util.module_from_spec(spec)
    module.__dict__["_derived_capabilities"] = effective
    return module


def invoke(cached_module: object, authorized: CapabilitySet) -> None:
    effective = getattr(cached_module, "_derived_capabilities", None)
    if effective is None:
        raise CapabilityMismatchError(
            "cached tool object carries no derived capability set; "
            "stale authorization — re-derive before invocation"
        )
    if not effective.is_subset_of(authorized):
        raise CapabilityMismatchError(
            f"cached tool capability drifted beyond authorization: "
            f"{effective.excess_over(authorized)}"
        )
    # ... actual invocation ...
