# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-trust-broker-warrant-decay-in-cross-org-agent-federation-before-policy-negotiation-collapses.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-trust-broker-warrant-decay-in-cross-org-agent-federation-before-policy-negotiation-collapses.warrant.json
# Markdown SHA-256:   28a43ba0cead2349f056606cd1fea54ae175fa4be6cce2198dc70dcf1252f467
# Code AST SHA-256:   ab4baf1faf9ea38112536e805c3cd4420825e120a01d83462a7800c63315104f
# Verified Classes:   EpochStaleWarrantError, ScopeDisagreementError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EpochStaleWarrantError(RuntimeError):
    """Raised when a warrant's embedded policy_epoch is older than the
    evaluating engine's current epoch by more than the compatibility window.
    Distinct from ScopeDisagreementError: do not renegotiate scope on this."""
    pass


class ScopeDisagreementError(RuntimeError):
    """Raised when epochs match but the requested capability/purpose is not
    permitted under the current policy. Safe to renegotiate scope."""
    pass


def evaluate_warrant(warrant, engine, compatibility_window=0):
    """Evaluate a federated warrant at a remote policy engine.

    Enforces the freshness invariant at every evaluation point (each
    delegation hop, each negotiation round-trip), not just the first.
    """
    current_epoch = engine.current_policy_epoch()
    attestation_epoch = warrant.attestation.policy_epoch
    delta = current_epoch - attestation_epoch

    if delta < 0:
        # Warrant minted against a future epoch: broker ahead of engine.
        # Treat as untrusted rather than silently accepting.
        raise EpochStaleWarrantError(
            f"warrant epoch {attestation_epoch} is ahead of engine epoch "
            f"{current_epoch}; broker/engine clock skew, refusing"
        )

    if delta > compatibility_window:
        # The core failure: warrant is unexpired but epoch-stale.
        # Caller MUST NOT renegotiate scope; must force broker re-gossip.
        raise EpochStaleWarrantError(
            f"warrant policy_epoch {attestation_epoch} is {delta} epochs behind "
            f"engine epoch {current_epoch} (window={compatibility_window}); "
            f"invalidate and re-mint, do not renegotiate scope"
        )

    # Epochs compatible; now check actual scope.
    if not engine.policy_permits(
        purpose=warrant.attestation.purpose,
        data_class=warrant.attestation.data_class,
        delegation_depth=warrant.attestation.delegation_depth,
    ):
        raise ScopeDisagreementError(
            f"epochs compatible ({attestation_epoch}~{current_epoch}) but "
            f"policy denies purpose={warrant.attestation.purpose} "
            f"data_class={warrant.attestation.data_class} "
            f"depth={warrant.attestation.delegation_depth}"
        )

    return True


def negotiate(warrant, engine, max_rounds=5):
    """Negotiation loop that branches on epoch-stale vs scope-disagreement."""
    for round_idx in range(max_rounds):
        try:
            return evaluate_warrant(warrant, engine)
        except EpochStaleWarrantError:
            # Do not renegotiate scope. Force broker re-gossip, re-mint.
            warrant = warrant.broker.refresh_and_remint(warrant)
        except ScopeDisagreementError:
            # Genuine scope conflict; adjust and retry.
            warrant = warrant.broker.remint_with_scope(
                warrant, engine.suggest_scope()
            )
    raise EpochStaleWarrantError(
        f"negotiation exhausted {max_rounds} rounds; warrant could not be "
        f"reconciled with engine epoch {engine.current_policy_epoch()}"
    )
