# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-across-memory-write-handoffs-when-a-poisoned-fact-is-re-attested-by-a-trusted-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-across-memory-write-handoffs-when-a-poisoned-fact-is-re-attested-by-a-trusted-agent.warrant.json
# Markdown SHA-256:   6d870a3f659eefb176a382c3be54d248cfb7e79dcf60d946b588b058b6fad90e
# Code AST SHA-256:   796f07f09ad6c34ceaa251fe9d73cd254cf5123fb0cc2ea9dfd2c37e5cfebde4
# Verified Classes:   ProvenanceLaunderingError, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived-record write would sever ancestry or exceed the trust floor."""
    pass

@dataclass
class MemoryRecord:
    record_id: str
    content: str
    source: str
    source_trust: int          # 0..3, higher = more trusted
    derived_from: tuple = ()   # ancestor record_ids; MUST be non-empty for derived records
    effective_trust: Optional[int] = None

TRUST = {"scraper": 0, "synthesizer": 1, "auditor": 3}

def compute_effective_trust(rec: MemoryRecord, store: dict) -> int:
    floor = rec.source_trust
    for anc_id in rec.derived_from:
        anc = store.get(anc_id)
        if anc is None:
            raise ProvenanceLaunderingError(
                f"record {rec.record_id} references missing ancestor {anc_id}; "
                "ancestry edge severed (fail-closed)"
            )
        anc_eff = anc.effective_trust if anc.effective_trust is not None else compute_effective_trust(anc, store)
        floor = min(floor, anc_eff)
    return floor

def write_derived(rec: MemoryRecord, store: dict, is_derived: bool) -> MemoryRecord:
    if is_derived and not rec.derived_from:
        raise ProvenanceLaunderingError(
            f"derived record {rec.record_id} has empty derived_from; "
            "would launder provenance (schema must require ancestor IDs)"
        )
    rec.effective_trust = compute_effective_trust(rec, store)
    store[rec.record_id] = rec
    return rec

def promote(rec_id: str, store: dict, threshold: int) -> MemoryRecord:
    rec = store[rec_id]
    eff = rec.effective_trust if rec.effective_trust is not None else compute_effective_trust(rec, store)
    if eff >= threshold:
        return rec
    # require two ancestry-disjoint corroborating records
    ancestors = set(rec.derived_from)
    corroborators = [
        r for r in store.values()
        if r.record_id != rec_id
        and r.content == rec.content
        and not (set(r.derived_from) & ancestors)
        and not (set(r.derived_from) & {rec_id})
    ]
    if len(corroborators) < 2:
        raise ProvenanceLaunderingError(
            f"cannot promote {rec_id} above floor {eff}: needs 2 ancestry-disjoint "
            f"attestations, found {len(corroborators)}"
        )
    rec.effective_trust = threshold
    return rec
