# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-quarantine-a-poisoned-episodic-memory-before-semantic-distillation-and-why-provenance-scoring-alone-cannot-stop-the-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-quarantine-a-poisoned-episodic-memory-before-semantic-distillation-and-why-provenance-scoring-alone-cannot-stop-the-propagation.warrant.json
# Markdown SHA-256:   6beb4132d2fc01f63324fce920b40bfe853141976caee58304a317f2fc299e83
# Code AST SHA-256:   ddc92ff33b66a1f81f3af822885ae1fde68d4644c0b0debacac5f348977d31f6
# Verified Classes:   TrustLaunderingError, ProvenanceLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class TrustLaunderingError(RuntimeError):
    """Raised when distillation would mint a semantic fact whose trust exceeds
    the minimum trust of its source episodes, or when the cursor advances past
    an unresolved/quarantined episode."""


class ProvenanceLedger:
    def __init__(self, retrieval_floor: float = 0.6):
        self.episodes = {}          # hash -> {"trust": float, "status": str}
        self.facts = {}             # fact_id -> {"trust": float, "derived_from": list}
        self.cursor = 0
        self.retrieval_floor = retrieval_floor

    def record_episode(self, ep_hash: str, trust: float, status: str = "clean") -> None:
        self.episodes[ep_hash] = {"trust": trust, "status": status}

    def quarantine(self, ep_hash: str) -> None:
        if ep_hash not in self.episodes:
            raise TrustLaunderingError(f"cannot quarantine unknown episode {ep_hash}")
        self.episodes[ep_hash]["status"] = "quarantined"

    def distill(self, fact_id: str, derived_from: list[str], summarizer_confidence: float) -> None:
        # Condition 2: cursor-gated quarantine.
        for ep_hash in derived_from:
            ep = self.episodes.get(ep_hash)
            if ep is None:
                raise TrustLaunderingError(f"fact {fact_id} cites missing episode {ep_hash}")
            if ep["status"] == "quarantined":
                raise TrustLaunderingError(
                    f"cursor blocked: fact {fact_id} derives from quarantined episode {ep_hash}"
                )
            if ep["status"] == "unresolved":
                raise TrustLaunderingError(
                    f"cursor blocked: episode {ep_hash} awaiting adjudication before distillation"
                )

        # Condition 1: trust monotonicity across derivation.
        lineage_trust = min(self.episodes[h]["trust"] for h in derived_from)
        minted_trust = lineage_trust  # summarizer_confidence is deliberately ignored
        if minted_trust > lineage_trust:
            raise TrustLaunderingError(
                f"trust laundering: fact {fact_id} would mint at {minted_trust} "
                f"exceeding lineage min {lineage_trust}"
            )
        self.facts[fact_id] = {"trust": minted_trust, "derived_from": list(derived_from)}

    def compact(self) -> None:
        # Condition 3: lineage survivability — never GC a cited episode.
        cited = {h for f in self.facts.values() for h in f["derived_from"]}
        self.episodes = {h: e for h, e in self.episodes.items() if h in cited or e["status"] != "clean"}


def run_distillation_batch(ledger: ProvenanceLedger, batch: list[dict]) -> None:
    for item in batch:
        if item["trust"] < ledger.retrieval_floor and item["status"] == "clean":
            # Retrieval filter would have hidden this; distillation must still see it.
            ledger.quarantine(item["hash"])
        ledger.distill(
            fact_id=item["fact_id"],
            derived_from=item["derived_from"],
            summarizer_confidence=item["confidence"],
        )
    ledger.compact()
