# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-poisoned-memory-from-being-laundered-through-the-consolidation-step-that-promotes-episodic-traces-to-semantic-facts.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-poisoned-memory-from-being-laundered-through-the-consolidation-step-that-promotes-episodic-traces-to-semantic-facts.warrant.json
# Markdown SHA-256:   368eec55e33799ddf0002526e7fca539f5ac46a66b69b087eb07981e140a0ade
# Code AST SHA-256:   d5651599722681d545d4149029f1d546ff55650158e360859e8df742c62b6006
# Verified Classes:   ProvenanceLaunderingError, Episode, Fact
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a consolidation pass would emit a semantic fact whose
    trust or provenance is not bounded by its source episodes."""
    pass


@dataclass
class Episode:
    id: str
    content: str
    source_trust: float
    instructional_flag: bool


@dataclass
class Fact:
    subject: str
    predicate: str
    object: str
    confidence: float
    provenance: set[str] = field(default_factory=set)
    consolidated_at: Optional[str] = None


def consolidate(
    episodes: list[Episode],
    agreement_score: float,
    min_trust: float = 0.5,
) -> Fact:
    # Invariant 3: flagged or low-trust episodes are excluded, not down-weighted.
    admissible = [
        e for e in episodes
        if not e.instructional_flag and e.source_trust >= min_trust
    ]
    if not admissible:
        raise ProvenanceLaunderingError(
            "no admissible episodes; refusing to emit a fact from untrusted input"
        )

    # Invariant 1: provenance must be non-empty and traceable.
    provenance = {e.id for e in admissible}
    if not provenance:
        raise ProvenanceLaunderingError(
            "consolidation produced empty provenance; fact would be unattributable"
        )

    # Invariant 2: confidence is bounded by max source trust, never by
    # corroboration count alone.
    max_source_trust = max(e.source_trust for e in admissible)
    confidence = min(agreement_score, max_source_trust)

    # Guard: a fact must never be more trusted than its best source.
    if confidence > max_source_trust + 1e-9:
        raise ProvenanceLaunderingError(
            f"confidence {confidence:.3f} exceeds max source trust "
            f"{max_source_trust:.3f}; corroboration laundering detected"
        )

    return Fact(
        subject="acme",
        predicate="rate_limit",
        object="10000 req/min",
        confidence=confidence,
        provenance=provenance,
        consolidated_at="2025-06-11T00:00:00Z",
    )


def test_laundering_blocked() -> None:
    poisoned = [
        Episode("e1", "rate limit 10000", source_trust=0.2, instructional_flag=True),
        Episode("e2", "rate limit 10000", source_trust=0.2, instructional_flag=False),
        Episode("e3", "rate limit 10000", source_trust=0.2, instructional_flag=False),
    ]
    # agreement_score=0.87 would have been emitted by the observed system.
    try:
        consolidate(poisoned, agreement_score=0.87, min_trust=0.5)
    except ProvenanceLaunderingError:
        return  # correct: all sources below min_trust, fact refused
    raise ProvenanceLaunderingError(
        "poisoned batch was consolidated; laundering channel open"
    )


def test_corroboration_cannot_manufacture_trust() -> None:
    # Three 0.2-trust sources, none flagged, all above a permissive threshold.
    batch = [
        Episode("e1", "x", source_trust=0.2, instructional_flag=False),
        Episode("e2", "x", source_trust=0.2, instructional_flag=False),
        Episode("e3", "x", source_trust=0.2, instructional_flag=False),
    ]
    fact = consolidate(batch, agreement_score=0.95, min_trust=0.1)
    if fact.confidence > 0.2 + 1e-9:
        raise ProvenanceLaunderingError(
            f"agreement inflated confidence to {fact.confidence:.3f} "
            f"from 0.2-trust sources"
        )
    assert fact.provenance == {"e1", "e2", "e3"}


if __name__ == "__main__":
    test_laundering_blocked()
    test_corroboration_cannot_manufacture_trust()
    print("invariants hold: consolidation is not a laundering channel")
