# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-own-successful-writes-become-indistinguishable-from-injected-poison-in-a-content-addressed-memory-store.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-own-successful-writes-become-indistinguishable-from-injected-poison-in-a-content-addressed-memory-store.warrant.json
# Markdown SHA-256:   cecabb233e2d4cdeed3c955f8e3f80db6e30a86e150d520fc658ee91fc497e13
# Code AST SHA-256:   a62663b74e5a379101485f55f8b55686bf3bcf2c5424931ded7e56af0a97c87c
# Verified Classes:   Trust, ProvenanceLaunderingError, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class Trust(IntEnum):
    UNTRUSTED = 0
    TOOL = 1
    DISTILLED = 2
    VERIFIED = 3


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived record's trust exceeds its lineage's minimum."""


@dataclass
class MemoryRecord:
    claim: str
    provenance: Trust
    novelty: float
    contradicts: list[str] = field(default_factory=list)
    lineage: Optional[list["MemoryRecord"]] = None


def admit(record: MemoryRecord, existing: list[MemoryRecord]) -> bool:
    # Invariant 1: distillation must not exceed the trust of its sources.
    if record.provenance == Trust.DISTILLED:
        if not record.lineage:
            raise ProvenanceLaunderingError(
                f"distilled record {record.claim!r} has no lineage; "
                "trust cannot be established"
            )
        floor = min(src.provenance for src in record.lineage)
        if floor < Trust.DISTILLED:
            raise ProvenanceLaunderingError(
                f"record {record.claim!r} claims DISTILLED but lineage floor "
                f"is {floor.name}; laundering through summarization detected"
            )

    # Invariant 2: confirmatory poison signature — untrusted + low novelty +
    # no contradiction. Reject outright; do not treat as clean.
    if (
        record.provenance <= Trust.TOOL
        and record.novelty < 0.30
        and not record.contradicts
    ):
        raise ProvenanceLaunderingError(
            f"confirmatory-poison signature on {record.claim!r}: "
            "untrusted source, low novelty, no contradiction"
        )

    # Invariant 3: novelty is only a signal when conditioned on provenance.
    if record.provenance == Trust.DISTILLED and record.novelty > 0.85:
        if not record.lineage:
            raise ProvenanceLaunderingError(
                f"high-novelty distilled record {record.claim!r} requires "
                "lineage for re-derivation, not novelty-based quarantine"
            )
        # Re-derivable: admit, verifier will re-check against raw origins.
        return True

    return True
