# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-provenance-consistent-memory-write-that-arrives-through-a-legitimately-authorized-retrieval-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-provenance-consistent-memory-write-that-arrives-through-a-legitimately-authorized-retrieval-channel.warrant.json
# Markdown SHA-256:   6ae5fa5ff38fb65bf0234b08c0f2d9b2bdbec617052d598f8179d5ca176fae7e
# Code AST SHA-256:   c978432456a6b0832376978119304c096e8c47745b860777bc0fdf27e3299623
# Verified Classes:   TaintState, MemoryAdmissionError, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TaintState(Enum):
    CLEAN = "clean"          # conditioned only on trusted sources
    TAINTED = "tainted"      # conditioned on >=1 untrusted source
    UNKNOWN = "unknown"      # taint-set absent / uncomputable


class MemoryAdmissionError(RuntimeError):
    """Raised when a provenance-valid record is rejected on content-integrity grounds."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    writer: str
    session: str
    warrant_verified: bool
    taint: Optional[TaintState]          # None == field absent in payload
    taint_sources: frozenset = field(default_factory=frozenset)
    quarantined: bool = False


def admit(record: MemoryRecord, writer_has_untrusted_input: bool) -> bool:
    """
    Two-predicate admission. Provenance AND content-integrity must both hold.
    Provenance verification alone is insufficient for writers that ingest
    untrusted channels.
    """
    if not record.warrant_verified:
        raise MemoryAdmissionError(
            f"{record.record_id}: provenance chain failed verification"
        )

    # Normalize: a missing taint field is UNKNOWN, never CLEAN.
    taint = record.taint if record.taint is not None else TaintState.UNKNOWN

    if taint is TaintState.UNKNOWN:
        # Absence of evidence is not evidence of absence.
        raise MemoryAdmissionError(
            f"{record.record_id}: taint-set absent; cannot certify content "
            f"integrity for writer {record.writer} (fail-closed)"
        )

    if taint is TaintState.TAINTED:
        if not record.quarantined:
            raise MemoryAdmissionError(
                f"{record.record_id}: provenance valid but content conditioned on "
                f"untrusted sources {sorted(record.taint_sources)}; "
                f"must be quarantined, not admitted to trusted namespace"
            )
        # Quarantined tainted records are admissible only into quarantine.
        return True

    # taint is CLEAN
    if writer_has_untrusted_input and not record.taint_sources:
        # A clean taint-set from a writer with untrusted input surface is
        # plausible only if the ledger confirms no untrusted source was touched.
        # Caller must have cross-checked the authoritative taint ledger.
        pass
    return True


def promote_from_quarantine(record: MemoryRecord, rederived: bool) -> MemoryRecord:
    """Promotion requires re-derivation, not re-signing."""
    if not rederived:
        raise MemoryAdmissionError(
            f"{record.record_id}: promotion requires re-derivation with taint "
            f"carried into the distiller prompt; re-signing is insufficient"
        )
    return MemoryRecord(
        record_id=record.record_id,
        writer=record.writer,
        session=record.session,
        warrant_verified=True,
        taint=TaintState.CLEAN,
        taint_sources=frozenset(),
        quarantined=False,
    )
