# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-tool-manifest-whose-declared-capability-set-is-a-strict-superset-of-the-capability-the-planner-actually-invoked.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-tool-manifest-whose-declared-capability-set-is-a-strict-superset-of-the-capability-the-planner-actually-invoked.warrant.json
# Markdown SHA-256:   b66f4948afee57854c1a965ab9a99970d6a8300b6a9c9faf8f2a77e430162587
# Code AST SHA-256:   c8d0fc3a9083e2e1a91ff887050303beeff6965eacb390b83804c908cc7a9fb6
# Verified Classes:   CapabilitySupersetError, Capability
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class CapabilitySupersetError(RuntimeError):
    """Raised when a manifest declares capabilities outside the task envelope."""


@dataclass(frozen=True)
class Capability:
    effect_class: str      # e.g. "fs_read", "net_egress", "clock"
    resource_class: str    # e.g. "local_fs", "any_host"


BASELINE: FrozenSet[Capability] = frozenset({
    Capability("clock", "none"),
    Capability("log", "none"),
})


def normalize(manifest: dict) -> FrozenSet[Capability]:
    """Map declared tools to structural capabilities, ignoring names/descriptions."""
    caps = set()
    for tool in manifest.get("tools", []):
        caps.add(Capability(tool["effect_class"], tool["resource_class"]))
    return frozenset(caps)


def admit_manifest(manifest: dict, required: FrozenSet[Capability]) -> FrozenSet[Capability]:
    declared = normalize(manifest)
    allowed = required | BASELINE
    surplus = declared - allowed
    if surplus:
        # Hard refusal: a warned-but-loaded superset is a dormant injection target.
        raise CapabilitySupersetError(
            f"manifest declares capabilities outside task envelope: "
            f"{sorted((c.effect_class, c.resource_class) for c in surplus)}"
        )
    return declared


def load_session(manifest: dict, plan_required: FrozenSet[Capability]) -> FrozenSet[Capability]:
    # Envelope must be derived from the plan, never from the registry's offer.
    if not plan_required:
        raise CapabilitySupersetError(
            "empty task envelope: refusing to admit any manifest without declared intent"
        )
    return admit_manifest(manifest, plan_required)
