# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-attest-a-peer-enclave-whose-measurement-matches-but-whose-sealed-memory-epoch-has-rolled.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-attest-a-peer-enclave-whose-measurement-matches-but-whose-sealed-memory-epoch-has-rolled.warrant.json
# Markdown SHA-256:   163567d9ea683cf28d937176502ab742e9d917ad69aa7f3070766f1f298072ec
# Code AST SHA-256:   b7a7da0a12de8c8ed10e28dee10bff0c95b3d2cb7d48d5446beb22e991c204c5
# Verified Classes:   SealedMemoryEpochMismatch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SealedMemoryEpochMismatch(RuntimeError):
    """Peer measurement matched but sealed-memory lineage is incompatible."""
    pass


def admit_peer(
    measurement_match: bool,
    prior_epoch_known: bool,
    last_witnessed_epoch: int,
    peer_epoch: int,
    lineage_commit_match: bool,
) -> str:
    if not measurement_match:
        # Easy case: wrong code. Terminal.
        raise SealedMemoryEpochMismatch(
            "measurement mismatch: peer code differs from pinned MRENCLAVE"
        )

    if not prior_epoch_known:
        # First contact: no reference point, accept and establish baseline.
        return "accept_establish_baseline"

    delta = peer_epoch - last_witnessed_epoch

    if delta < 0:
        # Epoch regressed: stale witness or replayed quote. Never reseal.
        raise SealedMemoryEpochMismatch(
            f"epoch regression: peer={peer_epoch} < witnessed={last_witnessed_epoch}"
        )

    if delta == 0 and lineage_commit_match:
        return "accept_continue"

    if delta > 0 and not lineage_commit_match:
        # The observed failure: right code, wrong memory lineage.
        # Refuse and route to reseal, do NOT fall back to empty memory.
        raise SealedMemoryEpochMismatch(
            f"epoch rollover without lineage match: "
            f"witnessed={last_witnessed_epoch} peer={peer_epoch}; "
            f"reseal required against epoch {peer_epoch}"
        )

    if delta > 0 and lineage_commit_match:
        # Rollover but logical lineage intact: accept, flag for audit.
        return "accept_flag_rollover"

    # delta == 0 and lineage mismatch: same epoch, divergent memory. Hard fault.
    raise SealedMemoryEpochMismatch(
        "same epoch but lineage commitment diverged: possible fork"
    )
