# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-divergence-when-a-trajectory-trace-replays-clean-but-the-decision-graph-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-divergence-when-a-trajectory-trace-replays-clean-but-the-decision-graph-does-not.warrant.json
# Markdown SHA-256:   c64f2de1e6b14fe70c9b83e5cfc2afa2c670101d226b3424b13940f808f7b6f0
# Code AST SHA-256:   90dd856e8f51a21e213be9b5888a92ac87decfa41a6389bd16a11de3ca80e2cd
# Verified Classes:   ProvenanceDivergence, Node, Edge, DecisionGraph
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Optional


class ProvenanceDivergence(RuntimeError):
    """Raised when a replayed decision graph is not causally equivalent to the recorded one."""
    pass


@dataclass
class Node:
    node_id: str
    recorded_input: bytes
    recorded_output: bytes
    warrant_digest: Optional[str] = None
    has_action_authority: bool = False


@dataclass
class Edge:
    src: str
    dst: str
    # policy: "strict" | "snapshot" | "warrant"
    policy: str = "strict"
    frozen_at_record_time: bool = False


@dataclass
class DecisionGraph:
    nodes: Dict[str, Node] = field(default_factory=dict)
    edges: List[Edge] = field(default_factory=list)

    def outgoing(self, node_id: str) -> List[Edge]:
        return [e for e in self.edges if e.src == node_id]

    def reaches_action(self, start: str, seen: Optional[set] = None) -> bool:
        seen = seen or set()
        if start in seen:
            return False
        seen.add(start)
        node = self.nodes[start]
        if node.has_action_authority:
            return True
        return any(self.reaches_action(e.dst, seen) for e in self.outgoing(start))


def replay_graph(
    graph: DecisionGraph,
    replay_node: Callable[[Node], bytes],
    warrant_of: Callable[[Node], str],
) -> None:
    """Replay a decision graph under the edge-recomputation invariant.

    Raises ProvenanceDivergence if any live edge fails re-derivation, or if a
    demoted (snapshot) edge is reachable to an action node.
    """
    replayed_output: Dict[str, bytes] = {}

    for node_id, node in graph.nodes.items():
        # Snapshot-pinned edges may not sit above the action frontier.
        if any(
            e.policy == "snapshot" and e.frozen_at_record_time
            for e in graph.edges
            if e.dst == node_id
        ):
            if graph.reaches_action(node_id):
                raise ProvenanceDivergence(
                    f"node {node_id}: snapshot-pinned edge reaches action frontier; "
                    f"demotion across an action boundary is not permitted"
                )

        out = replay_node(node)
        replayed_output[node_id] = out

        # Edge-recomputation invariant: downstream inputs must be re-derivable
        # from upstream replayed outputs for every strict edge.
        for edge in graph.outgoing(node_id):
            if edge.policy == "strict":
                downstream = graph.nodes[edge.dst]
                recomputed = _recompute_input(out, downstream)
                if recomputed != downstream.recorded_input:
                    raise ProvenanceDivergence(
                        f"edge {edge.src}->{edge.dst}: recomputed input "
                        f"{hashlib.sha256(recomputed).hexdigest()[:12]} != recorded "
                        f"{hashlib.sha256(downstream.recorded_input).hexdigest()[:12]}"
                    )
            elif edge.policy == "warrant":
                downstream = graph.nodes[edge.dst]
                live = warrant_of(downstream)
                if downstream.warrant_digest is not None and live != downstream.warrant_digest:
                    raise ProvenanceDivergence(
                        f"edge {edge.src}->{edge.dst}: warrant digest drift "
                        f"{live[:12]} != {downstream.warrant_digest[:12]}"
                    )


def _recompute_input(upstream_output: bytes, downstream: Node) -> bytes:
    # Domain-specific: the downstream input is a pure function of upstream output.
    # In practice this is the prompt-construction / argument-binding function.
    return upstream_output.strip()
