# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-optimistic-branch-merge-when-a-speculative-tool-invocation-s-side-effects-are-not-idempotent-across-roll.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-optimistic-branch-merge-when-a-speculative-tool-invocation-s-side-effects-are-not-idempotent-across-roll.warrant.json
# Markdown SHA-256:   7db9b722133e772b8f99a0450568c92b7bd7815f40172224615b46f5e11a7852
# Code AST SHA-256:   745db7cdf8947fa73fb50f8b74b2a09204a9645aed803e54ac0619cc82e9f0b0
# Verified Classes:   SpeculativeMergeRefused, ToolClass, ToolProfile
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class SpeculativeMergeRefused(RuntimeError):
    """Raised when an instance attempts optimistic invocation of a tool whose
    side effects are observable to sibling branches and whose compensation
    does not restore the pre-branch invariant."""
    pass


class ToolClass(Enum):
    BRANCH_SCOPED = "branch_scoped"          # invisible to siblings
    OVERWRITE_SAFE = "overwrite_safe"        # visible but pure overwrite, versioned reads
    NON_MERGEABLE = "non_mergeable"          # visible + non-commutative compensation


@dataclass(frozen=True)
class ToolProfile:
    name: str
    observable_to_siblings: bool
    compensation_preserves_invariant: bool

    def classify(self) -> ToolClass:
        if not self.observable_to_siblings:
            return ToolClass.BRANCH_SCOPED
        if self.compensation_preserves_invariant:
            return ToolClass.OVERWRITE_SAFE
        return ToolClass.NON_MERGEABLE


REGISTRY: dict[str, ToolProfile] = {
    "increment_counter": ToolProfile("increment_counter", True, False),
    "send_email": ToolProfile("send_email", True, False),
    "write_blob_branch_scoped": ToolProfile("write_blob_branch_scoped", False, True),
    "set_config_overwrite": ToolProfile("set_config_overwrite", True, True),
}


def authorize_optimistic_invocation(branch_id: str, tool_name: str) -> ToolClass:
    profile = REGISTRY.get(tool_name)
    if profile is None:
        # Unclassified tools are presumed unsafe for optimism.
        raise SpeculativeMergeRefused(
            f"branch {branch_id}: tool {tool_name!r} has no registered profile; "
            f"refusing optimistic invocation (default-deny)."
        )
    cls = profile.classify()
    if cls is ToolClass.NON_MERGEABLE:
        raise SpeculativeMergeRefused(
            f"branch {branch_id}: tool {tool_name!r} is NON_MERGEABLE "
            f"(observable_to_siblings=True, compensation_preserves_invariant=False). "
            f"Serialize behind branch-exclusive lock or defer until branch selection."
        )
    return cls


def fork_and_invoke(branch_id: str, tool_name: str, args: dict) -> dict:
    cls = authorize_optimistic_invocation(branch_id, tool_name)
    if cls is ToolClass.OVERWRITE_SAFE:
        # Must use versioned read so siblings cannot observe uncommitted value.
        args = {**args, "_read_version": "fork_point"}
    return {"branch": branch_id, "tool": tool_name, "args": args, "mode": cls.value}
