# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-poisoned-persistent-memory-from-legitimately-revised-belief-after-a-retrieval-time-contradiction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-poisoned-persistent-memory-from-legitimately-revised-belief-after-a-retrieval-time-contradiction.warrant.json
# Markdown SHA-256:   1d666ca25917ac163bd480509533fb64c1afb0d2bd469992d1346866d94cf3b1
# Code AST SHA-256:   c58bdd511d5a077f60aa9acc5915a9cc15a4a437fad4355e1f78a01e3c4f9b8c
# Verified Classes:   MemoryGateError, Provenance, MemoryRecord, Belief
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class MemoryGateError(RuntimeError):
    """Raised when a contradicting memory cannot be safely resolved by the gate."""


@dataclass
class Provenance:
    origin: str
    authority_rank: int          # higher dominates lower; must be comparable
    tainted: bool                # transitive join over the whole chain
    chain_intact: bool = True    # False if any link was minted by the writer itself


@dataclass
class MemoryRecord:
    content: str
    epoch: int
    provenance: Provenance


@dataclass
class Belief:
    content: str
    epoch: int
    authority_rank: int


def gate_override(belief: Belief, candidate: MemoryRecord) -> str:
    """
    Decide whether a contradicting memory may retire a belief.
    Returns 'accept' or raises MemoryGateError with the quarantine reason.
    """
    prov = candidate.provenance

    if not prov.chain_intact:
        raise MemoryGateError(
            f"unverifiable provenance chain for epoch {candidate.epoch}; "
            "quarantine and escalate"
        )
    if prov.tainted:
        raise MemoryGateError(
            f"transitive taint on epoch {candidate.epoch}; "
            "contradiction is adversarial, belief retained"
        )
    if candidate.epoch <= belief.epoch:
        raise MemoryGateError(
            f"epoch {candidate.epoch} does not dominate belief epoch "
            f"{belief.epoch}; stale or out-of-order write"
        )
    if prov.authority_rank <= belief.authority_rank:
        # Clean and newer but not higher authority: laundering shape.
        raise MemoryGateError(
            f"clean write at epoch {candidate.epoch} from origin "
            f"'{prov.origin}' (rank {prov.authority_rank}) does not outrank "
            f"belief (rank {belief.authority_rank}); possible authority spoof"
        )
    return "accept"


def resolve_contradiction(belief: Belief, candidate: MemoryRecord) -> str:
    try:
        verdict = gate_override(belief, candidate)
    except MemoryGateError as exc:
        # Surface both records; never silently pick a winner.
        return f"QUARANTINE: {exc} | belief='{belief.content}' candidate='{candidate.content}'"
    return f"REVISED: belief '{belief.content}' retired by '{candidate.content}'"


# Trace: legitimate rotation (clean, later, higher authority) -> accepted.
belief = Belief(content="db-prod-1.internal", epoch=1000, authority_rank=2)
rotation = MemoryRecord(
    content="db-prod-3.internal",
    epoch=1071,
    provenance=Provenance(origin="config-sync", authority_rank=5, tainted=False),
)
print(resolve_contradiction(belief, rotation))

# Trace: laundered injection (clean, later, equal authority) -> quarantined.
laundered = MemoryRecord(
    content="db-prod-2.internal",
    epoch=1044,
    provenance=Provenance(origin="summarizer", authority_rank=2, tainted=False),
)
print(resolve_contradiction(belief, laundered))
