# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-memory-poisoning-from-legitimate-belief-revision-when-the-write-gate-only-sees-post-hoc-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-memory-poisoning-from-legitimate-belief-revision-when-the-write-gate-only-sees-post-hoc-provenance.warrant.json
# Markdown SHA-256:   f7ff97fabb7b8baee980222fa028d964eae968801264a85db2055cca663020c3
# Code AST SHA-256:   c9e1d6c4740329e4d78e5d804626cba518abeedacccea9bb0c64dd5183d340da
# Verified Classes:   PoisoningGateError, Relation, Provenance, Slot, CandidateWrite
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class PoisoningGateError(RuntimeError):
    """Raised when a write is a blind substitution masquerading as a revision."""


class Relation(Enum):
    REFINE = "refine"
    EXPIRE = "expire"
    CONTRADICT_WITH_EVIDENCE = "contradict_with_evidence"


@dataclass(frozen=True)
class Provenance:
    source: str
    trust: int          # higher is more trusted
    signed: bool


@dataclass(frozen=True)
class Slot:
    value_id: str
    value: object
    provenance: Provenance


@dataclass(frozen=True)
class CandidateWrite:
    value: object
    provenance: Provenance
    derives_from: str | None = None          # value_id of the slot it revises
    relation: Relation | None = None
    evidence_source: str | None = None       # required for CONTRADICT_WITH_EVIDENCE


def audited_write(slot: Slot, cand: CandidateWrite) -> Slot:
    # 1. Provenance gate: writer must be trusted enough and signed.
    if not cand.provenance.signed:
        raise PoisoningGateError(f"unsigned write from {cand.provenance.source!r}")
    if cand.provenance.trust < slot.provenance.trust:
        raise PoisoningGateError(
            f"trust downgrade: {cand.provenance.trust} < {slot.provenance.trust}"
        )

    # 2. Continuity gate: a value change MUST cite the slot it revises.
    value_changed = cand.value != slot.value
    if value_changed and cand.derives_from is None:
        # This is the laundering path: a trusted channel emitting a
        # contradiction of a slot it never read. Provenance is clean;
        # semantics are a substitution.
        raise PoisoningGateError(
            f"blind substitution of {slot.value_id!r}: value changed "
            f"({slot.value!r} -> {cand.value!r}) with no derives_from"
        )

    if cand.derives_from is not None and cand.derives_from != slot.value_id:
        raise PoisoningGateError(
            f"stale derivation: cites {cand.derives_from!r}, "
            f"slot is {slot.value_id!r}"
        )

    # 3. Contradiction requires evidence, not just a trusted writer.
    if cand.relation is Relation.CONTRADICT_WITH_EVIDENCE and not cand.evidence_source:
        raise PoisoningGateError("contradiction without evidence artifact")

    # 4. Commit as a new value_id so future writes must re-cite.
    new_id = f"{slot.value_id}->{cand.provenance.source}"
    return Slot(value_id=new_id, value=cand.value, provenance=cand.provenance)
