# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-attestation-chain-forks-from-surviving-key-rotation-across-federated-aaif-trust-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-attestation-chain-forks-from-surviving-key-rotation-across-federated-aaif-trust-domains.warrant.json
# Markdown SHA-256:   6059faeef75315f161d11f548e10d0cc5dc931af057b335ca9e22c59283426a4
# Code AST SHA-256:   616d52afa49d4d6eef333a2428d01cbd05c85eb4f7ab9153018931c422abf4b2
# Verified Classes:   AttestationForkError, EpochProbeUnavailable
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AttestationForkError(RuntimeError):
    """Raised when a rotation decision would be made without an authoritative
    home-domain epoch reference, risking an attestation-chain fork."""
    pass


class EpochProbeUnavailable(AttestationForkError):
    """Home domain could not supply a signed epoch assertion; decision is unbounded."""
    pass


def resolve_presentation(
    agent_id: str,
    presented_key_id: str,
    presented_epoch: int,
    local_registry_epoch: int,
    local_registry_key_id: str,
    probe_epoch_fn,
) -> str:
    """
    Decide admit/reject for a key presentation across a federated trust boundary.

    Invariant: any decision where presented_epoch != local_registry_epoch MUST be
    backed by a fresh, signed epoch assertion from the attesting home domain.
    Local registry state alone is never sufficient authority post-rotation.
    """
    if presented_epoch == local_registry_epoch and presented_key_id == local_registry_key_id:
        return "ADMIT_LOCAL"

    # Epoch divergence detected: local view is stale or the presentation is replayed.
    # A local-only decision here is exactly the fork trigger.
    try:
        authoritative_epoch = probe_epoch_fn(agent_id)
    except Exception as exc:
        raise EpochProbeUnavailable(
            f"cannot resolve epoch divergence for {agent_id}: "
            f"presented={presented_epoch} local={local_registry_epoch}"
        ) from exc

    if not getattr(authoritative_epoch, "signed", False):
        raise EpochProbeUnavailable(
            f"epoch assertion for {agent_id} is unsigned; refusing to bound decision"
        )

    if presented_epoch < authoritative_epoch.value:
        # Key predates the home domain's current epoch: replay of a retired key.
        return "REJECT_REPLAY"

    if presented_epoch > authoritative_epoch.value:
        # Verifier's probe is itself behind; do not admit on stale authority.
        raise AttestationForkError(
            f"probe for {agent_id} returned epoch {authoritative_epoch.value} "
            f"behind presented {presented_epoch}; cannot establish ordering"
        )

    # presented_epoch == authoritative_epoch: legitimate rotation not yet ingested locally.
    return "ADMIT_AND_SYNC"
