# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-a-delegated-credential-be-re-scoped-when-an-aaif-agent-chain-crosses-an-oauth-trust-boundary-and-why-does-the-naive-pass-thr.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-a-delegated-credential-be-re-scoped-when-an-aaif-agent-chain-crosses-an-oauth-trust-boundary-and-why-does-the-naive-pass-thr.warrant.json
# Markdown SHA-256:   24344d7c8589497f173976e6a9905fc856a71a6189a91ce55c64fc8fb8a25ca5
# Code AST SHA-256:   58416ddaf7224313f7d1625565df9ab44ed7ff4c41d2c9b4e11b5e0bc90d223d
# Verified Classes:   DelegationChainCollapseError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationChainCollapseError(RuntimeError):
    """Raised when a cross-realm token exchange silently resets or truncates
    the actor chain instead of preserving delegation depth."""
    pass


def exchange_and_verify(
    exchange_fn,
    subject_token: dict,
    expected_prior_depth: int,
    expected_prior_actor: str,
) -> dict:
    """
    Perform an RFC 8693 exchange and verify the receiving AS preserved the
    delegation chain. Fail closed on collapse.

    exchange_fn: callable that performs the HTTP exchange and returns the
                 decoded response token claims.
    """
    prior_depth = subject_token.get("delegation_depth", 0)
    if prior_depth != expected_prior_depth:
        raise DelegationChainCollapseError(
            f"local subject token depth {prior_depth} != expected "
            f"{expected_prior_depth}; refusing to exchange"
        )

    new_token = exchange_fn(subject_token)

    new_depth = new_token.get("delegation_depth")
    if new_depth is None:
        raise DelegationChainCollapseError(
            "exchange response omitted delegation_depth; cannot verify "
            "chain preservation across trust boundary"
        )

    if new_depth != prior_depth + 1:
        raise DelegationChainCollapseError(
            f"delegation depth collapsed: prior={prior_depth}, "
            f"returned={new_depth}; receiving AS did not preserve actor chain"
        )

    # Walk the nested act chain and confirm the prior actor is still present.
    actors = []
    node = new_token.get("act")
    while isinstance(node, dict):
        if "sub" in node:
            actors.append(node["sub"])
        node = node.get("act")

    if expected_prior_actor not in actors:
        raise DelegationChainCollapseError(
            f"prior actor {expected_prior_actor!r} missing from nested act "
            f"chain {actors!r}; provenance lost at trust boundary"
        )

    return new_token
