# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-boundaries-when-a-retrieved-memory-fragment-carries-an-injected-instruction-that-was-laundered-through-a-prior-se.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-boundaries-when-a-retrieved-memory-fragment-carries-an-injected-instruction-that-was-laundered-through-a-prior-se.warrant.json
# Markdown SHA-256:   a69decd3850f1c9567939a81e442988565ef70bdcc4ca05d4f07d5dce7a4fd32
# Code AST SHA-256:   bb630b0ce4e604ed2ede30eab99cbfd4d0a549ae27da0d27f7d14f4736433196
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a distilled memory fragment would cross a session boundary
    carrying less taint than its source episodes. The fragment's imperative
    force survived reformulation while its provenance did not."""
    pass


TRUST_ORDER = {"tainted": 0, "quarantined": 1, "internal": 2}


def distill_and_promote(source_episodes, distilled_facts, target_session):
    """
    source_episodes: list of dicts with 'taint' in {tainted, internal}
    distilled_facts: list of dicts produced by the summarizer, each with 'text'
    target_session: session id requesting promotion into shared semantic store

    Invariant: max taint of the batch bounds the taint of every output.
    A fragment may be promoted to 'internal' only if every source was 'internal'.
    """
    batch_taint = min(
        (ep["taint"] for ep in source_episodes),
        key=lambda t: TRUST_ORDER[t],
    )

    promoted = []
    for fact in distilled_facts:
        if batch_taint == "internal":
            fact["trust"] = "internal"
            fact["scope"] = "shared"
        else:
            fact["trust"] = "quarantined"
            fact["scope"] = "session"
            fact["origin_session"] = source_episodes[0]["session"]

        # The chokepoint: refuse to let a tainted fragment reach a session
        # that did not produce it, even as a quarantined belief, unless the
        # caller explicitly opted into unverified hypotheses.
        if fact["scope"] == "session" and target_session != fact["origin_session"]:
            if not fact.get("allow_unverified"):
                raise TaintLaunderingError(
                    f"fragment {fact.get('id')!r} carries batch taint "
                    f"{batch_taint!r} from session {fact['origin_session']!r} "
                    f"but was requested for session {target_session!r}; "
                    f"imperative force survived distillation, provenance did not"
                )
        promoted.append(fact)

    return promoted


def taint_preservation_rate(distilled_records):
    """Operational metric: should be 1.0. Drift means a distillation path
    is dropping the source-episode join and laundering taint."""
    if not distilled_records:
        return 1.0
    preserved = sum(
        1 for r in distilled_records
        if TRUST_ORDER[r["trust"]] <= TRUST_ORDER[r["batch_max_taint"]]
    )
    rate = preserved / len(distilled_records)
    if rate < 1.0:
        raise TaintLaunderingError(
            f"taint-preservation rate {rate:.3f} < 1.0: "
            f"{len(distilled_records) - preserved} fragments lost provenance"
        )
    return rate
