# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-speculative-branch-after-rollback-when-the-reconciliation-witness-is-reconstructed-from-logs-rather-than-carried.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-speculative-branch-after-rollback-when-the-reconciliation-witness-is-reconstructed-from-logs-rather-than-carried.warrant.json
# Markdown SHA-256:   7418aba18b41dd71fdbc82679963845e47ff0a143ca74504a1df18d13cae5086
# Code AST SHA-256:   753e0bda912b83cda32d28a1e7e312afde26de10670164d7e3f85ada642bc215
# Verified Classes:   WitnessReconstructionError, Witness, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class WitnessReconstructionError(RuntimeError):
    """Raised when a reconciler attempts to merge on a replayed (reconstructed) witness
    instead of a carried (committed) witness, or when carried and replayed witnesses diverge."""


@dataclass(frozen=True)
class Witness:
    branch_id: str
    effect_set: frozenset
    precondition_hash: str
    postcondition_predicate: str
    seq_vector: tuple
    provenance: str  # "carried" | "replayed"
    signature: Optional[str] = None

    def digest(self) -> str:
        h = hashlib.sha256()
        h.update(self.branch_id.encode())
        h.update(repr(sorted(self.effect_set)).encode())
        h.update(self.precondition_hash.encode())
        h.update(self.postcondition_predicate.encode())
        h.update(repr(self.seq_vector).encode())
        return h.hexdigest()


@dataclass
class Branch:
    branch_id: str
    deterministic: bool
    carried_witness: Optional[Witness] = None
    committed_effects: frozenset = field(default_factory=frozenset)


def commit(branch: Branch, effect_set: frozenset, precondition_hash: str,
           postcondition_predicate: str, seq_vector: tuple) -> Witness:
    w = Witness(
        branch_id=branch.branch_id,
        effect_set=effect_set,
        precondition_hash=precondition_hash,
        postcondition_predicate=postcondition_predicate,
        seq_vector=seq_vector,
        provenance="carried",
    )
    branch.carried_witness = w
    branch.committed_effects = effect_set
    return w


def replay(branch: Branch, tool_fn, inputs) -> Witness:
    """Reconstruct a witness by re-executing the branch's tools. Sound ONLY for
    deterministic branches with complete output logs. Never use as merge ground truth."""
    replayed_effects = frozenset(tool_fn(inputs))
    return Witness(
        branch_id=branch.branch_id,
        effect_set=replayed_effects,
        precondition_hash=branch.carried_witness.precondition_hash,
        postcondition_predicate=branch.carried_witness.postcondition_predicate,
        seq_vector=branch.carried_witness.seq_vector,
        provenance="replayed",
    )


def reconcile(branches, tool_fns, inputs):
    """Merge branches by comparing CARRIED witnesses. Replay is audit-only."""
    carried = []
    for b in branches:
        if b.carried_witness is None:
            raise WitnessReconstructionError(
                f"branch {b.branch_id} has no carried witness; "
                f"refusing to reconcile on reconstructed state"
            )
        if b.carried_witness.provenance != "carried":
            raise WitnessReconstructionError(
                f"branch {b.branch_id} witness provenance is "
                f"{b.carried_witness.provenance!r}; merge requires 'carried'"
            )
        if not b.deterministic:
            replayed = replay(b, tool_fns[b.branch_id], inputs[b.branch_id])
            if replayed.digest() != b.carried_witness.digest():
                raise WitnessReconstructionError(
                    f"non-deterministic branch {b.branch_id}: replayed witness "
                    f"{replayed.digest()[:12]} != carried witness "
                    f"{b.carried_witness.digest()[:12]}; quarantine branch"
                )
        carried.append(b.carried_witness)

    merged_effects = frozenset().union(*(w.effect_set for w in carried))
    if len({w.precondition_hash for w in carried}) > 1:
        raise WitnessReconstructionError(
            "carried witnesses disagree on precondition_hash; fork divergence"
        )
    return merged_effects
