# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-trust-scores-from-laundering-poisoned-memories-during-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-trust-scores-from-laundering-poisoned-memories-during-consolidation.warrant.json
# Markdown SHA-256:   995308ad891077b0e016aff4270cc6cf30f657c3bdcc4ad13ae699a9a8107405
# Code AST SHA-256:   dc70952a1d0d9a5f08aa5dfffb1f1b31567b133d82350ce91ce12c44718e4f56
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

TAU = 0.60
EPS = 1e-6


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived memory's claimed trust exceeds what its provenance closure supports."""


@dataclass
class MemoryEntry:
    id: str
    claim: str
    trust: float
    provenance: list[str] = field(default_factory=list)  # ids of supporting entries
    rejected: bool = False


def resolve_closure(entry: MemoryEntry, store: dict[str, MemoryEntry],
                    seen: Optional[set[str]] = None) -> tuple[set[str], list[MemoryEntry]]:
    """Return (leaf_ids, leaves). Raises if any provenance pointer dangles."""
    seen = seen or set()
    if entry.id in seen:
        raise ProvenanceLaunderingError(f"cycle detected at {entry.id}")
    seen.add(entry.id)
    if not entry.provenance:
        return {entry.id}, [entry]
    leaf_ids: set[str] = set()
    leaves: list[MemoryEntry] = []
    for pid in entry.provenance:
        src = store.get(pid)
        if src is None:
            raise ProvenanceLaunderingError(
                f"dangling provenance {pid!r} referenced by {entry.id!r}; quarantine, do not admit"
            )
        lids, ls = resolve_closure(src, store, seen)
        leaf_ids |= lids
        leaves.extend(ls)
    return leaf_ids, leaves


def admit_derived(entry: MemoryEntry, store: dict[str, MemoryEntry]) -> float:
    """Enforce min-bounded derivation + taint persistence. Returns admitted trust."""
    leaf_ids, leaves = resolve_closure(entry, store)

    if any(l.rejected for l in leaves):
        # rejected material cannot be resurrected by re-derivation
        return 0.0

    min_trust = min(l.trust for l in leaves)
    recomputed = min_trust  # invariant: derived <= min(support)

    if entry.trust > recomputed + EPS:
        raise ProvenanceLaunderingError(
            f"entry {entry.id!r} claims trust {entry.trust:.3f} but closure min is "
            f"{recomputed:.3f} (inflation {entry.trust - recomputed:.3f}); reject as laundering"
        )

    if recomputed < TAU:
        return recomputed  # admitted below gate; downstream retrieval must not surface it

    return recomputed
