# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-the-dpop-key-thumbprint-at-token-exchange-time-and-why-re-binding-on-refresh-silently-voids-the-capability-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-the-dpop-key-thumbprint-at-token-exchange-time-and-why-re-binding-on-refresh-silently-voids-the-capability-warrant.warrant.json
# Markdown SHA-256:   9efad62a5e3c2e48e3718dc09fe9c039e443f1b82bcaf20b022a45f9215c4d16
# Code AST SHA-256:   0a7cff7a6439e420f3431205b8ed6a7d70738eff7ffb0a111f4a886310cb5395
# Verified Classes:   WarrantBindingDiscontinuity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class WarrantBindingDiscontinuity(RuntimeError):
    """Raised when a refreshed token's cnf.jkt no longer matches the
    thumbprint recorded in the delegation ledger for the active warrant."""
    pass


def refresh_or_reexchange(
    held_token: dict,
    current_dpop_key_thumbprint: str,
    ledger_warrant_thumbprint: str,
    root_token_available: bool,
) -> dict:
    """
    held_token: decoded access token currently held by the agent
    current_dpop_key_thumbprint: thumbprint of the key this process will sign with
    ledger_warrant_thumbprint: cnf.jkt recorded when the warrant was minted
    root_token_available: whether the root delegator token is still valid
    """
    token_jkt = held_token.get("cnf", {}).get("jkt")
    if token_jkt is None:
        raise WarrantBindingDiscontinuity(
            "held token has no cnf.jkt; cannot establish proof-of-possession continuity"
        )

    # Case 1: key unchanged, binding intact -> plain refresh is safe.
    if current_dpop_key_thumbprint == token_jkt == ledger_warrant_thumbprint:
        return {"action": "refresh", "binding": token_jkt}

    # Case 2: key rotated but ledger still expects old binding.
    # Refresh would silently re-bind; refuse and force re-exchange.
    if current_dpop_key_thumbprint != ledger_warrant_thumbprint:
        if not root_token_available:
            raise WarrantBindingDiscontinuity(
                f"DPoP key rotated ({ledger_warrant_thumbprint} -> "
                f"{current_dpop_key_thumbprint}) and root token unavailable; "
                "refusing refresh because it would launder the warrant binding"
            )
        return {
            "action": "reexchange_from_root",
            "revoke_warrant": ledger_warrant_thumbprint,
            "new_binding": current_dpop_key_thumbprint,
        }

    # Case 3: token's cnf.jkt disagrees with ledger (tamper or stale ledger).
    if token_jkt != ledger_warrant_thumbprint:
        raise WarrantBindingDiscontinuity(
            f"token cnf.jkt {token_jkt} does not match ledger warrant "
            f"{ledger_warrant_thumbprint}; possible replay or stale ledger"
        )

    return {"action": "refresh", "binding": token_jkt}
