# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-write-boundary-between-poisoned-memory-and-legitimate-belief-revision-in-a-persistent-agent-store.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-write-boundary-between-poisoned-memory-and-legitimate-belief-revision-in-a-persistent-agent-store.warrant.json
# Markdown SHA-256:   ffb31f31c82afdfef31db7563b2a03243ead6da721e70cbf7bf99b1feecff90f
# Code AST SHA-256:   856d4976b0454c1522408ce5c25c5e3a81a858f00793880a27b628e7a9fc2742
# Verified Classes:   TrustClass, ProvenanceViolation, MemoryNode, ProvenanceStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import FrozenSet


class TrustClass(IntEnum):
    EXTERNAL_DERIVED = 0
    SELF_ORIGINATED = 1


class ProvenanceViolation(RuntimeError):
    """Raised when a memory node's trust lineage is inconsistent with its claimed class."""
    pass


@dataclass(frozen=True)
class MemoryNode:
    node_id: str
    claim: str
    confidence: float
    trust_class: TrustClass
    derivation_set: FrozenSet[str] = field(default_factory=frozenset)
    action_authorizing: bool = False


class ProvenanceStore:
    def __init__(self) -> None:
        self._nodes: dict[str, MemoryNode] = {}

    def write(self, node: MemoryNode, parent_ids: FrozenSet[str]) -> None:
        # Monotonic taint: class is min over full derivation DAG, never the author's claim.
        if parent_ids:
            parent_min = min(
                (self._nodes[p].trust_class for p in parent_ids), default=TrustClass.EXTERNAL_DERIVED
            )
            if node.trust_class > parent_min:
                raise ProvenanceViolation(
                    f"node {node.node_id} claims {node.trust_class.name} but derivation "
                    f"minimum is {parent_min.name}; trust cannot be laundered upward"
                )
        # Content-addressed dedup: identical claim + identical derivation is not corroboration.
        for existing in self._nodes.values():
            if existing.claim == node.claim and existing.derivation_set == node.derivation_set:
                return  # idempotent re-derivation, not a new confirmation
        self._nodes[node.node_id] = node

    def authorize_action(self, node_id: str) -> None:
        node = self._nodes[node_id]
        if node.action_authorizing and node.trust_class < TrustClass.SELF_ORIGINATED:
            raise ProvenanceViolation(
                f"refusing to promote {node_id} ({node.trust_class.name}) to action-authorizing "
                f"slot; route to first-party verification and write a supersedes edge"
            )
