# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-when-a-tool-output-is-laundered-through-a-memory-write-the-label-laundering-boundary-in-prompt-injection-inform.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-when-a-tool-output-is-laundered-through-a-memory-write-the-label-laundering-boundary-in-prompt-injection-inform.warrant.json
# Markdown SHA-256:   c72391974948a45d6525ec2d6db0545d8afecb0c5fa8704010389ccfc5c18fd4
# Code AST SHA-256:   cff2c82fe83a2a2c3b633d545f254df6d5db6fd41bdf139ddf5a90ccc0926cdb
# Verified Classes:   Taint, ProvenanceLaunderingError, MemoryEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    TRUSTED = 0
    DERIVED = 1          # trusted only if derivation chain is complete & join-correct
    UNTRUSTED_EXTERNAL = 2

    def join(self, other: "Taint") -> "Taint":
        return Taint(max(int(self), int(other)))


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write would lower the taint lattice position of a
    value derived from a previously-labeled segment, or when a read encounters
    a trusted:derived entry whose derivation chain is incomplete."""


@dataclass
class MemoryEntry:
    key: str
    value: str
    label: Taint
    producer: str
    derived_from: list[str] = field(default_factory=list)  # keys of inputs consumed


def write_memory(
    store: dict[str, MemoryEntry],
    key: str,
    value: str,
    producer: str,
    input_keys: list[str],
    declared_label: Optional[Taint] = None,
) -> MemoryEntry:
    # Compute the join over ALL transitive inputs actually consumed.
    join_label = Taint.TRUSTED
    for ik in input_keys:
        if ik not in store:
            # Cannot see an input's taint -> fail closed, do not upgrade trust.
            join_label = join_label.join(Taint.UNTRUSTED_EXTERNAL)
            continue
        join_label = join_label.join(store[ik].label)

    # A summarizer/extractor consuming untrusted text is an impure producer;
    # its output inherits the join, never the producer's own trust level.
    effective = join_label if join_label > Taint.TRUSTED else Taint.DERIVED

    if declared_label is not None and declared_label < effective:
        raise ProvenanceLaunderingError(
            f"write '{key}' from producer '{producer}' would launder taint: "
            f"declared {declared_label.name} < join {effective.name} "
            f"over inputs {input_keys}"
        )

    entry = MemoryEntry(
        key=key, value=value, label=effective,
        producer=producer, derived_from=list(input_keys),
    )
    store[key] = entry
    return entry


def read_memory(store: dict[str, MemoryEntry], key: str) -> MemoryEntry:
    if key not in store:
        raise ProvenanceLaunderingError(f"read of unknown key '{key}'")
    entry = store[key]
    # A trusted:derived entry must have a resolvable, non-empty derivation chain.
    if entry.label == Taint.DERIVED:
        if not entry.derived_from:
            raise ProvenanceLaunderingError(
                f"entry '{key}' labeled DERIVED with empty derivation chain; "
                f"cannot upgrade trust on read"
            )
        for parent in entry.derived_from:
            if parent not in store:
                raise ProvenanceLaunderingError(
                    f"entry '{key}' derivation edge to '{parent}' unresolvable; "
                    f"provenance truncated, treating as untrusted"
                )
    return entry


def guarded_action(store: dict[str, MemoryEntry], key: str, action: str) -> None:
    entry = read_memory(store, key)
    if entry.label >= Taint.UNTRUSTED_EXTERNAL:
        raise ProvenanceLaunderingError(
            f"refusing privileged action '{action}' driven by tainted entry "
            f"'{key}' (label={entry.label.name}); declassification warrant required"
        )
    # proceed with action
