# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-write-provenance-drift-from-silently-laundering-poisoned-memory-past-contradiction-checks.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-write-provenance-drift-from-silently-laundering-poisoned-memory-past-contradiction-checks.warrant.json
# Markdown SHA-256:   65cfd8dc6c1cb67c9fd1b02e4f499e5c7e8759f92cba212a28597012e22d9d66
# Code AST SHA-256:   2171ebb0c2d4b71b5d15bb733a72a450b896b0a60be52df1737557c2f9a3560d
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry, TieredStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Tier = Literal["human_correction", "tool_output", "peer_agent", "self_reflection"]

PROVENANCE: dict[Tier, float] = {
    "human_correction": 0.95,
    "tool_output": 0.55,
    "peer_agent": 0.50,
    "self_reflection": 0.45,
}

ADMISSION_FLOOR = 0.40
CONFLICT_DISSIMILARITY = 0.62


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write's only support is at or below its own provenance tier,
    or when admitting it would evict a higher-provenance assertion of the same
    proposition. This is the signature of consensus manufacturing."""


@dataclass
class MemoryEntry:
    proposition: str
    provenance: float
    tier: Tier
    last_access_days: float = 0.0
    support_count: int = 0


@dataclass
class TieredStore:
    entries: list[MemoryEntry] = field(default_factory=list)

    def max_provenance_for(self, proposition: str) -> float:
        matching = [e.provenance for e in self.entries if e.proposition == proposition]
        return max(matching) if matching else 0.0

    def highest_tier_supported(self, proposition: str, tier_floor: float) -> bool:
        return any(
            e.proposition == proposition and e.provenance >= tier_floor
            for e in self.entries
        )


def admit_write(
    store: TieredStore,
    candidate: MemoryEntry,
    *,
    contradicts_high_tier: bool,
    eviction_would_remove: str | None,
) -> str:
    """Returns 'admit' | 'quarantine' | 'reject'. Raises ProvenanceLaunderingError
    when the candidate is the terminal write of a laundering sequence."""

    p = candidate.provenance

    if p < ADMISSION_FLOOR:
        return "reject"

    # The invariant: contradiction baseline is restricted to entries at or above
    # the candidate's own provenance tier.
    if contradicts_high_tier:
        return "reject"

    # If admitting this write would evict a higher-provenance assertion of the
    # same proposition, the baseline is being mutated to make future poison
    # locally consistent. This is the laundering boundary.
    if eviction_would_remove is not None:
        evicted_prov = store.max_provenance_for(eviction_would_remove)
        if evicted_prov > p:
            raise ProvenanceLaunderingError(
                f"write of {candidate.proposition!r} at provenance {p:.2f} would "
                f"evict {eviction_would_remove!r} at provenance {evicted_prov:.2f}; "
                f"eviction must not reduce the store's highest-tier assertion below "
                f"the candidate's own tier"
            )

    # If the candidate has no support at or above its own tier, it is
    # quarantine-eligible: it may be true, but it cannot form its own baseline.
    if not store.highest_tier_supported(candidate.proposition, p):
        return "quarantine"

    return "admit"


def replay_laundering_sequence(store: TieredStore) -> None:
    # Phase 1: 40 low-tier seeds asserting eu-west-2 with no high-tier backing.
    for i in range(40):
        seed = MemoryEntry(
            proposition="staging_region=eu-west-2",
            provenance=PROVENANCE["peer_agent"],
            tier="peer_agent",
        )
        verdict = admit_write(
            store,
            seed,
            contradicts_high_tier=False,
            eviction_would_remove="production_region=us-east-1",
        )
        if verdict == "admit":
            store.entries.append(seed)
            raise ProvenanceLaunderingError(
                f"seed {i} was admitted to the general store; it should have been "
                f"quarantined because its only support is at or below its own tier"
            )

    # Phase 3: the poison write. Under the corrected boundary this must be
    # quarantined or rejected, never admitted.
    poison = MemoryEntry(
        proposition="failover_target=eu-west-2",
        provenance=PROVENANCE["peer_agent"],
        tier="peer_agent",
    )
    verdict = admit_write(
        store,
        poison,
        contradicts_high_tier=store.highest_tier_supported("failover_target=eu-west-2", 0.95),
        eviction_would_remove=None,
    )
    if verdict == "admit":
        raise ProvenanceLaunderingError(
            "poison write admitted: contradiction baseline was reshaped by prior "
            "low-tier seeds and the high-tier assertion was evicted"
        )
