# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-cross-store-disagreement-as-memory-poisoning-rather-than-legitimate-consolidation-lag.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-cross-store-disagreement-as-memory-poisoning-rather-than-legitimate-consolidation-lag.warrant.json
# Markdown SHA-256:   a7772822e68d9851ca1fbf84f8c1458ad0d4e8fe937ad917e7ef728c6a45a083
# Code AST SHA-256:   1bcf56512fb4104fe037b5af377b728a0d034779d544967b18972385e6a97e7e
# Verified Classes:   ProvenanceClass, ProvenanceEdge, MemoryRecord, MemoryPoisoningError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ProvenanceClass(IntEnum):
    RETRIEVED_UNTRUSTED = 0
    MODEL_INFERRED = 1
    TOOL_VERIFIED = 2
    HUMAN = 3


@dataclass(frozen=True)
class ProvenanceEdge:
    source_id: str
    origin: ProvenanceClass
    timestamp: int


@dataclass(frozen=True)
class MemoryRecord:
    record_id: str
    store: str  # "episodic" | "semantic" | "procedural"
    content: str
    provenance: Optional[ProvenanceEdge]
    timestamp: int


class MemoryPoisoningError(RuntimeError):
    """Raised when cross-store divergence resolves toward recency rather than provenance."""


def audit_divergence(records: list[MemoryRecord], distillation_window: int) -> str:
    if not records:
        return "no_records"

    stores = {r.store for r in records}
    if len(stores) < 2:
        return "single_store_no_audit"

    # Condition 1: provenance must be total.
    for r in records:
        if r.provenance is None:
            raise MemoryPoisoningError(
                f"record {r.record_id} in store {r.store} has no provenance edge; "
                "audit unsound, fail closed on procedural derivation"
            )

    # Condition 3: any semantic record whose chain contains an untrusted node
    # without a corroborating verified edge is a poisoning candidate.
    for r in records:
        if r.store == "semantic" and r.provenance.origin == ProvenanceClass.RETRIEVED_UNTRUSTED:
            has_corroboration = any(
                other.provenance is not None
                and other.provenance.origin >= ProvenanceClass.TOOL_VERIFIED
                and other.content == r.content
                for other in records
            )
            if not has_corroboration:
                return f"candidate_poisoning:{r.record_id}"

    # Condition 2: reconciliation must be provenance-ordered, not recency-ordered.
    strongest = max(records, key=lambda r: (r.provenance.origin, -r.timestamp))
    most_recent = max(records, key=lambda r: r.timestamp)

    if strongest.record_id != most_recent.record_id:
        # Disagreement resolves toward recency only -> injection-then-laundering signature.
        if most_recent.provenance.origin < ProvenanceClass.TOOL_VERIFIED:
            raise MemoryPoisoningError(
                f"divergence resolves toward recency record {most_recent.record_id} "
                f"(origin={most_recent.provenance.origin.name}) over provenance-strongest "
                f"{strongest.record_id} (origin={strongest.provenance.origin.name}); "
                "treat as poisoning until provenance re-established"
            )

    # Legitimate consolidation lag: older store is subset/superset, monotonic chain.
    newest = max(records, key=lambda r: r.timestamp)
    oldest = min(records, key=lambda r: r.timestamp)
    if newest.timestamp - oldest.timestamp <= distillation_window:
        return "consolidation_lag"

    return "consistent"


def gate_procedural_write(semantic: MemoryRecord, chain: list[ProvenanceEdge]) -> None:
    if semantic.store != "semantic":
        raise MemoryPoisoningError(f"procedural gate expects semantic record, got {semantic.store}")
    if any(edge.origin == ProvenanceClass.RETRIEVED_UNTRUSTED for edge in chain):
        raise MemoryPoisoningError(
            f"procedural derivation blocked: semantic record {semantic.record_id} "
            "has untrusted node in provenance chain"
        )
    if not any(edge.origin >= ProvenanceClass.TOOL_VERIFIED for edge in chain):
        raise MemoryPoisoningError(
            f"procedural derivation blocked: semantic record {semantic.record_id} "
            "lacks a verified or human origin edge"
        )
