# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-enclave-attestation-that-verifies-correctly-but-binds-a-stale-measurement-and-how-the-memory-sealing-epoc.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-enclave-attestation-that-verifies-correctly-but-binds-a-stale-measurement-and-how-the-memory-sealing-epoc.warrant.json
# Markdown SHA-256:   5502a015812f3379b1fdfe76388dc0a7dc3c620113b881a1a1b7df2b6a0be644
# Code AST SHA-256:   d8f8c1e73d17f2a4a9bbe46e6235bb6f5c1f8e6201c10aee709125c7476fe1ec
# Verified Classes:   StaleSealingEpochError, EnclaveEpoch, SealedRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleSealingEpochError(RuntimeError):
    """Raised when a sealed memory record's epoch does not match the running enclave."""


@dataclass(frozen=True)
class EnclaveEpoch:
    measurement: bytes      # hash over image + config
    svn: int                # CPU security version at seal time
    min_svn: int            # platform floor; anything below is untrusted


@dataclass(frozen=True)
class SealedRecord:
    ciphertext: bytes
    aad_measurement: bytes  # bound into AEAD associated data
    aad_svn: int            # bound into AEAD associated data


def unseal_for_resume(record: SealedRecord, current: EnclaveEpoch,
                      forward_compatible: bool = False) -> bytes:
    # Integrity is assumed already checked by the AEAD layer; here we enforce provenance.
    if record.aad_measurement != current.measurement:
        raise StaleSealingEpochError(
            f"measurement mismatch: sealed under {record.aad_measurement.hex()[:12]}, "
            f"running {current.measurement.hex()[:12]}"
        )
    if record.aad_svn < current.min_svn:
        raise StaleSealingEpochError(
            f"SVN regression: sealed at svn={record.aad_svn}, floor={current.min_svn}"
        )
    if not forward_compatible and record.aad_svn != current.svn:
        raise StaleSealingEpochError(
            f"epoch mismatch: sealed at svn={record.aad_svn}, running svn={current.svn}; "
            "quarantine and rebuild semantic memory"
        )
    return record.ciphertext  # caller decrypts with enclave-bound key


def resume_agent(record: SealedRecord, current: EnclaveEpoch) -> bytes:
    try:
        return unseal_for_resume(record, current)
    except StaleSealingEpochError:
        # Cold-start amnesia is the correct, bounded outcome.
        return b""  # trigger re-derivation from attested external source
