# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-peer-s-attestation-chain-when-the-federation-trust-anchor-rotates-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-peer-s-attestation-chain-when-the-federation-trust-anchor-rotates-mid-handoff.warrant.json
# Markdown SHA-256:   9276949a25dcca641a79af5e711548a6ef0cb4f1a9e0dec5beb5470ecf535c17
# Code AST SHA-256:   667c1bf3680d84a397e868fa671a90b8d9f085043cd1cb02af2f325132d01ce1
# Verified Classes:   AnchorEpochSkewError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AnchorEpochSkewError(RuntimeError):
    """Raised when a peer's attestation chain cannot be reconciled with the
    handoff's recorded anchor epoch under the currently advertised root set."""
    pass


def validate_continuation(handoff, chain, advertised_anchors):
    # advertised_anchors: {root_id: epoch}
    # handoff: {"leaf": str, "epoch": int, "state_token": str}
    if chain.leaf != handoff["leaf"]:
        raise AnchorEpochSkewError(
            f"leaf key divergence: token bound to {handoff['leaf']}, "
            f"chain presents {chain.leaf}"
        )

    root_epoch = advertised_anchors.get(chain.root_id)
    if root_epoch is None:
        raise AnchorEpochSkewError(
            f"chain roots at {chain.root_id}, not in advertised set "
            f"{list(advertised_anchors)}"
        )

    if root_epoch < handoff["epoch"]:
        raise AnchorEpochSkewError(
            f"epoch regression: token epoch {handoff['epoch']}, "
            f"chain roots at epoch {root_epoch} (replay suspected)"
        )

    if root_epoch > handoff["epoch"]:
        # Rotation advanced mid-handoff. Do NOT drop the payload and do NOT
        # accept it under the old binding. Hold and demand atomic re-attestation.
        return {"action": "re_attest", "required_epoch": root_epoch,
                "state_token": handoff["state_token"]}

    return {"action": "accept", "epoch": root_epoch}
