# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-tool-manifest-whose-capability-grant-is-a-strict-superset-of-the-skill-it-was-invoked-to-perform.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-tool-manifest-whose-capability-grant-is-a-strict-superset-of-the-skill-it-was-invoked-to-perform.warrant.json
# Markdown SHA-256:   ec1b973aa590c84acf82506464ed2f2ec6aff84d088e429af9e340112222e78d
# Code AST SHA-256:   bc84a78204dae23c70f4f485666a631515ec9b9c0af20ef69a469ce7d61a7b22
# Verified Classes:   CapabilitySupersetError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CapabilitySupersetError(RuntimeError):
    """Raised when a dynamically loaded manifest grants more than the invoking task requires.

    The manifest may be authentic and schema-valid; the error is about the
    grant exceeding the task-scoped requirement, which opens an injection
    surface through the manifest's free-text description field.
    """

    def __init__(self, skill: str, excess: frozenset[str]):
        self.skill = skill
        self.excess = excess
        super().__init__(
            f"manifest for skill {skill!r} grants excess capabilities "
            f"{sorted(excess)} beyond task scope"
        )


def admit_manifest(
    manifest: dict,
    task_requirements: frozenset[str] | None,
) -> frozenset[str]:
    """Return the enforced capability set, or raise if the grant is over-broad.

    Invariant: effective capabilities = grant INTERSECT task_requirements,
    and admission requires grant SUBSET task_requirements. If task
    requirements are unknown, fail closed.
    """
    if task_requirements is None:
        raise CapabilitySupersetError(
            skill=manifest.get("name", "<unknown>"),
            excess=frozenset(manifest.get("capabilities", [])),
        )

    grant = frozenset(manifest.get("capabilities", []))
    excess = grant - task_requirements

    if excess:
        # Do NOT silently narrow: the description field still carries
        # instructions targeting the excess capabilities.
        raise CapabilitySupersetError(
            skill=manifest.get("name", "<unknown>"),
            excess=excess,
        )

    # Safe to project description into model context now.
    return grant


def load_and_project(manifest: dict, task_requirements: frozenset[str] | None) -> dict:
    enforced = admit_manifest(manifest, task_requirements)
    return {
        "name": manifest["name"],
        "capabilities": sorted(enforced),
        "description": manifest.get("description", ""),  # only reached when scoped
    }
