# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-tag-decay-from-laundering-poisoned-memories-through-episodic-to-semantic-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-tag-decay-from-laundering-poisoned-memories-through-episodic-to-semantic-consolidation.warrant.json
# Markdown SHA-256:   be63e079635dec3a2dab9773004fdc581a515f7117b3860e4edac94ec1cb5982
# Code AST SHA-256:   ec32e0e37c1198b78c0dbbfa0c3835877548615b776cbb127d9980f564383683
# Verified Classes:   ProvenanceLaunderingError, MemoryRecord, ProvenanceStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived memory record's trust exceeds its ancestry bound."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    content: str
    source: str
    trust_tier: float
    derived_from: tuple[str, ...] = field(default_factory=tuple)


class ProvenanceStore:
    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}

    def add(self, rec: MemoryRecord) -> None:
        self._records[rec.record_id] = rec

    def effective_trust(self, record_id: str, _seen: Optional[set[str]] = None) -> float:
        seen = _seen if _seen is not None else set()
        if record_id in seen:
            raise ProvenanceLaunderingError(
                f"cyclic derivation detected at {record_id!r}"
            )
        seen.add(record_id)
        rec = self._records[record_id]
        if not rec.derived_from:
            return rec.trust_tier
        ancestor_min = min(self.effective_trust(a, seen) for a in rec.derived_from)
        return min(rec.trust_tier, ancestor_min)

    def admit_to_high_stakes(self, record_id: str, threshold: float) -> bool:
        rec = self._records[record_id]
        eff = self.effective_trust(record_id)
        if rec.trust_tier > eff + 1e-9:
            # stored trust was inflated by consolidation; do not clamp silently
            raise ProvenanceLaunderingError(
                f"record {record_id!r} stored trust {rec.trust_tier} exceeds "
                f"ancestry bound {eff}; consolidation is unsound"
            )
        return eff >= threshold
