# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-branch-s-committed-tool-effects-as-non-rollbackable-and-how-does-silent-divergence-between.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-branch-s-committed-tool-effects-as-non-rollbackable-and-how-does-silent-divergence-between.warrant.json
# Markdown SHA-256:   f093025f9685ad028937e16351caf4a4f81b5300a6d0382dbd0d0deeee0d649a
# Code AST SHA-256:   9164279521038b7eef4c42f6ab9bae84513b78d417d698567d02d468cbc1a6b5
# Verified Classes:   SpeculativeDivergenceError, EffectDisposition, EffectRecord, EffectLedger, Reconciler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SpeculativeDivergenceError(RuntimeError):
    """Raised when a branch is discarded with unresolved committed effects."""


class EffectDisposition(Enum):
    COMPENSATED = "compensated"
    ORPHANED = "orphaned"
    UNRESOLVED = "unresolved"


@dataclass
class EffectRecord:
    branch_id: str
    tool: str
    target: str
    pre_image_hash: str
    post_image_hash: str
    reversible: bool
    inverse_spec: Optional[str] = None
    disposition: EffectDisposition = EffectDisposition.UNRESOLVED


@dataclass
class EffectLedger:
    records: list = field(default_factory=list)

    def record(self, rec: EffectRecord) -> None:
        self.records.append(rec)

    def for_branch(self, branch_id: str) -> list:
        return [r for r in self.records if r.branch_id == branch_id]

    def unresolved_for_branch(self, branch_id: str) -> list:
        return [
            r for r in self.for_branch(branch_id)
            if r.disposition is EffectDisposition.UNRESOLVED
        ]


@dataclass
class Reconciler:
    ledger: EffectLedger
    winning_branch: str

    def reconcile(self, losing_branches: list, current_hashes: dict) -> dict:
        warrants = {}
        for branch in losing_branches:
            unresolved = self.ledger.unresolved_for_branch(branch)
            for rec in unresolved:
                if rec.reversible and rec.inverse_spec is not None:
                    if current_hashes.get(rec.target) != rec.post_image_hash:
                        # Pre-image drifted: cannot safely apply inverse.
                        rec.disposition = EffectDisposition.ORPHANED
                    else:
                        rec.disposition = EffectDisposition.COMPENSATED
                else:
                    rec.disposition = EffectDisposition.ORPHANED

            orphans = [
                r for r in self.ledger.for_branch(branch)
                if r.disposition is EffectDisposition.ORPHANED
            ]
            if orphans:
                warrants[branch] = orphans

        return warrants

    def assert_discard_safe(self, branch: str) -> None:
        leftover = [
            r for r in self.ledger.for_branch(branch)
            if r.disposition is EffectDisposition.UNRESOLVED
        ]
        if leftover:
            targets = ", ".join(sorted({r.target for r in leftover}))
            raise SpeculativeDivergenceError(
                f"Branch {branch!r} cannot be discarded: "
                f"{len(leftover)} committed effect(s) unresolved on [{targets}]. "
                f"Compensate or carry forward as orphaned-effect warrant."
            )


def verify_winner(reconciler: Reconciler, winner: str, observed: dict) -> str:
    warrants = reconciler.reconcile(
        losing_branches=[b for b in {r.branch_id for r in reconciler.ledger.records}
                         if b != winner],
        current_hashes=observed,
    )
    if warrants:
        raise SpeculativeDivergenceError(
            f"Winner {winner!r} verification blocked: orphaned effects from "
            f"{sorted(warrants)} persist in the world-state it read. "
            f"Emitting divergence warrant; do not report VALID."
        )
    for branch in {r.branch_id for r in reconciler.ledger.records}:
        reconciler.assert_discard_safe(branch)
    return "VALID"
