# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-the-write-path-and-the-audit-path-disagree-on-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-the-write-path-and-the-audit-path-disagree-on-provenance.warrant.json
# Markdown SHA-256:   8ce3bf5222985940348a11570eb1fbc6235c49db8077d7c05780295f8c29fe88
# Code AST SHA-256:   dfb3ea9bc6dc2e433d190b61b84958479cdc67967114815ba123223e9ebaf097
# Verified Classes:   ProvenanceDivergenceError, Node, Record
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

MAX_HOPS = 8
TRUST_ORDER = {"untrusted": 0, "internal": 1, "trusted": 2}


class ProvenanceDivergenceError(RuntimeError):
    """Raised when a record's lineage cannot be reconciled to trusted roots."""


@dataclass
class Node:
    node_id: str
    kind: str  # "root" | "transform" | "origin"
    content_trust: str
    inputs: list[str] = field(default_factory=list)


@dataclass
class Record:
    record_id: str
    declared_trust: str
    sources: list[str]


def reconcile(record: Record, trail: dict[str, Node]) -> str:
    """Walk lineage transitively to a fixed point; return effective trust.

    Raises ProvenanceDivergenceError if lineage does not close within MAX_HOPS
    or if any source is missing from the append-only trail.
    """
    if not record.sources:
        raise ProvenanceDivergenceError(
            f"record {record.record_id} has empty provenance; cannot audit"
        )

    effective = TRUST_ORDER[record.declared_trust]
    frontier = list(record.sources)
    seen: set[str] = set()
    hops = 0

    while frontier:
        hops += 1
        if hops > MAX_HOPS:
            raise ProvenanceDivergenceError(
                f"record {record.record_id} lineage exceeds {MAX_HOPS} hops; "
                f"unclosed provenance must be quarantined"
            )
        next_frontier = []
        for node_id in frontier:
            if node_id in seen:
                continue
            seen.add(node_id)
            node = trail.get(node_id)
            if node is None:
                raise ProvenanceDivergenceError(
                    f"record {record.record_id} references {node_id} "
                    f"absent from evidence trail; lineage open"
                )
            effective = min(effective, TRUST_ORDER[node.content_trust])
            if node.kind == "transform":
                # A transform inherits taint from its inputs: keep walking.
                next_frontier.extend(node.inputs)
            elif node.kind == "origin" and not node.inputs:
                pass  # terminal origin; nothing further to walk
            elif node.kind == "origin" and node.inputs:
                raise ProvenanceDivergenceError(
                    f"node {node_id} labeled origin but carries inputs; "
                    f"laundering write suspected"
                )
        frontier = next_frontier

    if effective < TRUST_ORDER[record.declared_trust]:
        raise ProvenanceDivergenceError(
            f"record {record.record_id} declared {record.declared_trust} "
            f"but lineage reconciles to {effective_trust_name(effective)}"
        )
    return effective_trust_name(effective)


def effective_trust_name(level: int) -> str:
    for name, val in TRUST_ORDER.items():
        if val == level:
            return name
    raise ProvenanceDivergenceError(f"unknown trust level {level}")
