# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-persist-a-tainted-memory-provenance-class-monotonicity-at-the-write-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-persist-a-tainted-memory-provenance-class-monotonicity-at-the-write-boundary.warrant.json
# Markdown SHA-256:   b30b2cad7ec637dacb5e6ad49292b6c56293888ad457a6724adb343baf1ef556
# Code AST SHA-256:   a07c6853eee2107476f81d9dada40ab522b22fca04963dc04140a56062beea5e
# Verified Classes:   Provenance, TaintLaunderingError, Span, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum


class Provenance(IntEnum):
    # Higher value = more trusted. Join is min(); promotion is forbidden.
    EXTERNAL_UNTRUSTED = 0
    TOOL_OBSERVED = 1
    FIRST_PARTY = 2


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would raise provenance above its sources' join."""


@dataclass(frozen=True)
class Span:
    text: str
    provenance: Provenance


@dataclass(frozen=True)
class MemoryRecord:
    key: str
    value: str
    provenance: Provenance


def join_provenance(sources: list[Span]) -> Provenance:
    if not sources:
        # Unknown lineage must default to least-trusted, never first-party.
        return Provenance.EXTERNAL_UNTRUSTED
    return Provenance(min(s.provenance for s in sources))


def distill_and_persist(
    store: dict[str, MemoryRecord],
    key: str,
    summary: str,
    sources: list[Span],
    asserted_class: Provenance | None = None,
) -> MemoryRecord:
    """Persist a distilled fact, enforcing monotonic-join provenance.

    `asserted_class` models the buggy path where the writer claims trust based
    on its own identity (e.g. source="distiller") rather than content lineage.
    """
    computed = join_provenance(sources)

    if asserted_class is not None and asserted_class > computed:
        raise TaintLaunderingError(
            f"write of {key!r} asserts {asserted_class.name} but sources join to "
            f"{computed.name}; refusing to launder taint into durable memory"
        )

    existing = store.get(key)
    if existing is not None:
        # Merge must be a join, not a max: least-trusted input governs.
        merged = Provenance(min(existing.provenance, computed))
        if merged > computed or merged > existing.provenance:
            raise TaintLaunderingError(
                f"merge of {key!r} would raise trust to {merged.name}; forbidden"
            )
        computed = merged

    record = MemoryRecord(key=key, value=summary, provenance=computed)
    store[key] = record
    return record


def render_for_context(record: MemoryRecord) -> str:
    """Untrusted records are shown as data, never as instruction channel."""
    if record.provenance < Provenance.FIRST_PARTY:
        return f"[DATA:{record.provenance.name}] {record.value}"
    return record.value
