# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-survives-write-time-provenance-scoring-the-cross-session-consistency-invariant-and-the-provenance-la.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-survives-write-time-provenance-scoring-the-cross-session-consistency-invariant-and-the-provenance-la.warrant.json
# Markdown SHA-256:   e2e0844f0c4c722c903a95ebfb404f95bb685d8d98881d731ff071a08a9baa19
# Code AST SHA-256:   e973588a4f8a71326577607b6334510595709f5083c7093e03f19ecfb76f1fcd
# Verified Classes:   ProvenanceMonotonicityError, SelfCorroborationError, MemoryRecord, ProvenanceGuardedStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceMonotonicityError(RuntimeError):
    """Raised when a write would displace an authoritative record at lower trust."""
    pass


class SelfCorroborationError(RuntimeError):
    """Raised when a memory's only corroboration is itself (source-graph cycle)."""
    pass


@dataclass
class MemoryRecord:
    key: str
    value: str
    trust_score: float
    source_id: str
    authoritative: bool = False
    superseded_by: Optional[str] = None
    superseded_at: Optional[str] = None
    corroborating_sources: list = field(default_factory=list)


class ProvenanceGuardedStore:
    def __init__(self):
        self._live = {}
        self._retained = []  # prior versions, never destroyed
        self._quarantine = []

    def commit(self, incoming: MemoryRecord, now: str) -> None:
        target = self._live.get(incoming.key)
        if target is not None and target.authoritative:
            # Invariant: displacement of an authoritative record requires
            # the incoming write's OWN trust to meet or exceed the target's.
            # Never blend, never inherit the region's score.
            if incoming.trust_score < target.trust_score:
                self._quarantine.append((incoming, now))
                raise ProvenanceMonotonicityError(
                    f"write {incoming.source_id} trust={incoming.trust_score} "
                    f"cannot displace authoritative {target.source_id} "
                    f"trust={target.trust_score} for key={incoming.key}"
                )
            # Retain prior version so consistency can still see displacement.
            target.superseded_by = incoming.source_id
            target.superseded_at = now
            self._retained.append(target)
        self._live[incoming.key] = incoming

    def check_corroboration(self, record: MemoryRecord) -> None:
        # A record whose only corroboration is its own source is self-referential.
        independent = [s for s in record.corroborating_sources if s != record.source_id]
        if record.authoritative and not independent:
            raise SelfCorroborationError(
                f"memory key={record.key} corroborated only by its own source "
                f"{record.source_id}; source-graph independence required"
            )

    def consistency_pass(self) -> list:
        events = []
        for prior in self._retained:
            live = self._live.get(prior.key)
            if live is not None and live.value != prior.value:
                events.append({
                    "key": prior.key,
                    "prior": prior.value,
                    "prior_trust": prior.trust_score,
                    "live": live.value,
                    "live_trust": live.trust_score,
                    "displaced_by": live.source_id,
                })
        return events
