# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-poisoned-memory-write-before-provenance-weighted-trust-scoring-can-converge.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-poisoned-memory-write-before-provenance-weighted-trust-scoring-can-converge.warrant.json
# Markdown SHA-256:   45ed12a87ba7bbb99b6306bff377b7f979adaf35159f272b7fada9e860760510
# Code AST SHA-256:   a91e46674db794cd0436b2569b3139a7124f76726f9a4d0d2441e38171a1ed7d
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write claims higher provenance than a cited low-trust parent
    without an external attestation naming that parent."""
    pass


@dataclass
class MemoryEntry:
    entry_id: str
    source_id: str
    trust: float
    parent_hashes: list[str] = field(default_factory=list)
    quarantined: bool = False
    attestation: Optional[dict] = None  # {"parent": id, "reason": str, "attestor": id}


RETRIEVAL_FLOOR = 0.50


def effective_trust(entry: MemoryEntry, store: dict[str, MemoryEntry]) -> float:
    """Trust an entry is retrievable at. Descendants inherit the minimum of
    their parents unless an attestation explicitly promotes a named parent."""
    if entry.quarantined:
        return 0.0
    base = entry.trust
    for ph in entry.parent_hashes:
        parent = store.get(ph)
        if parent is None:
            continue
        if entry.attestation and entry.attestation.get("parent") == ph:
            continue  # explicitly promoted past this parent
        base = min(base, effective_trust(parent, store))
    return base


def admit_write(entry: MemoryEntry, store: dict[str, MemoryEntry]) -> MemoryEntry:
    """Enforce the laundering predicate before the write becomes retrievable."""
    low_trust_parents = [
        ph for ph in entry.parent_hashes
        if ph in store and effective_trust(store[ph], store) < RETRIEVAL_FLOOR
    ]
    if low_trust_parents:
        parent_sources = {store[ph].source_id for ph in low_trust_parents}
        claims_higher = entry.source_id not in parent_sources and entry.trust > RETRIEVAL_FLOOR
        if claims_higher:
            attested = entry.attestation is not None and entry.attestation.get("parent") in low_trust_parents
            if not attested:
                entry.quarantined = True
                raise ProvenanceLaunderingError(
                    f"write {entry.entry_id} cites low-trust parent(s) {low_trust_parents} "
                    f"but claims source {entry.source_id} at trust {entry.trust:.2f}; "
                    f"quarantined pending external attestation naming a specific parent"
                )
    store[entry.entry_id] = entry
    return entry


def retrieve(query_floor: float, store: dict[str, MemoryEntry]) -> list[MemoryEntry]:
    return [
        e for e in store.values()
        if not e.quarantined and effective_trust(e, store) >= query_floor
    ]
