# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-tainted-memory-through-episodic-to-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-tainted-memory-through-episodic-to-semantic-distillation.warrant.json
# Markdown SHA-256:   ca84d7950bcd4bfab6c3fd99a899e73a9f77d1a39feb1a92b300f57138fca3ca
# Code AST SHA-256:   274d9be0721229a085e3aa8da4234f3e013246f3afd301055d746e762ec3f8aa
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a distilled memory fact enters the trusted tier without
    a proven-clean derivation set, indicating a possible laundering path."""
    pass


TAINTED = "TAINT:external"
CLEAN = "CLEAN"


def distill_to_semantic(episodic_spans, trusted_tier, quarantine_tier):
    """
    episodic_spans: list of dicts with keys 'text' and 'label'.
    Returns the tier the distilled fact was written to.
    Raises TaintLaunderingError if a fact derived from tainted content
    is about to be written to the trusted tier without attestation.
    """
    derivation_set = {span["label"] for span in episodic_spans}
    fact_text = _summarize(episodic_spans)  # generative step: label-laundering oracle

    # The fact's own label is NOT trustworthy; only the derivation set is.
    if TAINTED in derivation_set:
        attested_sources = _attribution(fact_text, episodic_spans)
        if not attested_sources or any(
            s["label"] == TAINTED for s in attested_sources
        ):
            # Fail closed: cannot prove clean derivation -> quarantine.
            quarantine_tier.write(fact_text, label=TAINTED)
            return "quarantine"
        # Attested clean, but attribution is probabilistic; only safe for
        # read-only reasoning, never for side-effecting justification.
        quarantine_tier.write(fact_text, label="TAINT:attested")
        return "quarantine"

    trusted_tier.write(fact_text, label=CLEAN)
    return "trusted"


def action_gate(action, justification_facts):
    """
    Blocks side-effecting actions whose justification chain includes any
    fact from a non-trusted tier, regardless of the fact's content label.
    """
    for fact in justification_facts:
        if fact.tier != "trusted":
            raise TaintLaunderingError(
                f"Action {action.name!r} justified by fact from tier "
                f"{fact.tier!r}; possible taint laundering via distillation."
            )
    return True
