# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-across-a-memory-write-boundary-even-when-every-tool-output-was-correctly-labeled.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-across-a-memory-write-boundary-even-when-every-tool-output-was-correctly-labeled.warrant.json
# Markdown SHA-256:   da2ddd529ad67449785c07f508b64472d65b89779bbc648df878e313f9f2bc1f
# Code AST SHA-256:   621a4d3a05f028334d9da37c9a57f9bd0d641bc6e129b17617ec64b91b667215
# Verified Classes:   Taint, TaintLaunderingError, MemoryRecord, Context
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1  # join is max(); sticky upward


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would relabel tainted content as trusted."""


@dataclass
class MemoryRecord:
    text: str
    label: Taint
    provenance: tuple[str, ...] = ()


@dataclass
class Context:
    # taint-set of every labeled value currently resident in the window
    resident: dict[str, Taint] = field(default_factory=dict)

    def join(self) -> Taint:
        return max(self.resident.values(), default=Taint.TRUSTED)


def write_memory(
    ctx: Context,
    payload: str,
    model_declared_label: Taint,
    cited_sources: Iterable[str],
    is_verbatim_projection: bool,
) -> MemoryRecord:
    cited = tuple(cited_sources)
    cited_join = max((ctx.resident.get(s, Taint.TRUSTED) for s in cited), default=Taint.TRUSTED)

    if is_verbatim_projection:
        # content is a structural copy of the cited source; cite label is sound
        effective = cited_join
    else:
        # model-authored paraphrase: the citation is not evidence.
        # label must be the join over the ENTIRE resident context.
        effective = ctx.join()

    # a model-declared TRUSTED label may never lower a derived UNTRUSTED label
    if model_declared_label == Taint.TRUSTED and effective == Taint.UNTRUSTED:
        raise TaintLaunderingError(
            f"memory write would launder taint: cited={cited} "
            f"cited_join={cited_join.name} context_join={effective.name} "
            f"declared={model_declared_label.name}"
        )

    record = MemoryRecord(text=payload, label=effective, provenance=cited)
    ctx.resident[f"mem:{hash(payload) & 0xffff:x}"] = effective
    return record


def read_memory(record: MemoryRecord, ctx: Context) -> str:
    # taint re-enters the working context on read; it does not decay
    ctx.resident[f"mem:{hash(record.text) & 0xffff:x}"] = record.label
    return record.text
