# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-poisoned-memory-through-a-trusted-sibling-taint-lineage-collapse-at-write-audit-merge-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-poisoned-memory-through-a-trusted-sibling-taint-lineage-collapse-at-write-audit-merge-boundaries.warrant.json
# Markdown SHA-256:   258ac6f1e4c5448e48f72bf2f0cef1cc9ecea44488462c06a2cd8336160ad542
# Code AST SHA-256:   c0f90a53f5d3a57173e64120cf6b68998fd67630f1fd714c75b521236855b6ae
# Verified Classes:   TaintLineageSevered, MemoryRecord, WriteRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLineageSevered(RuntimeError):
    """Raised when a write consumed a retrieved record but declared no ancestry,
    severing the taint chain that poisoning detection depends on."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    content: str
    origin_trust: str            # "untrusted_external" | "trusted_internal"
    derived_from: list[str] = field(default_factory=list)


@dataclass
class WriteRequest:
    record_id: str
    content: str
    writer: str
    derived_from: list[str]
    reads_this_turn: list[str]  # record IDs the writer retrieved in this turn


def audit_write(req: WriteRequest, store: dict[str, MemoryRecord]) -> MemoryRecord:
    # Invariant: if the writer read anything this turn, the write must declare
    # ancestry for every read that plausibly informed it. Empty ancestry after a
    # retrieval is a taint-severance event, not a clean write.
    if req.reads_this_turn and not req.derived_from:
        raise TaintLineageSevered(
            f"write {req.record_id} by {req.writer} consumed reads "
            f"{req.reads_this_turn} but declared derived_from=[]; "
            f"taint lineage would be severed — quarantine required"
        )

    # Propagate the most-restrictive origin trust across declared ancestry.
    root_trust = "trusted_internal"
    for parent_id in req.derived_from:
        parent = store.get(parent_id)
        if parent is None:
            raise TaintLineageSevered(
                f"write {req.record_id} declares unknown parent {parent_id}"
            )
        if parent.origin_trust == "untrusted_external":
            root_trust = "untrusted_external"

    rec = MemoryRecord(
        record_id=req.record_id,
        content=req.content,
        origin_trust=root_trust,
        derived_from=list(req.derived_from),
    )
    store[rec.record_id] = rec
    return rec


def corroboration_confidence(record_ids: list[str], store: dict[str, MemoryRecord]) -> float:
    # Deduplicate by root ancestry: N paraphrases of one source are one evidence.
    roots: set[str] = set()

    def collect(rid: str) -> None:
        rec = store.get(rid)
        if rec is None:
            return
        if not rec.derived_from:
            roots.add(rid)
            return
        for parent in rec.derived_from:
            collect(parent)

    for rid in record_ids:
        collect(rid)
    return min(0.95, 0.3 + 0.3 * len(roots))
