# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-the-provenance-graph-itself-is-written-by-the-agent-it-audits.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-the-provenance-graph-itself-is-written-by-the-agent-it-audits.warrant.json
# Markdown SHA-256:   fbda3f01cb16f95c5dd28f5118bed04e40ec965e61d2e98a1db9af5534044785
# Code AST SHA-256:   e32ae2f241aa8c344f3baaabacdc7569f2c05bf7db25143cbf4cd76bc2221306
# Verified Classes:   ProvenanceLaunderingError, ProvenanceGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory operation would destroy an indictment edge or
    silently re-target ancestry, invalidating self-audit."""
    pass


TRUSTED = {"internal", "corroborated"}
UNTRUSTED = {"external", "unverified"}


class ProvenanceGraph:
    def __init__(self, journal):
        # journal: append-only, externally anchored; agent cannot write it.
        self.journal = journal
        self.edges = {}      # node_id -> set of parent node_ids (immutable)
        self.trust = {}      # node_id -> frozen trust label at write time
        self.tombstoned = set()

    def write(self, node_id, parents, trust_label):
        self.edges[node_id] = set(parents)
        # Trust is the MIN over ancestry, frozen now, never recomputed.
        inherited = {self.trust.get(p, "unverified") for p in parents}
        effective = min(inherited | {trust_label},
                        key=lambda t: 0 if t in UNTRUSTED else 1)
        self.trust[node_id] = effective
        self.journal.append(("write", node_id, sorted(parents), effective))

    def forget(self, node_id):
        # Refuse to forget a node that is the last witness to another's taint.
        inbound = [n for n, ps in self.edges.items()
                   if node_id in ps and n not in self.tombstoned]
        if inbound:
            # Only permitted if the taint is already resolved for every child.
            unresolved = [n for n in inbound if self.trust.get(n) in UNTRUSTED]
            if unresolved:
                raise ProvenanceLaunderingError(
                    f"refusing forget({node_id}): it is the last ancestry "
                    f"witness for tainted surviving nodes {unresolved}; "
                    f"route through external journal or corroborate first."
                )
        self.tombstoned.add(node_id)
        # Edges are NOT removed and NOT re-targeted. They dangle, as evidence.
        self.journal.append(("forget", node_id))

    def consolidate(self, source_ids, summary_id):
        # Two-phase: inherit full edge set BEFORE tombstoning sources.
        inherited_parents = set()
        for s in source_ids:
            inherited_parents |= self.edges.get(s, set())
        # Inherit the WORST trust among sources; never recompute from neighbors.
        worst = min((self.trust.get(s, "unverified") for s in source_ids),
                    key=lambda t: 0 if t in UNTRUSTED else 1)
        self.edges[summary_id] = inherited_parents
        self.trust[summary_id] = worst
        self.journal.append(
            ("consolidate", summary_id, sorted(source_ids),
             sorted(inherited_parents), worst))
        for s in source_ids:
            # Tombstone but leave edges dangling; do not call forget() wholesale.
            self.tombstoned.add(s)
            self.journal.append(("tombstone", s))

    def audit(self, node_id):
        # Replay from journal, not from live graph, to detect cache divergence.
        journaled = self._replay_trust(node_id)
        if journaled != self.trust.get(node_id):
            raise ProvenanceLaunderingError(
                f"cache/journal trust divergence on {node_id}: "
                f"live={self.trust.get(node_id)} journal={journaled}"
            )
        return journaled

    def _replay_trust(self, node_id):
        trust = None
        for op in self.journal:
            if op[0] == "write" and op[1] == node_id:
                trust = op[3]
            elif op[0] == "consolidate" and op[1] == node_id:
                trust = op[4]
        return trust
