# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-memory-poisoning-boundary-breach-in-persistent-agent-stores-the-provenance-gap-asymmetry-between-write-time-taint-a.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-memory-poisoning-boundary-breach-in-persistent-agent-stores-the-provenance-gap-asymmetry-between-write-time-taint-a.warrant.json
# Markdown SHA-256:   cee2b6e36b3267d141c4ec032c27688e9eb4bf3f56d1986b15bfeffc6153b1a3
# Code AST SHA-256:   bc06c574ade4a74a5d5bf5188f317e9cb7e18782a8f379356c5a6c6df2fb43f5
# Verified Classes:   Taint, ProvenanceLaunderingError, DanglingAncestryError, SourceDigest, MemoryRecord, PersistentStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class Taint(IntEnum):
    """Trust lattice. Higher = less trusted. Read gating fails closed toward UNTRUSTED."""
    TRUSTED = 0
    UNKNOWN = 1   # dangling ancestry: unverifiable, must not be treated as authoritative
    UNTRUSTED = 2


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write would set a taint lower than the join of its ancestry."""


class DanglingAncestryError(RuntimeError):
    """Raised when a record's derived_from references a source absent from the store."""


@dataclass(frozen=True)
class SourceDigest:
    source_id: str
    taint: Taint


@dataclass
class MemoryRecord:
    record_id: str
    write_taint: Taint
    derived_from: tuple[SourceDigest, ...] = field(default_factory=tuple)


class PersistentStore:
    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}

    def put_source(self, record: MemoryRecord) -> None:
        self._records[record.record_id] = record

    def contains(self, record_id: str) -> bool:
        return record_id in self._records

    def get(self, record_id: str) -> MemoryRecord:
        return self._records[record_id]


def join_taint(sources: tuple[SourceDigest, ...], store: PersistentStore) -> Taint:
    """Lattice join over ancestry. Dangling sources resolve to UNKNOWN (fail closed)."""
    if not sources:
        return Taint.TRUSTED
    worst = Taint.TRUSTED
    for src in sources:
        effective = src.taint if store.contains(src.source_id) else Taint.UNKNOWN
        if effective > worst:
            worst = effective
    return worst


def write_derived(
    store: PersistentStore,
    record_id: str,
    claimed_taint: Taint,
    derived_from: tuple[SourceDigest, ...],
) -> MemoryRecord:
    """Write a distilled/fan-in record. Enforces the taint-inversion invariant."""
    required = join_taint(derived_from, store)
    if claimed_taint < required:
        raise ProvenanceLaunderingError(
            f"record {record_id!r}: claimed taint {claimed_taint.name} "
            f"< ancestry join {required.name}; write would launder provenance"
        )
    record = MemoryRecord(record_id, claimed_taint, derived_from)
    store.put_source(record)
    return record


def read_for_context(store: PersistentStore, record_id: str) -> Taint:
    """Recompute effective taint at read time; never trust the stored label alone."""
    rec = store.get(record_id)
    recomputed = join_taint(rec.derived_from, store)
    effective = max(rec.write_taint, recomputed)
    if effective == Taint.UNKNOWN and rec.write_taint == Taint.TRUSTED:
        # Downgrade: trusted label with unverifiable ancestry is not authoritative.
        return Taint.UNKNOWN
    return effective


# --- demonstration of the laundering boundary ---
if __name__ == "__main__":
    store = PersistentStore()
    store.put_source(MemoryRecord("chunk-42", Taint.UNTRUSTED))

    # Correct distillation: taint is inherited.
    write_derived(
        store,
        record_id="fact-1",
        claimed_taint=Taint.UNTRUSTED,
        derived_from=(SourceDigest("chunk-42", Taint.UNTRUSTED),),
    )

    # Laundering attempt: distillation stamped with session taint.
    try:
        write_derived(
            store,
            record_id="fact-2",
            claimed_taint=Taint.TRUSTED,
            derived_from=(SourceDigest("chunk-42", Taint.UNTRUSTED),),
        )
    except ProvenanceLaunderingError as exc:
        print(f"blocked: {exc}")

    # Dangling ancestry downgrades a trusted label at read time.
    store.put_source(
        MemoryRecord(
            "fact-3",
            Taint.TRUSTED,
            derived_from=(SourceDigest("chunk-evicted", Taint.TRUSTED),),
        )
    )
    assert read_for_context(store, "fact-3") == Taint.UNKNOWN
