# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-pre-execution-from-committing-side-effects-that-the-agent-s-eventual-decision-path-never-ratifies.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-pre-execution-from-committing-side-effects-that-the-agent-s-eventual-decision-path-never-ratifies.warrant.json
# Markdown SHA-256:   3357dbbbd26ac0a82126d60814d3ca70fccd2f9fef24033355c1dd3a7ba98ab8
# Code AST SHA-256:   a8a313e44ba102068fb41fac3a6c0763755a9599f3d685bf5f0f04b8c283658d
# Verified Classes:   UnratifiedEffectError, MissingCompensationError, RatificationToken, StagedEffect, SpeculativeGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

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


class UnratifiedEffectError(RuntimeError):
    """Raised when an effectful tool attempts to settle without a valid ratification token."""
    pass


class MissingCompensationError(RuntimeError):
    """Raised when an effectful tool is staged without a registered, precondition-checked inverse."""
    pass


@dataclass
class RatificationToken:
    decision_node_id: str
    tool_name: str
    args_hash: str
    target_resource: str

    def binds(self, tool_name: str, args: dict, target_resource: str) -> bool:
        return (
            self.tool_name == tool_name
            and self.args_hash == _hash_args(args)
            and self.target_resource == target_resource
        )


def _hash_args(args: dict) -> str:
    canonical = repr(sorted(args.items()))
    return hashlib.sha256(canonical.encode()).hexdigest()


@dataclass
class StagedEffect:
    tool_name: str
    args: dict
    target_resource: str
    settle: Callable[[], str]
    inverse: Callable[[], None]
    staged_at: float = field(default_factory=time.monotonic)
    window_s: float = 0.9


class SpeculativeGate:
    """Gate-before-commit runtime for speculative tool dispatch.

    Invariant: an effectful call may be *staged* speculatively, but may only
    *settle* when presented a token bound to a committed decision node that
    names this exact call. Staged effects are unwound by their registered
    inverse on window expiry.
    """

    def __init__(self) -> None:
        self._staged: dict[str, StagedEffect] = {}

    def stage(
        self,
        call_id: str,
        tool_name: str,
        args: dict,
        target_resource: str,
        settle: Callable[[], str],
        inverse: Optional[Callable[[], None]],
        inverse_preconditions_ok: bool,
    ) -> None:
        if inverse is None or not inverse_preconditions_ok:
            raise MissingCompensationError(
                f"cannot stage effectful call {call_id!r} ({tool_name}): "
                "no registered inverse with satisfied preconditions; "
                "serialize this tool instead of speculating."
            )
        self._staged[call_id] = StagedEffect(
            tool_name=tool_name,
            args=args,
            target_resource=target_resource,
            settle=settle,
            inverse=inverse,
        )

    def ratify_and_settle(self, call_id: str, token: RatificationToken) -> str:
        staged = self._staged.get(call_id)
        if staged is None:
            raise UnratifiedEffectError(f"no staged effect for call {call_id!r}")
        if not token.binds(staged.tool_name, staged.args, staged.target_resource):
            raise UnratifiedEffectError(
                f"ratification token {token.decision_node_id!r} does not bind "
                f"to staged call {call_id!r} ({staged.tool_name} on {staged.target_resource}); "
                "token names a different call."
            )
        del self._staged[call_id]
        return staged.settle()

    def expire_and_compensate(self) -> list[str]:
        """Called when the decision path diverges: unwind all unratified speculations."""
        now = time.monotonic()
        unwound: list[str] = []
        for call_id, staged in list(self._staged.items()):
            if now - staged.staged_at >= staged.window_s:
                staged.inverse()
                del self._staged[call_id]
                unwound.append(call_id)
        return unwound


def run_divergent_branch(gate: SpeculativeGate, call_id: str, committed_branch: str) -> None:
    """Simulates the t1..t4 divergence: disconfirming lookup wins, branch flips to escalate."""
    if committed_branch == "escalate":
        # No ratification token is ever minted for the speculative refund.
        unwound = gate.expire_and_compensate()
        if call_id not in unwound:
            # The speculative effect settled before disconfirmation arrived.
            raise UnratifiedEffectError(
                f"orphaned side effect: {call_id!r} settled without a ratification "
                "token bound to a committed decision node; the agent's trace has no "
                "record of it. Gate-before-commit invariant was violated."
            )
