# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-prompt-injection-through-its-own-episodic-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-prompt-injection-through-its-own-episodic-memory.warrant.json
# Markdown SHA-256:   db0d1f767983f069a7a3d56e134f8c5b77f629686647dc36f5a87fa2a19331b3
# Code AST SHA-256:   55532046fe566537c715755cb074ba11aaa2865221a856e8f59a47023e73379a
# Verified Classes:   Provenance, TaintPromotionError, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from enum import IntEnum
from dataclasses import dataclass, field


class Provenance(IntEnum):
    SELF = 0
    DERIVED_FROM_EXTERNAL = 1
    EXTERNAL = 2


class TaintPromotionError(RuntimeError):
    """Raised when a memory write would upgrade taint above its inputs."""
    pass


@dataclass
class MemoryRecord:
    content: str
    provenance: Provenance
    sources: tuple = field(default_factory=tuple)


def distill(source: MemoryRecord, summary: str) -> MemoryRecord:
    # Derived memory inherits the *maximum* taint of its inputs (i.e. min trust).
    inherited = max(source.provenance, Provenance.DERIVED_FROM_EXTERNAL)
    return MemoryRecord(content=summary, provenance=inherited, sources=(source, ))


def write_memory(store: list, record: MemoryRecord, claimed: Provenance) -> None:
    # Guardrail: a write may never claim a *lower* taint number (higher trust)
    # than the record actually carries. This is the monotonicity invariant.
    if claimed < record.provenance:
        raise TaintPromotionError(
            f"write claims provenance={claimed.name} but record carries "
            f"{record.provenance.name}; taint promotion is forbidden"
        )
    store.append(record)


def authorize_action(record: MemoryRecord, mutates_external_state: bool) -> bool:
    if not mutates_external_state:
        return True
    if record.provenance >= Provenance.DERIVED_FROM_EXTERNAL:
        # Secondhand claims may inform reasoning but cannot authorize mutation
        # without re-verification against the original source.
        raise TaintPromotionError(
            f"record provenance={record.provenance.name} cannot authorize "
            f"external mutation without re-verification"
        )
    return True
