# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-writes-from-surviving-the-semantic-distillation-pass-in-persistent-agent-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-writes-from-surviving-the-semantic-distillation-pass-in-persistent-agent-memory-stores.warrant.json
# Markdown SHA-256:   7837f6f3e92140d920e56e6e4c59923d79b3327d4ecc7378f9c13794d8fa10fb
# Code AST SHA-256:   6cbd19274f16f9bbb43cdcf4b1a5616a0d9b88b8d3edd8b22cfc099dadea7d02
# Verified Classes:   ProvenanceLaunderingError, Episode, SemanticAssertion
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Trust = Literal["untrusted_external", "derived", "verified", "system"]
_TRUST_ORDER = {"untrusted_external": 0, "derived": 1, "verified": 2, "system": 3}


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a semantic write would carry higher trust than its provenance closure permits."""


@dataclass(frozen=True)
class Episode:
    episodic_id: str
    trust: Trust


@dataclass
class SemanticAssertion:
    fact: str
    provenance: list[str]
    claimed_trust: Trust
    effective_trust: Trust = field(default="untrusted_external")


def _min_trust(trusts: list[Trust]) -> Trust:
    if not trusts:
        # Orphan assertion: no provenance means no basis for elevation.
        return "untrusted_external"
    return min(trusts, key=lambda t: _TRUST_ORDER[t])


def validate_semantic_write(
    assertion: SemanticAssertion,
    episodic_index: dict[str, Episode],
    distiller_trust: Trust,
) -> SemanticAssertion:
    """
    Enforce taint-preserving distillation. The distiller's trust applies to the
    act of distillation, never to the content distilled.
    """
    missing = [pid for pid in assertion.provenance if pid not in episodic_index]
    if missing:
        raise ProvenanceLaunderingError(
            f"provenance references unknown episodes {missing}; "
            f"cannot compute trust closure for fact {assertion.fact!r}"
        )

    ancestor_trusts = [episodic_index[pid].trust for pid in assertion.provenance]
    closure_min = _min_trust(ancestor_trusts)
    permitted = _min_trust([closure_min, distiller_trust])

    if _TRUST_ORDER[assertion.claimed_trust] > _TRUST_ORDER[permitted]:
        # Demote + quarantine rather than drop: preserve the injection signal.
        assertion.effective_trust = permitted
        raise ProvenanceLaunderingError(
            f"claimed trust {assertion.claimed_trust!r} exceeds provenance closure "
            f"minimum {permitted!r} for fact {assertion.fact!r}; "
            f"demoted to {permitted!r} and quarantined"
        )

    assertion.effective_trust = permitted
    return assertion
