# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-become-non-rollbackable-before-merge-in-a-branch-and-merge-agent-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-become-non-rollbackable-before-merge-in-a-branch-and-merge-agent-graph.warrant.json
# Markdown SHA-256:   49957bdcc87ed91f4be0be33a0a5b051f8829601958633118a4146c5ff9b27c6
# Code AST SHA-256:   a43191f720b4b0aea7969141b725fbbdb858cc8b66b15f479dc35ea6a4c35d79
# Verified Classes:   NonRollbackableBranchError, Effect, EffectLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class NonRollbackableBranchError(RuntimeError):
    """Raised when a branch's durable-effect frontier cannot be fully compensated."""
    pass


@dataclass(frozen=True)
class Effect:
    branch_id: str
    tool: str
    args_hash: str
    idempotency_key: Optional[str]
    compensable: bool


@dataclass
class EffectLedger:
    # Written by the tool-execution proxy, never by the agent's reasoning loop.
    effects: list[Effect] = field(default_factory=list)

    def record(self, branch_id: str, tool: str, args: dict, attempt_seq: int) -> None:
        args_hash = hashlib.sha256(
            repr(sorted(args.items())).encode()
        ).hexdigest()
        # Proxy stamps the key so retries collapse; agent cannot forge it.
        key = hashlib.sha256(
            f"{branch_id}:{tool}:{args_hash}:{attempt_seq}".encode()
        ).hexdigest()
        # Dedup: identical key already present means a retry, not a new effect.
        if any(e.idempotency_key == key for e in self.effects):
            return
        self.effects.append(Effect(
            branch_id=branch_id, tool=tool, args_hash=args_hash,
            idempotency_key=key,
            compensable=tool in COMPENSABLE_TOOLS,
        ))

    def frontier(self, branch_id: str) -> list[Effect]:
        return [e for e in self.effects if e.branch_id == branch_id]


COMPENSABLE_TOOLS = {"git_worktree_write", "file_write_isolated", "cache_restore"}


def assert_discardable(ledger: EffectLedger, branch_id: str) -> None:
    frontier = ledger.frontier(branch_id)
    uncompensated = [e for e in frontier if not e.compensable]
    if uncompensated:
        raise NonRollbackableBranchError(
            f"branch {branch_id} has {len(uncompensated)} non-compensable "
            f"effect(s) on the frontier (e.g. {uncompensated[0].tool}); "
            f"branch is committed, not speculative. Route to reconciliation."
        )


def select_and_merge(ledger: EffectLedger, candidates: dict[str, float]) -> str:
    # Partition by frontier cleanliness BEFORE comparing confidence.
    clean = {b: c for b, c in candidates.items() if not ledger.frontier(b)}
    if not clean:
        raise NonRollbackableBranchError(
            "no rollbackable candidate; all branches have durable effects"
        )
    chosen = max(clean, key=clean.get)
    for b in candidates:
        if b != chosen:
            assert_discardable(ledger, b)  # raises if a "discarded" branch is committed
    return chosen
