# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-fail-closed-on-attestation-anchor-drift-during-a-cross-org-agent-federation-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-fail-closed-on-attestation-anchor-drift-during-a-cross-org-agent-federation-handshake.warrant.json
# Markdown SHA-256:   8c8a115e28e20fc02bcc402c917b27800b1cc5bc672dd3a2c7d897efae59640f
# Code AST SHA-256:   06f57df55b1e05f3570bdc0d15aaef85f409573c4b3a554bf92df971624a2468
# Verified Classes:   AnchorDriftError, AnchorConfusionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AnchorDriftError(RuntimeError):
    """Raised when federation handshake cannot establish a joint trust-anchor epoch."""
    pass


class AnchorConfusionError(RuntimeError):
    """Raised when an attestation chain references an anchor outside the negotiated set."""
    pass


def verify_federation_handshake(
    local_anchors: dict[str, tuple[int, int]],   # anchor_id -> (valid_from, valid_to)
    peer_anchors: dict[str, tuple[int, int]],
    peer_asserted_epoch: int,
    local_epoch: int,
    epoch_tolerance: int,
    attestation_chain: list[str],
    negotiated_anchor_ids: set[str],
) -> str:
    if abs(peer_asserted_epoch - local_epoch) > epoch_tolerance:
        raise AnchorDriftError(
            f"epoch mismatch: peer={peer_asserted_epoch} local={local_epoch} "
            f"tolerance={epoch_tolerance}; fail closed, require out-of-band re-anchor"
        )

    def valid_at(anchors, epoch):
        return {a for a, (lo, hi) in anchors.items() if lo <= epoch <= hi}

    common = valid_at(local_anchors, peer_asserted_epoch) & valid_at(
        peer_anchors, peer_asserted_epoch
    )
    if not common:
        raise AnchorDriftError(
            f"empty anchor intersection at epoch {peer_asserted_epoch}; "
            f"local={sorted(valid_at(local_anchors, peer_asserted_epoch))} "
            f"peer={sorted(valid_at(peer_anchors, peer_asserted_epoch))}"
        )

    for anchor_id in attestation_chain:
        if anchor_id not in negotiated_anchor_ids:
            raise AnchorConfusionError(
                f"attestation references anchor {anchor_id!r} outside negotiated set "
                f"{sorted(negotiated_anchor_ids)}; possible anchor-confusion, abort"
            )

    return sorted(common)[0]
