# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-capability-escrow-renegotiation-deadlock-in-cross-org-agent-federation-when-trust-broker-warrants-outlive-the-negotia.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-capability-escrow-renegotiation-deadlock-in-cross-org-agent-federation-when-trust-broker-warrants-outlive-the-negotia.warrant.json
# Markdown SHA-256:   03b3695304b7d678472f5b7b80644d679cf00075778ff8eea12177d6dc509954
# Code AST SHA-256:   9a30f3a428b4898a520da792ee3a91411de861bee27727d4c1b95b2ca0a2c2b1
# Verified Classes:   OrphanedWarrantDeadlock
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OrphanedWarrantDeadlock(RuntimeError):
    """Raised when a capability warrant is escrowed against a superseded policy
    epoch and the broker cannot unilaterally renegotiate or revoke it."""
    pass


def check_warrant_liveness(warrant, current_epoch, broker_cosigned, now):
    """
    Evaluate the epoch-binding invariant for an escrowed warrant.

    warrant: dict with keys epoch, not_after, domain, quota_remaining
    current_epoch: the receiving domain's live policy epoch id
    broker_cosigned: bool, whether broker co-signed epoch transition
    now: monotonic timestamp
    """
    if warrant["epoch"] == current_epoch:
        return "live"

    # Epoch advanced under an outstanding warrant. Two legal resolutions:
    # (a) broker co-signed the transition -> warrant scope is compatible
    # (b) warrant already expired -> ordinary expiry path
    if broker_cosigned:
        return "transition_cosigned"

    if now >= warrant["not_after"]:
        return "expired"

    # Neither: the warrant is orphaned. It is signature-valid and not yet
    # expired, but priced against a policy epoch that no longer exists.
    raise OrphanedWarrantDeadlock(
        f"warrant for domain={warrant['domain']} bound to epoch "
        f"{warrant['epoch']} but live epoch is {current_epoch}; "
        f"broker did not co-sign transition; quota_remaining="
        f"{warrant['quota_remaining']}. Freeze escrow, emit blocking "
        f"renegotiation (not advisory), halt orchestrator reasoning loop."
    )


def broker_on_epoch_advance(warrant, new_epoch, broker_cosigned, now):
    try:
        state = check_warrant_liveness(warrant, new_epoch, broker_cosigned, now)
    except OrphanedWarrantDeadlock as e:
        # Freeze, do not release or consume. Pause orchestrator budget.
        return {"action": "freeze_and_renegotiate", "reason": str(e)}
    if state == "transition_cosigned":
        return {"action": "reprice", "epoch": new_epoch}
    return {"action": "noop", "state": state}
