# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-roll-back-a-speculative-branch-verifier-gated-commit-and-the-divergence-detection-invariant-in-parallel-agent-drafting.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-roll-back-a-speculative-branch-verifier-gated-commit-and-the-divergence-detection-invariant-in-parallel-agent-drafting.warrant.json
# Markdown SHA-256:   1e44466ce7e77df0d1fd24fed1d5d7aeb3d314edb50db91b9c82e45d1d61df30
# Code AST SHA-256:   cc22f55522e58f9dbf7e1e42657979bcab3b324d57c708be890a4d5c5b8cb7f8
# Verified Classes:   SpeculativeCommitDivergence, ToolRegistry, Orchestrator
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeCommitDivergence(RuntimeError):
    """Raised when a branch with live side effects is not in the committed set."""
    pass


class ToolRegistry:
    def __init__(self):
        # Declared at registration, checked BEFORE any call.
        self.spec = {
            "read_ledger":      {"irreversible": False, "buffered": True},
            "issue_restock":    {"irreversible": True,  "buffered": False},
            "send_email":       {"irreversible": True,  "buffered": False},
            "write_scratch":    {"irreversible": False, "buffered": True},
        }

    def classify(self, tool: str) -> str:
        s = self.spec[tool]
        if s["buffered"]:
            return "speculative"
        if s["irreversible"]:
            return "authoritative_on_call"
        return "provisional"


class Orchestrator:
    def __init__(self, registry: ToolRegistry, branches):
        self.registry = registry
        self.branches = branches
        self.effects_live = set()     # branch IDs that emitted a live effect
        self.committed = set()

    def pre_call_gate(self, branch_id: str, tool: str):
        cls = self.registry.classify(tool)
        if cls == "authoritative_on_call":
            # Freeze siblings BEFORE this call lands.
            for b in self.branches:
                if b != branch_id:
                    self.freeze(b)
            self.effects_live.add(branch_id)
        elif cls == "provisional":
            self.effects_live.add(branch_id)

    def freeze(self, branch_id: str):
        # Cancel before its next tool call; do not touch already-emitted effects.
        pass

    def commit(self, winner: str):
        self.committed.add(winner)
        # Invariant: every live-effect branch must be committed.
        rogue = self.effects_live - self.committed
        if rogue:
            raise SpeculativeCommitDivergence(
                f"branches with live side effects not committed: {sorted(rogue)}; "
                f"rollback of transcripts cannot revert their effects"
            )
        return True
