# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-when-a-tool-output-is-re-ingested-as-trusted-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-when-a-tool-output-is-re-ingested-as-trusted-memory.warrant.json
# Markdown SHA-256:   de782ea7a894e2d90b852489eab04c9ffbb30e3d285c4eee0c32d111ad3cad3e
# Code AST SHA-256:   e987accc5f3cae2a17b356bae179dbf2631aa05bb1c98e1abddd8aa8fd98481b
# Verified Classes:   TaintLaunderingError, Provenance, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

TRUST_ORDER = {"untrusted": 0, "unverified": 1, "trusted": 2}


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would raise trust above its derivation set."""


@dataclass(frozen=True)
class Provenance:
    source: str
    trust: str
    taint_ids: frozenset = field(default_factory=frozenset)


@dataclass
class MemoryRecord:
    content: str
    provenance: Provenance
    derived_from: tuple


def _min_trust(derivations: Iterable[Provenance]) -> str:
    derivations = list(derivations)
    if not derivations:
        return "unverified"  # ungrounded: never authoritative
    return min((d.trust for d in derivations), key=lambda t: TRUST_ORDER[t])


def write_memory(
    content: str,
    claimed_trust: str,
    derived_from: tuple,
) -> MemoryRecord:
    if not content.strip():
        raise TaintLaunderingError("refusing to write empty memory record")

    # An agent-authored claim with no derivation set is ungrounded.
    if not derived_from and claimed_trust == "trusted":
        raise TaintLaunderingError(
            "ungrounded trusted write: no derivation set; "
            "content must cite source chunks or be downgraded"
        )

    inherited = _min_trust(derived_from)

    # The core invariant: trust may not increase along the derivation DAG.
    if TRUST_ORDER[claimed_trust] > TRUST_ORDER[inherited]:
        carried = frozenset().union(*(d.taint_ids for d in derived_from)) if derived_from else frozenset()
        raise TaintLaunderingError(
            f"taint laundering blocked: claimed trust={claimed_trust!r} "
            f"exceeds inherited trust={inherited!r} "
            f"(carried taint_ids={sorted(carried)})"
        )

    carried = frozenset().union(*(d.taint_ids for d in derived_from)) if derived_from else frozenset()
    return MemoryRecord(
        content=content,
        provenance=Provenance(source="agent:consolidation", trust=inherited, taint_ids=carried),
        derived_from=tuple(d.source for d in derived_from),
    )


def action_gate(record: MemoryRecord, action: str) -> None:
    if record.provenance.trust != "trusted":
        raise TaintLaunderingError(
            f"action {action!r} refused: memory trust={record.provenance.trust!r} "
            f"taint_ids={sorted(record.provenance.taint_ids)}"
        )
