# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-token-whose-attenuation-chain-validates-but-whose-scope-lattice-has-been-widened-by-a.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-token-whose-attenuation-chain-validates-but-whose-scope-lattice-has-been-widened-by-a.warrant.json
# Markdown SHA-256:   66d8b7e6c7831d39410361f0af14aec6eaa1eba81ede827e501d8fa767868578
# Code AST SHA-256:   801515cfd4adf49d11131297f13e2089dfd39abc1c5b096bc4a06b34425ac40d
# Verified Classes:   LatticeWideningError, Scope, IssuedGrant, DelegationRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class LatticeWideningError(RuntimeError):
    """Raised when a presented credential's scope is dominated by an ancestor
    but not by any single issued sibling grant, indicating a composed
    principal assembled across a partition boundary."""


@dataclass(frozen=True)
class Scope:
    caps: FrozenSet[str]
    partition: str | None = None

    def __le__(self, other: "Scope") -> bool:
        return self.caps <= other.caps


@dataclass
class IssuedGrant:
    grant_id: str
    scope: Scope


@dataclass
class DelegationRegistry:
    # parent_grant_id -> list of actually-minted child grants
    children: dict[str, list[IssuedGrant]] = field(default_factory=dict)
    # parent_grant_id -> True if the orchestrator partitioned children
    # to enforce non-interference
    partitioned: dict[str, bool] = field(default_factory=dict)

    def register_child(self, parent_id: str, child: IssuedGrant) -> None:
        self.children.setdefault(parent_id, []).append(child)

    def mark_partitioned(self, parent_id: str) -> None:
        self.partitioned[parent_id] = True


def verify_presented(
    presented_scope: Scope,
    parent_scope: Scope,
    parent_id: str,
    registry: DelegationRegistry,
) -> None:
    # Edge attenuation: standard check, passes for the defective token.
    if not (presented_scope <= parent_scope):
        raise LatticeWideningError(
            f"presented scope {presented_scope.caps} exceeds parent {parent_scope.caps}"
        )

    siblings = registry.children.get(parent_id, [])
    dominated_by_sibling = any(presented_scope <= s.scope for s in siblings)

    if not dominated_by_sibling:
        # Presented scope fits under the parent but under no single issued child.
        # If the parent's children were partitioned, this is a composed principal
        # that crosses a separation boundary — reject hard.
        if registry.partitioned.get(parent_id, False):
            raise LatticeWideningError(
                "composed credential spans partitioned sibling grants: "
                f"scope {presented_scope.caps} is not dominated by any single "
                f"issued child of {parent_id}; refusing cross-partition merge"
            )
        # Undifferentiated pool: union-under-parent is benign, allow.
        return


def handle_handoff(
    presented_scope: Scope,
    parent_scope: Scope,
    parent_id: str,
    registry: DelegationRegistry,
) -> str:
    verify_presented(presented_scope, parent_scope, parent_id, registry)
    return "accepted"


if __name__ == "__main__":
    reg = DelegationRegistry()
    parent = Scope(frozenset({"fs:read:/data", "tool:search",
                              "net:post:api.internal", "fs:write:/scratch"}))
    reg.mark_partitioned("cap_root")
    reg.register_child("cap_root", IssuedGrant("cap_A", Scope(
        frozenset({"fs:read:/data", "tool:search"}), partition="read")))
    reg.register_child("cap_root", IssuedGrant("cap_B", Scope(
        frozenset({"net:post:api.internal", "fs:write:/scratch"}), partition="egress")))

    merged = Scope(frozenset({"fs:read:/data", "tool:search",
                              "net:post:api.internal", "fs:write:/scratch"}))
    # Raises LatticeWideningError: subset of parent, but no single child dominates it.
    handle_handoff(merged, parent, "cap_root", reg)
