# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-summarization-provenance-label-collapse-when-an-injected-instruction-survives-an-agent-s-own.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-summarization-provenance-label-collapse-when-an-injected-instruction-survives-an-agent-s-own.warrant.json
# Markdown SHA-256:   ddd8c1db9e2750d4704fe167a49239c1b99fd64042fa0876c178844de10a1d52
# Code AST SHA-256:   7d0ebb72834ec6477f2a4c7e985f9380abbf408291ab68407409a1ae7f303435
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a trust-gated sink would accept a record whose content
    overlaps a tainted operand but whose label was stamped by the transform."""
    pass


# Declared per transform: does its output possibly contain operand substrings?
TRANSFORM_PRESERVES_SUBSTRINGS = {
    "summarize": True,
    "extract_fields": True,
    "classify_enum": False,   # fixed-schema, cannot carry free-text payload
}


def propagate_label(transform: str, operand_label: str, node_trust: str) -> str:
    """Label algebra: meet over operand and node, gated by substring preservation."""
    if TRANSFORM_PRESERVES_SUBSTRINGS.get(transform) is None:
        raise TaintLaunderingError(
            f"transform {transform!r} has no declared substring policy; "
            "cannot compute a sound output label"
        )
    if TRANSFORM_PRESERVES_SUBSTRINGS[transform]:
        # Taint-preserving: output inherits the operand's (worse) label.
        return worst(operand_label, node_trust)
    # Span-destroying: node trust is legitimate.
    return node_trust


def worst(a: str, b: str) -> str:
    order = {"TRUSTED": 0, "INTERNAL": 1, "EXTERNAL": 2, "TAINTED": 3}
    return a if order[a] >= order[b] else b


def write_memory(record: dict, spans: list[dict]) -> None:
    """Sink gate: label is meet over every span, computed at write time."""
    if not spans:
        raise TaintLaunderingError(
            f"record {record.get('id')!r} has no span provenance; "
            "record-level label alone is unsound"
        )
    effective = "TRUSTED"
    for span in spans:
        effective = worst(effective, span["label"])
    if effective in ("EXTERNAL", "TAINTED"):
        raise TaintLaunderingError(
            f"refusing to persist record {record.get('id')!r}: "
            f"effective label {effective} from span provenance, "
            f"despite record stamp {record.get('label')!r}"
        )
    record["effective_label"] = effective
    # ... persist ...
