# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-capability-grant-when-a-delegated-scope-s-transitive-closure-exceeds-the-issuing-authority-s-own.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-capability-grant-when-a-delegated-scope-s-transitive-closure-exceeds-the-issuing-authority-s-own.warrant.json
# Markdown SHA-256:   53083d3d57c63b1c2856772f931a077d40d5d921f78c6e140f5a76c739668020
# Code AST SHA-256:   e4376ef48feb700efc316fc769bdcd1862f647b137c182ad91409b979cab26aa
# Verified Classes:   ClosureExceedsWarrant, Capability, Warrant, Delegatee
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ClosureExceedsWarrant(RuntimeError):
    """Raised when a delegated capability's transitive closure, unioned with
    the delegatee's pre-existing baseline, escapes the issuer's warrant."""
    pass


@dataclass(frozen=True)
class Capability:
    name: str
    constraints: FrozenSet[str] = frozenset()

    def composable_with(self, other: "Capability") -> bool:
        # A capability is composable if its output class can feed another's
        # input class. Encoded here as a conservative name-based rule; a real
        # implementation uses typed I/O signatures.
        terminal = {"notify", "receipt", "audit:emit"}
        return self.name not in terminal and other.name not in terminal


@dataclass
class Warrant:
    issuer: str
    granted: FrozenSet[Capability]
    envelope: FrozenSet[str]  # constraint atoms the issuer may operate under

    def closure(self) -> FrozenSet[Capability]:
        # Closure of a warrant: what the issuer itself may reach.
        return self.granted


@dataclass
class Delegatee:
    domain: str
    baseline: FrozenSet[Capability]
    decision_point_enforces_envelope: bool = False


def negotiate(
    issuer_warrant: Warrant,
    delegatee: Delegatee,
    proposed: Capability,
    baseline_projection: FrozenSet[Capability] | None,
) -> Capability:
    """Return the grant if sound; raise ClosureExceedsWarrant otherwise."""

    # 1. Composability demands baseline visibility.
    if baseline_projection is None:
        if any(proposed.composable_with(c) for c in delegatee.baseline):
            raise ClosureExceedsWarrant(
                f"grant of {proposed.name!r} is composable with delegatee "
                f"{delegatee.domain} baseline but no projection was disclosed; "
                f"closure cannot be bounded by issuer {issuer_warrant.issuer!r}"
            )

    # 2. Envelope enforcement must exist at the delegatee's composition point.
    if not delegatee.decision_point_enforces_envelope:
        raise ClosureExceedsWarrant(
            f"delegatee {delegatee.domain} composes in planner, not at a "
            f"decision point; grant envelope cannot be enforced"
        )

    # 3. Compute the closure the delegatee will actually reach.
    effective = delegatee.baseline | {proposed}
    reachable = frozenset(effective)
    for cap in effective:
        for other in effective:
            if cap is not other and cap.composable_with(other):
                reachable = reachable | {
                    Capability(f"{cap.name}+{other.name}", cap.constraints | other.constraints)
                }

    issuer_closure = issuer_warrant.closure()

    # 4. Every reachable operation must be contained in the issuer's warrant closure.
    for op in reachable:
        if op not in issuer_closure and op.name not in {
            f"{a.name}+{b.name}"
            for a in issuer_closure
            for b in issuer_closure
            if a is not b and a.composable_with(b)
        }:
            raise ClosureExceedsWarrant(
                f"composed operation {op.name!r} reachable by delegatee "
                f"{delegatee.domain} is outside warrant of {issuer_warrant.issuer!r}; "
                f"refusing grant of {proposed.name!r}"
            )

    return proposed
