# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-token-whose-scope-silently-widens-at-the-second-hop-of-a-cross-org-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-capability-token-whose-scope-silently-widens-at-the-second-hop-of-a-cross-org-federation.warrant.json
# Markdown SHA-256:   bf5aac9c6f19ff20c7e7fc61a29f745517a6fb1016ce5bb03a8f4e5c8e8d708b
# Code AST SHA-256:   47dab7f3afe76f34623cb5e1488daf9062d9db59d6d22bd55f8c9c5404e8db49
# Verified Classes:   ScopeWideningError, CapabilityEnvelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a delegated capability's resolved scope exceeds its parent's."""


@dataclass(frozen=True)
class CapabilityEnvelope:
    issuer: str
    constraints: FrozenSet[str]          # e.g. {"row_limit=1000", "pii_redaction=required"}
    residual: FrozenSet[str] = field(default_factory=frozenset)  # unrepresentable-but-carried


def re_delegate(
    parent: CapabilityEnvelope,
    re_delegator: str,
    representable: FrozenSet[str],
) -> CapabilityEnvelope:
    """
    Re-delegate a capability under monotonic attenuation.

    `representable` is the set of parent constraints the re-delegator's own
    schema can encode. Anything not representable MUST be carried as a signed
    residual attributed to the original issuer; it MUST NOT be dropped.
    """
    if not parent.constraints.issubset(representable | parent.residual):
        # The re-delegator cannot express a constraint and has no residual to carry it.
        # Emitting anyway would silently widen scope at the next hop.
        unrepresentable = parent.constraints - representable - parent.residual
        raise ScopeWideningError(
            f"{re_delegator} cannot re-delegate without widening scope; "
            f"unrepresentable constraints: {sorted(unrepresentable)}"
        )

    # Constraints the delegator can encode stay inline; the rest ride as residual,
    # still attributed to the original issuer, never re-signed by the delegator.
    inline = parent.constraints & representable
    carried = (parent.constraints - representable) | parent.residual
    return CapabilityEnvelope(
        issuer=parent.issuer,           # issuer attribution preserved
        constraints=frozenset(inline),
        residual=frozenset(carried),
    )


def enforce_at_edge(
    envelope: CapabilityEnvelope,
    requested_ops: FrozenSet[str],
    required_constraints: FrozenSet[str],
) -> None:
    """Final enforcement point must interpret inline + residual together."""
    effective = envelope.constraints | envelope.residual
    missing = required_constraints - effective
    if missing:
        raise ScopeWideningError(
            f"edge enforcement rejected: constraints {sorted(missing)} "
            f"absent from effective scope of envelope issued by {envelope.issuer}"
        )


# Reproduces the observed failure: B's schema cannot encode row_limit or pii_redaction,
# and B has no residual channel -> must fail closed instead of emitting a wider token.
parent = CapabilityEnvelope(
    issuer="org-a",
    constraints=frozenset({"op=read", "resource=finance/q2", "row_limit=1000", "pii_redaction=required"}),
)
try:
    re_delegate(parent, re_delegator="org-b", representable=frozenset({"op=read", "resource=finance/q2"}))
except ScopeWideningError as e:
    print(f"blocked at hop A->B: {e}")
