# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-pre-execution-when-optimistic-concurrency-collides-with-non-idempotent-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-pre-execution-when-optimistic-concurrency-collides-with-non-idempotent-side-effects.warrant.json
# Markdown SHA-256:   e2c19d97c360b80b28e4fd61d04a2e2de66beac99804a0880b12e8dbda3548ae
# Code AST SHA-256:   a8db7f5b5552b004343a52ab39f2e030e33df897ba4c7207196133e18b70cd89
# Verified Classes:   UnsafeSpeculationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnsafeSpeculationError(RuntimeError):
    """Raised when a speculative write cannot be bounded by a compensable envelope."""
    pass


# Per-tool annotations derived from reversibility-closure and fan-out checks.
# A tool is speculatable only if its effect is invisible until commit OR it has
# a true inverse covering every synchronous downstream trigger.
TOOL_SPECULATION_POLICY = {
    "read_tier":        {"speculatable": True,  "reason": "read-only"},
    "reserve_inventory": {"speculatable": False, "reason": "synchronous warehouse hold webhook has no inverse in capability set"},
    "charge_card":      {"speculatable": False, "reason": "settlement cycle outside agent boundary; no compensator"},
    "send_email":       {"speculatable": False, "reason": "externally observable on return; no inverse"},
}


def dispatch_speculative(tool_name: str, args: dict, speculation_id: str) -> dict:
    policy = TOOL_SPECULATION_POLICY.get(tool_name)
    if policy is None:
        raise UnsafeSpeculationError(
            f"tool {tool_name!r} has no speculation policy; defaulting to non-speculatable"
        )
    if not policy["speculatable"]:
        # Hard gate: refuse before dispatch, not after conflict resolution.
        raise UnsafeSpeculationError(
            f"refusing to speculate {tool_name!r} (speculation_id={speculation_id}): "
            f"{policy['reason']}. Defer behind commit barrier."
        )
    return _execute(tool_name, args)


def _execute(tool_name: str, args: dict) -> dict:
    # Placeholder for the actual tool transport.
    return {"tool": tool_name, "args": args, "status": "ok"}


def plan_step(tool_name: str, args: dict, speculation_id: str, defer: bool) -> dict:
    if defer:
        return _execute(tool_name, args)
    return dispatch_speculative(tool_name, args, speculation_id)
