# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-self-rewritten-context-against-the-pre-compaction-audit-trail-before-resuming.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-self-rewritten-context-against-the-pre-compaction-audit-trail-before-resuming.warrant.json
# Markdown SHA-256:   42d9efa39b0f3cdeedf39e3257e4786457f708d0f5ee3f5bff2357a5af00469b
# Code AST SHA-256:   5174e61fe5cb5660b9e937e22e647676a46b0ba5ec0696180174f1269171192c
# Verified Classes:   Origin, UnreconciledMemoryError, MemoryEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class Origin(Enum):
    VERBATIM = "verbatim"
    DISTILLED = "distilled"
    SYNTHESIZED = "synthesized"


class UnreconciledMemoryError(RuntimeError):
    """Raised when an instance attempts to act on a self-edited memory
    entry whose provenance was not reconciled against the pre-edit audit
    record. Signals that budget-driven compaction has converted state
    loss into undetectable epistemic corruption."""


@dataclass
class MemoryEntry:
    entry_id: str
    text: str
    origin: Origin
    cardinality_collapsed: bool = False
    negation_dropped: bool = False
    reconciled: bool = False


def gate_action(entry: MemoryEntry, destructive: bool, audit_available: bool) -> None:
    """Enforce the resume-time reconciliation invariant before acting."""
    if entry.origin is Origin.VERBATIM:
        return

    if entry.origin is Origin.SYNTHESIZED and not entry.reconciled:
        if not audit_available:
            raise UnreconciledMemoryError(
                f"entry {entry.entry_id} is synthesized and audit record is "
                f"unavailable; state is unrecoverable, restart from external checkpoint"
            )
        raise UnreconciledMemoryError(
            f"entry {entry.entry_id} is synthesized; re-derive from audit record "
            f"before acting (do not treat as memory)"
        )

    if entry.origin is Origin.DISTILLED:
        if entry.cardinality_collapsed or entry.negation_dropped:
            raise UnreconciledMemoryError(
                f"entry {entry.entry_id} lost cardinality/negation during "
                f"distillation; re-derive original from audit record"
            )
        if destructive and not entry.reconciled:
            raise UnreconciledMemoryError(
                f"entry {entry.entry_id} is distilled and load-bearing for a "
                f"destructive op; re-run underlying check before proceeding"
            )
