# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundered-memory-writes-when-the-audit-diff-converges-on-a-poisoned-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundered-memory-writes-when-the-audit-diff-converges-on-a-poisoned-consensus.warrant.json
# Markdown SHA-256:   cf477f6d6c7426a222e5a9947a478e29fbfaab91032c0c08556d2de8dd22cb2b
# Code AST SHA-256:   fbf8ca1686019ba3d7a1671cdd2430cf0b4f110d7feb1d05ae9ec7b455a6dc1a
# Verified Classes:   AncestryDriftError, ProvenanceLaunderingError, ProvenanceNode, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class AncestryDriftError(RuntimeError):
    """Raised when a memory record's provenance ancestry was rewritten after write time."""
    pass


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a drifted record's trust was recomputed from a laundered ancestry."""
    pass


@dataclass(frozen=True)
class ProvenanceNode:
    node_id: str
    parents: tuple
    payload: str

    def content_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.node_id.encode())
        h.update(self.payload.encode())
        for p in sorted(self.parents):
            h.update(p.encode())
        return h.hexdigest()


@dataclass
class MemoryRecord:
    claim: str
    ancestry_ids: tuple
    trust_at_write: float
    ancestry_hash_at_write: str


def audit_record(record: MemoryRecord, live_graph: dict) -> str:
    """Re-derive ancestry hash from the live graph and compare to frozen hash.

    Returns 'clean' only if ancestry is hash-stable AND trust matches.
    """
    h = hashlib.sha256()
    for nid in sorted(record.ancestry_ids):
        node = live_graph.get(nid)
        if node is None:
            raise AncestryDriftError(
                f"ancestor {nid} of record {record.claim!r} no longer resolvable"
            )
        h.update(node.content_hash().encode())
    live_hash = h.hexdigest()

    if live_hash != record.ancestry_hash_at_write:
        raise AncestryDriftError(
            f"record {record.claim!r}: ancestry rewritten "
            f"(frozen={record.ancestry_hash_at_write[:12]} live={live_hash[:12]}) "
            f"-- possible provenance laundering; quarantine"
        )

    rederived_trust = min(
        live_graph[nid].payload.count("verified") for nid in record.ancestry_ids
    )
    if rederived_trust < record.trust_at_write:
        raise ProvenanceLaunderingError(
            f"record {record.claim!r}: trust_at_write={record.trust_at_write} "
            f"exceeds re-derived trust={rederived_trust} from frozen ancestry"
        )
    return "clean"
