# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundered-memory-writes-when-consolidation-rewrites-the-anomaly-score-it-was-supposed-to-preserve.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundered-memory-writes-when-consolidation-rewrites-the-anomaly-score-it-was-supposed-to-preserve.warrant.json
# Markdown SHA-256:   b8c9b8304a7cfb477d9e650b4254ce8b2d694c256c590a3c3b3b1ffa4d6b277c
# Code AST SHA-256:   0e24753c6b8c5fad3bd45425294697b38b85866150475b6cd017f6f549200358
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ProvenanceLaunderingError(RuntimeError):
    """Raised when consolidation would raise provenance or clear a taint bit."""


@dataclass(frozen=True)
class MemoryEntry:
    entry_id: str
    content: str
    provenance: float          # 0.0 (untrusted) .. 1.0 (trusted)
    tainted: bool              # anomaly bit; monotone under consolidation
    source_ids: tuple[str, ...] = field(default_factory=tuple)


def consolidate(cluster: Iterable[MemoryEntry], summary_id: str, summary_text: str) -> MemoryEntry:
    """Lineage-scored consolidation: provenance is the meet, taint is the OR.

    The summary's score is bounded above by the worst contributor, and it is
    tainted if ANY contributor was tainted. A consolidation that would produce
    a higher score than its worst source, or that would clear a taint bit,
    is laundering and must be rejected.
    """
    members = list(cluster)
    if not members:
        raise ProvenanceLaunderingError("cannot consolidate an empty cluster")

    worst = min(m.provenance for m in members)
    any_tainted = any(m.tainted for m in members)
    sources = tuple(sorted({sid for m in members for sid in m.source_ids}))

    derived = MemoryEntry(
        entry_id=summary_id,
        content=summary_text,
        provenance=worst,
        tainted=any_tainted,
        source_ids=sources,
    )

    # Invariant checks: the derived entry may not exceed its lineage.
    if derived.provenance > worst + 1e-9:
        raise ProvenanceLaunderingError(
            f"summary {summary_id} provenance {derived.provenance} exceeds "
            f"worst contributor {worst}"
        )
    if any_tainted and not derived.tainted:
        raise ProvenanceLaunderingError(
            f"summary {summary_id} cleared taint inherited from {sources}"
        )
    return derived


def admit_to_recall(entry: MemoryEntry, min_provenance: float = 0.5) -> bool:
    """Recall gate: tainted lineage is excluded regardless of current score."""
    if entry.tainted:
        return False
    if entry.provenance < min_provenance:
        return False
    return True


def consolidate_or_reject(cluster: Iterable[MemoryEntry], summary_id: str, text: str) -> MemoryEntry:
    derived = consolidate(cluster, summary_id, text)
    if derived.tainted and derived.provenance >= 0.8:
        # A tainted entry with a high score is the signature of laundering
        # that slipped past the meet (e.g. an upstream bug). Refuse to admit.
        raise ProvenanceLaunderingError(
            f"tainted summary {summary_id} scored {derived.provenance}; "
            "refusing admission pending auditor review"
        )
    return derived
