# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-in-agent-provenance-graphs-when-tool-outputs-re-enter-memory-as-trusted-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-in-agent-provenance-graphs-when-tool-outputs-re-enter-memory-as-trusted-context.warrant.json
# Markdown SHA-256:   51b652f07337ac03bfa32ee281debc5e5dfaf7aa93ffda44a8afccd516a1480b
# Code AST SHA-256:   c4bbf27d206bec6a7e444afa28ab09b6d955ad9d7d086b115ac5993c4f159fbb
# Verified Classes:   TaintLaunderingError, Segment, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a derived write drops source taint labels."""


@dataclass(frozen=True)
class Segment:
    content: str
    labels: frozenset[str]

    def is_trusted(self) -> bool:
        return not any(lbl.startswith("untrusted:") for lbl in self.labels)


@dataclass
class MemoryRecord:
    content: str
    labels: frozenset[str]
    derived_from: tuple[str, ...] = field(default_factory=tuple)


def write_memory(
    derived_content: str,
    sources: Iterable[Segment],
    writer_label: str,
) -> MemoryRecord:
    """Persist a derived record, preserving the union of source taint labels.

    Invariant: labels(record) >= union(labels(source) for source in sources).
    The writer's own trust label is added but never substitutes for source taint.
    """
    sources = tuple(sources)
    if not sources:
        # No provenance: cannot prove non-derivation, so treat as untrusted.
        inherited = frozenset({"untrusted:unknown"})
    else:
        inherited = frozenset().union(*(s.labels for s in sources))

    proposed = inherited | {writer_label}

    # Guard: a derivation edge must not shrink the taint set.
    if not inherited.issubset(proposed):
        raise TaintLaunderingError(
            f"label shrinkage on derivation edge: inherited={sorted(inherited)} "
            f"proposed={sorted(proposed)}"
        )
    # Guard: if any source was untrusted, the record must remain untrusted.
    if any(not s.is_trusted() for s in sources) and not any(
        lbl.startswith("untrusted:") for lbl in proposed
    ):
        raise TaintLaunderingError(
            "derived record lost untrusted provenance; laundering detected"
        )

    return MemoryRecord(
        content=derived_content,
        labels=frozenset(proposed),
        derived_from=tuple(s.content[:32] for s in sources),
    )


def authorize_action(record: MemoryRecord, action: str, trusted_actions: set[str]) -> None:
    """Re-check labels at consumption time, not just write time."""
    if action in trusted_actions and not record.is_trusted():
        raise TaintLaunderingError(
            f"action {action!r} requires trusted provenance; "
            f"record carries {sorted(record.labels)}"
        )
