# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-memory-write-boundaries-in-prompt-injection-provenance-tracking.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-memory-write-boundaries-in-prompt-injection-provenance-tracking.warrant.json
# Markdown SHA-256:   5d66dd9d71dba98d1de6081823ce37507038ac38ab88ad292d3790229dd9df11
# Code AST SHA-256:   275b72e9d107663b0f2bff4174d013954fd07d6e7447fa7f86de6373b6ac0108
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would clear taint that was present in context."""
    pass


TRUST_ORDER = {"untrusted:web": 0, "untrusted:tool": 0, "agent:derived": 1, "trusted:human": 2}


def join_taint(context_spans):
    """Least-trusted label across all spans present during generation."""
    if not context_spans:
        return "trusted:human"
    return min((s.provenance for s in context_spans), key=lambda p: TRUST_ORDER[p])


def write_memory(store, content, context_spans, claimed_provenance):
    """Enforce: a write influenced by tainted context cannot self-declare trusted."""
    required = join_taint(context_spans)
    if TRUST_ORDER[claimed_provenance] > TRUST_ORDER[required]:
        raise TaintLaunderingError(
            f"memory write claims {claimed_provenance!r} but context taint is "
            f"{required!r}; author-based labeling would launder injection"
        )
    store.append({"content": content, "provenance": required})
    return required
