# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-retrieval-provenance-gaps-in-long-horizon-memory-writes-and-the-consistency-audit-invariant-that-bounds-them.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-retrieval-provenance-gaps-in-long-horizon-memory-writes-and-the-consistency-audit-invariant-that-bounds-them.warrant.json
# Markdown SHA-256:   36d7f16e8c957170ff200967ca9615bc8f47a965c5b42082236b5c110c3c1963
# Code AST SHA-256:   f28ed081a8af7c4429d533b705c7a9c1fd3536d0d0e2659be179b57922fa8f7b
# Verified Classes:   ProvenanceAuditError, MemoryWrite
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceAuditError(RuntimeError):
    """Raised when a memory promotion violates the ancestry-disjointness invariant."""
    pass


@dataclass
class MemoryWrite:
    episode_id: int
    claim: str
    origin: str                      # "agent_reasoning" | "tool_output" | "user_input" | "fetch"
    parent_episode: Optional[int]
    tool_trace_hash: Optional[str]
    ancestry: set = field(default_factory=set)


def compute_ancestry(write: MemoryWrite, store: dict) -> set:
    """Transitively resolve the full reachable ancestry set for a write."""
    seen = set()
    frontier = [write]
    while frontier:
        w = frontier.pop()
        for node in (w.parent_episode, w.tool_trace_hash):
            if node is None or node in seen:
                continue
            seen.add(node)
            parent = store.get(node)
            if parent is not None:
                frontier.append(parent)
    return seen


def audit_promotion(claim: str, writes: list, store: dict, untrusted_origins: set) -> bool:
    """
    Return True iff `claim` has at least two writes whose ancestry sets are
    disjoint at every untrusted-origin node. Otherwise raise.
    """
    asserting = [w for w in writes if w.claim == claim]
    if len(asserting) < 2:
        raise ProvenanceAuditError(
            f"claim {claim!r} has {len(asserting)} write(s); need >=2 for promotion"
        )

    ancestries = []
    for w in asserting:
        anc = compute_ancestry(w, store)
        if not anc and w.tool_trace_hash is None and w.parent_episode is None:
            raise ProvenanceAuditError(
                f"write at episode {w.episode_id} has empty ancestry; provenance forged or truncated"
            )
        ancestries.append(anc)

    # Check pairwise disjointness at the untrusted boundary.
    for i in range(len(ancestries)):
        for j in range(i + 1, len(ancestries)):
            shared_untrusted = {
                node for node in (ancestries[i] & ancestries[j])
                if store.get(node) is not None
                and store[node].origin in untrusted_origins
            }
            if not shared_untrusted:
                return True

    shared = ancestries[0] & ancestries[1]
    raise ProvenanceAuditError(
        f"claim {claim!r} corroboration is spurious: writes share untrusted ancestry {shared}"
    )
