# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-attacks-from-surviving-episodic-to-semantic-memory-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-attacks-from-surviving-episodic-to-semantic-memory-consolidation.warrant.json
# Markdown SHA-256:   d4ce9325643abc0ef814ef774dbe7459d1779aceaf800097df5887bd7f54ddf2
# Code AST SHA-256:   67023ca2959fd359019d1aef6de6b012bf52ce42ac465d89f7f82d001529b756
# Verified Classes:   ProvenanceLaunderingError, CrossTierContradictionError, EpisodicRecord, SemanticFact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Provenance = Literal["human", "internal_tool", "external_untrusted", "peer_agent"]


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a semantic write's trust exceeds its weakest episodic antecedent."""


class CrossTierContradictionError(RuntimeError):
    """Raised when a semantic fact conflicts with a trusted episodic record on the same subject."""


@dataclass
class EpisodicRecord:
    content: str
    subject: str
    provenance: Provenance
    trust: float


@dataclass
class SemanticFact:
    fact: str
    subject: str
    trust: float
    provenance_roots: set[str] = field(default_factory=set)


def consolidate(episodic: list[EpisodicRecord], distilled_trust: float, subject: str) -> SemanticFact:
    """Enforce the monotonicity invariant: semantic trust <= min(support trust)."""
    if not episodic:
        raise ProvenanceLaunderingError("consolidation with no episodic support")

    support_trust = min(r.trust for r in episodic)
    roots = {r.provenance for r in episodic}

    if distilled_trust > support_trust and len(roots) < 2:
        # Single-root trust inflation == laundering. Reject, do not clamp.
        raise ProvenanceLaunderingError(
            f"subject={subject!r} distilled_trust={distilled_trust} exceeds "
            f"support_trust={support_trust} with single provenance root {roots}. "
            f"Distiller likely dropped the provenance field."
        )

    return SemanticFact(
        fact=episodic[0].content,
        subject=subject,
        trust=min(distilled_trust, support_trust) if len(roots) < 2 else distilled_trust,
        provenance_roots=roots,
    )


def cross_tier_check(fact: SemanticFact, episodic_index: list[EpisodicRecord]) -> None:
    """Contradiction must be checked against the raw episodic tier, not the semantic tier."""
    trusted = [r for r in episodic_index if r.subject == fact.subject and r.provenance == "human"]
    for record in trusted:
        if record.content.strip() != fact.fact.strip():
            raise CrossTierContradictionError(
                f"semantic fact on {fact.subject!r} contradicts human episodic record "
                f"(trust={record.trust}); fact routed to quarantine, not promoted."
            )
