# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-warrant-scope-collapse-during-cross-org-federation-when-a-peer-s-trust-negotiation-contract-silently-widens-a.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-warrant-scope-collapse-during-cross-org-federation-when-a-peer-s-trust-negotiation-contract-silently-widens-a.warrant.json
# Markdown SHA-256:   97e94bdbe2982cceebc00cb863cd546bc48d141e5f736df2e067faf36bb3ef84
# Code AST SHA-256:   76f59c9dfefc1b95007ce2525f160384750501e0f9a242c7191a0601c9459751
# Verified Classes:   WarrantScopeCollapse, UnrepresentableAttenuation, Predicate, Warrant, ChildScope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class WarrantScopeCollapse(RuntimeError):
    """Raised when a sub-delegated capability is not a subset of the parent warrant's predicate axes."""
    pass


class UnrepresentableAttenuation(WarrantScopeCollapse):
    """Raised when the child protocol cannot express one or more parent predicate axes."""
    pass


@dataclass(frozen=True)
class Predicate:
    axes: FrozenSet[str]
    values: dict = field(default_factory=dict)


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    capability: str
    predicate: Predicate
    expiry_s: int


@dataclass(frozen=True)
class ChildScope:
    capability: str
    expressible_axes: FrozenSet[str]
    values: dict = field(default_factory=dict)


def check_axis_monotonicity(parent: Warrant, child: ChildScope) -> None:
    missing = parent.predicate.axes - child.expressible_axes
    if missing:
        raise UnrepresentableAttenuation(
            f"child manifest cannot express axes {sorted(missing)} "
            f"from parent warrant {parent.warrant_id}; "
            f"refusing to widen to broadest-match"
        )
    for axis in parent.predicate.axes:
        parent_val = parent.predicate.values.get(axis)
        child_val = child.values.get(axis)
        if parent_val is not None and child_val is not None:
            if not _is_subset_value(axis, child_val, parent_val):
                raise WarrantScopeCollapse(
                    f"axis {axis}: child value {child_val!r} is not a subset of "
                    f"parent value {parent_val!r} for warrant {parent.warrant_id}"
                )


def _is_subset_value(axis: str, child_val, parent_val) -> bool:
    if axis == "region":
        return child_val == parent_val or (isinstance(parent_val, str) and parent_val == "global")
    if axis == "classification":
        order = ["public", "internal", "restricted"]
        return order.index(child_val) <= order.index(parent_val)
    return child_val == parent_val


def sub_delegate(parent: Warrant, child: ChildScope, budget_ms: int) -> ChildScope:
    if budget_ms <= 0:
        raise WarrantScopeCollapse(
            f"negotiation budget exhausted for warrant {parent.warrant_id}; "
            f"fail-closed (no widening fallback)"
        )
    check_axis_monotonicity(parent, child)
    return child
