# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-divergent-branch-commits-after-speculative-multi-agent-rollback-before-it-can-safely-resume-the-parent-ta.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-divergent-branch-commits-after-speculative-multi-agent-rollback-before-it-can-safely-resume-the-parent-ta.warrant.json
# Markdown SHA-256:   e5609046f77a7aedec1d0e4c854a9a141d0382c75df1fa9d9d4ee2e6daf157e3
# Code AST SHA-256:   c3a17ff01a015196a78788857b5a3752de0209e2f4d7a5f1327ee680a565b250
# Verified Classes:   ReconciliationError, EffectClass, SideEffect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class ReconciliationError(RuntimeError):
    """Raised when a discarded branch's side effects cannot be bounded before rejoin."""


class EffectClass(Enum):
    SUBSUMED = "subsumed"
    ORPHANED = "orphaned"
    CONFLICTING = "conflicting"


@dataclass
class SideEffect:
    branch_id: str
    effect_id: str
    target: str
    payload: str
    warrant_id: str | None = None


@dataclass
class Branch:
    branch_id: str
    effects: list[SideEffect] = field(default_factory=list)


def reconcile_before_rejoin(
    winner: Branch,
    discarded: list[Branch],
    winner_effect_keys: set[tuple[str, str]],
) -> dict[str, EffectClass]:
    """Classify every discarded-branch effect; block rejoin on any unbounded effect."""
    classification: dict[str, EffectClass] = {}

    for branch in discarded:
        for eff in branch.effects:
            key = (eff.target, eff.payload)
            if key in winner_effect_keys:
                classification[eff.effect_id] = EffectClass.SUBSUMED
            elif eff.warrant_id is not None:
                # A speculative warrant reached a peer; cannot be silently kept.
                raise ReconciliationError(
                    f"branch {branch.branch_id} effect {eff.effect_id} issued "
                    f"warrant {eff.warrant_id} to {eff.target}; must be revoked "
                    f"or adopted before parent rejoin"
                )
            else:
                classification[eff.effect_id] = EffectClass.ORPHANED

    unresolved = [
        eid
        for eid, cls in classification.items()
        if cls is EffectClass.ORPHANED
    ]
    if unresolved:
        raise ReconciliationError(
            f"{len(unresolved)} orphaned effects lack compensation: {unresolved}"
        )

    return classification
