# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-provenance-laundered-memory-poisoning-when-a-poisoned-fact-is-re-derived-from-clean-sources.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-provenance-laundered-memory-poisoning-when-a-poisoned-fact-is-re-derived-from-clean-sources.warrant.json
# Markdown SHA-256:   36285346572303ea8ded943faaf2d2ec928d7041cbff56988893f9e5712d81f4
# Code AST SHA-256:   5694bd40f97367563bc9f6ef4805db4fb79f8c1eddd2c2c4d7ed0a83330c7a5c
# Verified Classes:   ProvenanceLaunderingError, Entry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

SIMILARITY_THRESHOLD = 0.90

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a trusted write restates a tainted/evicted claim without a trusted derivation path."""
    pass

@dataclass
class Entry:
    claim: str
    sources: list
    derivation_parents: list = field(default_factory=list)
    taint: str = "TRUSTED"
    embedding: Optional[list] = None

def cosine(a: list, b: list) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = sum(x * x for x in a) ** 0.5
    nb = sum(y * y for y in b) ** 0.5
    return dot / (na * nb) if na and nb else 0.0

def write_entry(new: Entry, store: list, tainted_or_evicted: list) -> Entry:
    # Write-local trust check (necessary, not sufficient)
    if any(src not in TRUSTED_SOURCES for src in new.sources):
        new.taint = "UNTRUSTED"
        store.append(new)
        return new

    # Closure / provenance-orphan audit: does this trusted write restate a poisoned claim?
    for prior in tainted_or_evicted:
        if prior.embedding is None or new.embedding is None:
            continue
        if cosine(new.embedding, prior.embedding) >= SIMILARITY_THRESHOLD:
            has_trusted_path = any(
                p in TRUSTED_SOURCES for p in new.derivation_parents
            )
            if not has_trusted_path:
                raise ProvenanceLaunderingError(
                    f"Trusted write restates tainted/evicted claim (sim={cosine(new.embedding, prior.embedding):.2f}) "
                    f"with no trusted derivation path. Quarantine required."
                )
    store.append(new)
    return new

TRUSTED_SOURCES = {"trusted_doc_A", "trusted_doc_B"}
