# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-poisoned-memory-write-from-a-legitimate-belief-update-when-both-arrive-through-the-same-retrieval-path.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-poisoned-memory-write-from-a-legitimate-belief-update-when-both-arrive-through-the-same-retrieval-path.warrant.json
# Markdown SHA-256:   d9fe70b7bf8e402d5c9ef030b32f2364c4aef4ccdcf950caa4d299fbd07c42c9
# Code AST SHA-256:   f2a7f9f78c14c94dc225f851c24c6aeb55d0a6b8408a6b3cea4f17bfe9f2d968
# Verified Classes:   ProvenanceDiscontinuity, ProvClass, MemoryRecord, MemoryStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class ProvenanceDiscontinuity(RuntimeError):
    """Raised when a memory write would overwrite a higher-provenance incumbent
    without an independent, equal-or-stronger provenance anchor."""


class ProvClass(IntEnum):
    MODEL_INFERRED = 0
    WEB_FETCH = 1
    PEER_AGENT_ATTESTED = 2
    HUMAN_CORRECTION = 3
    TOOL_VERIFIED = 4


@dataclass
class MemoryRecord:
    slot_id: str
    value: str
    prov_class: ProvClass
    provenance_chain: tuple[str, ...]
    first_observed: float
    confidence: float
    version: int = 1
    supersedes: Optional[int] = None


@dataclass
class MemoryStore:
    slots: dict[str, MemoryRecord] = field(default_factory=dict)
    disputed: list[MemoryRecord] = field(default_factory=list)
    audit: list[str] = field(default_factory=list)

    def write(self, incoming: MemoryRecord, contradicts: bool) -> str:
        incumbent = self.slots.get(incoming.slot_id)
        if incumbent is None:
            self.slots[incoming.slot_id] = incoming
            return "accepted_new"

        # Fail closed on missing/flattened provenance.
        if not incoming.provenance_chain:
            incoming = MemoryRecord(
                **{**incoming.__dict__, "prov_class": ProvClass.MODEL_INFERRED}
            )

        # Invariant: weaker provenance may never overwrite a stronger incumbent.
        if incoming.prov_class < incumbent.prov_class and contradicts:
            anchor = self._resolve_anchor(incoming)
            if anchor is None or anchor in incumbent.provenance_chain:
                self.disputed.append(incoming)
                self.audit.append(
                    f"QUARANTINE slot={incoming.slot_id} "
                    f"write_class={incoming.prov_class.name} "
                    f"incumbent_class={incumbent.prov_class.name}"
                )
                raise ProvenanceDiscontinuity(
                    f"write to {incoming.slot_id} from {incoming.prov_class.name} "
                    f"cannot displace {incumbent.prov_class.name} without an "
                    f"independent anchor; quarantined as DISPUTED"
                )

        # Accept: version the record, preserve both provenances.
        new_version = MemoryRecord(
            **{
                **incoming.__dict__,
                "version": incumbent.version + 1,
                "supersedes": incumbent.version,
                "provenance_chain": incoming.provenance_chain
                + (f"superseded:{incumbent.prov_class.name}@{incumbent.first_observed}",),
            }
        )
        self.slots[incoming.slot_id] = new_version
        return "accepted_versioned"

    def _resolve_anchor(self, record: MemoryRecord) -> Optional[str]:
        # An anchor is the first link in the chain that predates the write.
        return record.provenance_chain[0] if record.provenance_chain else None


def ingest_web_claim(store: MemoryStore, slot: str, value: str, ts: float) -> str:
    incoming = MemoryRecord(
        slot_id=slot,
        value=value,
        prov_class=ProvClass.WEB_FETCH,
        provenance_chain=("web:research-subtask",),
        first_observed=ts,
        confidence=0.95,
    )
    return store.write(incoming, contradicts=True)


if __name__ == "__main__":
    store = MemoryStore()
    store.slots["api.rate_limit"] = MemoryRecord(
        slot_id="api.rate_limit",
        value="1000",
        prov_class=ProvClass.TOOL_VERIFIED,
        provenance_chain=("tool:read_rate_limit", "anchor:T0"),
        first_observed=100.0,
        confidence=0.81,
    )
    try:
        ingest_web_claim(store, "api.rate_limit", "50", ts=200.0)
    except ProvenanceDiscontinuity as e:
        print(f"BLOCKED: {e}")
        print(f"incumbent intact: {store.slots['api.rate_limit'].value}")
