# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-re-delegate-a-federated-capability-when-the-peer-s-policy-envelope-is-narrower-than-the-delegating-in.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-re-delegate-a-federated-capability-when-the-peer-s-policy-envelope-is-narrower-than-the-delegating-in.warrant.json
# Markdown SHA-256:   6757575dd4483c81578cc48680dfd974f63e3e9d45ebed1877baca96eadf0fab
# Code AST SHA-256:   0486683144163bdf0502a43a1f4dcf2cab121f412902172a4a321f57bb8486b3
# Verified Classes:   FederatedDelegationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class FederatedDelegationError(RuntimeError):
    """Raised when a delegating instance cannot establish that its cached
    policy envelope for a peer is strictly wider than the peer's current
    enforced envelope, and therefore must not re-delegate."""
    pass


def re_delegate(
    delegator,
    peer,
    capability: str,
    warrant: dict,
    cached_envelope: dict,
) -> dict:
    # Invariant: cached envelope must be verifiably wider than peer's
    # current enforced envelope before any sub-delegation clause is honored.
    current = peer.fetch_current_policy_envelope(capability)

    if current is None:
        raise FederatedDelegationError(
            f"peer {peer.domain} did not expose current enforcement state for "
            f"{capability}; cached assumption is unfalsifiable, refusing to re-delegate"
        )

    if not envelope_strictly_wider(cached_envelope, current):
        raise FederatedDelegationError(
            f"cached envelope for {peer.domain}/{capability} is not strictly wider "
            f"than current enforcement (cached={cached_envelope.get('version')}, "
            f"current={current.get('version')}); re-negotiate before re-delegating"
        )

    if warrant.get("sub_delegation_clause") and not warrant.get("origin_domain_attestation"):
        raise FederatedDelegationError(
            f"sub-delegation warrant to {peer.domain} lacks origin_domain attestation; "
            f"peer enforcement may require it even if negotiated schema did not"
        )

    result = peer.invoke(capability, warrant)

    if result.rejected:
        if result.rejection_class == "schema_shape":
            raise FederatedDelegationError(
                f"schema-shape rejection from {peer.domain}: {result.detail}; "
                f"do not retry, re-negotiate warrant shape"
            )
        if result.rejection_class == "unmapped":
            raise FederatedDelegationError(
                f"unmapped rejection from {peer.domain}, cannot distinguish "
                f"enforcement narrowing from capacity failure; aborting sub-delegation"
            )

    return result
