# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-commit-before-it-speculates-irreversible-tool-effects-under-parallel-branch-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-commit-before-it-speculates-irreversible-tool-effects-under-parallel-branch-rollback.warrant.json
# Markdown SHA-256:   564f1f13bc6913af79c8877e4d600f0f5254144d40e97c8aa9b6d01c3a5eef6c
# Code AST SHA-256:   f54fb8f631670028e64de6be8119ebd282d345fde99c523b9009387ae4641092
# Verified Classes:   SpeculativeCommitmentError, ToolCapability
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SpeculativeCommitmentError(RuntimeError):
    """Raised when a speculative branch attempts an irreversible effect
    before winner selection, or when a proposal is replayed against a
    drifted context snapshot."""
    pass


class ToolCapability:
    def __init__(self, name: str, mutating: bool, compensator: str | None):
        self.name = name
        self.mutating = mutating
        self.compensator = compensator

    @property
    def speculative_safe(self) -> bool:
        # Safe to expose to a speculative branch only if it cannot mutate,
        # or if it mutates but has a registered compensator.
        return (not self.mutating) or (self.compensator is not None)


def build_speculative_manifest(tools: list[ToolCapability]) -> list[str]:
    manifest = []
    for t in tools:
        if t.speculative_safe:
            manifest.append(t.name)
        else:
            # Withhold the raw mutating tool; expose only the proposal shim.
            manifest.append(f"propose_commit:{t.name}")
    return manifest


def execute_speculative_call(
    branch_id: str,
    tool: ToolCapability,
    args: dict,
    selected_branch: str | None,
    context_hash_at_proposal: str,
    current_context_hash: str,
) -> dict:
    if tool.mutating and selected_branch is None:
        # Fan-out phase: a branch reached a live mutating tool.
        raise SpeculativeCommitmentError(
            f"branch {branch_id} invoked mutating tool {tool.name} "
            f"before winner selection; no compensator path is valid here"
        )

    if tool.mutating and not tool.speculative_safe:
        raise SpeculativeCommitmentError(
            f"tool {tool.name} is mutating without a registered compensator; "
            f"it must never appear in a speculative manifest"
        )

    if selected_branch is not None:
        if branch_id != selected_branch:
            raise SpeculativeCommitmentError(
                f"non-winner branch {branch_id} attempted commit of {tool.name}; "
                f"winner is {selected_branch}"
            )
        if context_hash_at_proposal != current_context_hash:
            raise SpeculativeCommitmentError(
                f"proposal for {tool.name} replayed against drifted context: "
                f"proposed at {context_hash_at_proposal}, now {current_context_hash}"
            )

    idempotency_key = f"{branch_id}:{tool.name}:{hash(frozenset(args.items()))}"
    return {"tool": tool.name, "args": args, "idempotency_key": idempotency_key,
            "committed": True}
