# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-task-when-the-negotiated-policy-grant-is-narrower-than-the-delegated-subtask-s-implied-capability-set.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-task-when-the-negotiated-policy-grant-is-narrower-than-the-delegated-subtask-s-implied-capability-set.warrant.json
# Markdown SHA-256:   ba28f2a1d612b5484b3f72300a3e7062ad0824ee25fb434859217069debdae8c
# Code AST SHA-256:   7af4bca8e23dc0923c2bc223a81bc1f02a0379701db41619d5c753ec32e03c1b
# Verified Classes:   GapClass, FederatedRefusal, Grant, PlanProjection
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class GapClass(Enum):
    NAMEABLE_ADDITIVE = "nameable_additive"   # renegotiate, then resume
    CONSTITUTIVE = "constitutive"             # task invalid under grant; refuse
    INCIDENTAL = "incidental"                 # proceed, record substitution


class FederatedRefusal(RuntimeError):
    """Raised pre-execution when implied capability set exceeds the negotiated grant."""
    def __init__(self, subtask_id: str, gap: GapClass, missing: set[str], action: str):
        self.subtask_id = subtask_id
        self.gap = gap
        self.missing = missing
        self.action = action
        super().__init__(
            f"subtask {subtask_id} refused: gap={gap.value} "
            f"missing={sorted(missing)} required_action={action}"
        )


@dataclass
class Grant:
    capabilities: set[str]
    closure: str  # "closed" | "open_with_audit"


@dataclass
class PlanProjection:
    """Bounded simulation of the target's first K tool-selections for a subtask."""
    branches: list[set[str]] = field(default_factory=list)
    bounded: bool = True


def preflight_gate(
    subtask_id: str,
    grant: Grant,
    projection: PlanProjection,
    constitutive_caps: set[str],
) -> None:
    """Invariant: no execution begins if any projected branch leaves a closed grant."""
    if not projection.bounded:
        # Cannot prove coverage; must fall back to provenance-recorded degradation,
        # which is enforced downstream, not by refusal here.
        return

    implied: set[str] = set().union(*projection.branches) if projection.branches else set()
    missing = implied - grant.capabilities

    if not missing:
        return

    if grant.closure == "open_with_audit":
        # Permitted to proceed, but every missing cap must be logged as a substitution.
        # Caller is responsible for emitting the provenance record; we do not refuse.
        return

    # Closed grant: classify the gap before the first capability call.
    if missing & constitutive_caps:
        raise FederatedRefusal(
            subtask_id, GapClass.CONSTITUTIVE, missing, action="abort"
        )
    if missing:
        raise FederatedRefusal(
            subtask_id, GapClass.NAMEABLE_ADDITIVE, missing, action="renegotiate"
        )
