# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-credential-chain-depth-before-bilateral-policy-negotiation-can-terminate-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-credential-chain-depth-before-bilateral-policy-negotiation-can-terminate-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   9fc2a7d9672b572f5a1854896207799d57604d6c7f1f8235d8f1fe4e2e5ada5a
# Code AST SHA-256:   82103b3134245cea3debef089d15aea64719d57462e783a774ae612023e06801
# Verified Classes:   PolicyNegotiationDivergence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PolicyNegotiationDivergence(RuntimeError):
    """Raised when bilateral policy negotiation cannot terminate within the local depth bound."""
    pass


MAX_CHAIN_DEPTH = 4  # local, unilateral clamp; never derived from peer


def negotiate_federation(peer_challenge, my_chain, depth_counter):
    """
    One round of bilateral policy negotiation.
    peer_challenge: dict with 'required_depth' and 'policy_ref' (peer-derived).
    my_chain: list of signed VC links already presented.
    depth_counter: mutable local counter, monotonic per negotiation.
    """
    required = peer_challenge.get("required_depth", 0)

    # Divergence detector: peer requirement grew past what we can satisfy locally.
    if required > MAX_CHAIN_DEPTH:
        raise PolicyNegotiationDivergence(
            f"peer requires chain depth {required} > local MAX_CHAIN_DEPTH "
            f"{MAX_CHAIN_DEPTH}; reciprocal policy deferral has no fixed point. "
            f"Refusing capability; verdict=policy_incompatibility (non-retryable)."
        )

    # At the bound, a further deferral is proof of non-convergence, not a transient fault.
    if depth_counter["rounds"] >= MAX_CHAIN_DEPTH and required >= depth_counter["rounds"]:
        raise PolicyNegotiationDivergence(
            f"deferral challenge at depth bound (round {depth_counter['rounds']}, "
            f"required {required}); classifying as terminal divergence, not retryable."
        )

    # Below bound: mint exactly one more link and re-present.
    depth_counter["rounds"] += 1
    new_link = sign_delegation_link(my_chain[-1], policy_ref=my_chain[-1]["policy_ref"])
    return my_chain + [new_link]
