# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-counterfactual-replay-of-a-speculative-multi-agent-trace-rather-than-silently-re-derive-it.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-counterfactual-replay-of-a-speculative-multi-agent-trace-rather-than-silently-re-derive-it.warrant.json
# Markdown SHA-256:   7c1a065d8389ea29fef84e51c3554c62816d460ff4dc54c8a10697b1a1f2e42a
# Code AST SHA-256:   86c6cb7291dddba5ae4e56f4c336a33e8a5496302ead1fe0bacc4ed6db6ec2a2
# Verified Classes:   UnresolvableCounterfactual, Node, Trace
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Mapping


class UnresolvableCounterfactual(RuntimeError):
    """Raised when a counterfactual node cannot be reconstructed from the
    original trace's sealed input closure. Refusal is mandatory; re-derivation
    is forbidden because it yields a self-consistent but non-counterfactual
    execution wearing the original trace's identifiers."""
    pass


@dataclass(frozen=True)
class Node:
    node_id: str
    inputs: Mapping[str, str]          # input_name -> content_hash
    deterministic_given_inputs: bool
    read_flipped_decision_indirectly: bool = False


@dataclass(frozen=True)
class Trace:
    sealed_hashes: frozenset[str]
    nodes: Mapping[str, Node]


def reconstruct_counterfactual_node(
    trace: Trace,
    node: Node,
    flipped_decision_id: str,
) -> dict:
    # Condition 1: sealed input closure.
    open_inputs = [
        name for name, h in node.inputs.items() if h not in trace.sealed_hashes
    ]
    if open_inputs:
        raise UnresolvableCounterfactual(
            f"node {node.node_id!r} has open input closure "
            f"(unsealed inputs: {open_inputs}); refusing to re-derive "
            f"counterfactual of flip {flipped_decision_id!r}"
        )

    # Condition 2: causal isolation of the flip.
    if node.read_flipped_decision_indirectly:
        raise UnresolvableCounterfactual(
            f"node {node.node_id!r} observed flip {flipped_decision_id!r} "
            f"through a side channel not modeled as a trace edge; "
            f"blast radius exceeds control-flow DAG, marking unresolved"
        )

    # Condition 4: determinism of the replayed suffix.
    if not node.deterministic_given_inputs:
        raise UnresolvableCounterfactual(
            f"node {node.node_id!r} is nondeterministic and its "
            f"nondeterminism was not sealed; cannot re-execute safely"
        )

    # Safe: reconstruct by re-evaluating committed decision against sealed inputs.
    return {"node_id": node.node_id, "status": "reconstructed", "inputs": dict(node.inputs)}
