# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-delegated-authority-from-transitive-trust-in-cross-org-multi-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-delegated-authority-from-transitive-trust-in-cross-org-multi-agent-federation.warrant.json
# Markdown SHA-256:   63e7671afc54000585b9b38b8bde7f251e24d18c50576e50e4f4e5b5791d5210
# Code AST SHA-256:   bddda3a7cd82facacfc96c59677aadaefcb7df9626874695010eefbc5de16a01
# Verified Classes:   DelegationDepthError, Grant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DelegationDepthError(RuntimeError):
    """Raised when a grant cannot be safely forwarded due to missing or exhausted delegation depth."""
    pass


class Grant:
    def __init__(self, scopes, delegation_depth, issuer):
        self.scopes = frozenset(scopes)
        self.delegation_depth = delegation_depth  # None means "field absent"
        self.issuer = issuer


def forward_grant(incoming: Grant, requested_scopes, downstream_org: str) -> Grant:
    if incoming.delegation_depth is None:
        raise DelegationDepthError(
            f"grant from {incoming.issuer} has no delegation_depth field; "
            f"refusing to forward to {downstream_org} (absence is not permission)"
        )
    if incoming.delegation_depth <= 0:
        raise DelegationDepthError(
            f"grant from {incoming.issuer} is non-redelegable (depth=0); "
            f"cannot satisfy request from {downstream_org}"
        )
    if not requested_scopes <= incoming.scopes:
        raise DelegationDepthError(
            f"requested scopes {requested_scopes - incoming.scopes} not held by {incoming.issuer}"
        )
    return Grant(
        scopes=requested_scopes,
        delegation_depth=incoming.delegation_depth - 1,
        issuer=f"{incoming.issuer}->{downstream_org}",
    )
