# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-safe-speculative-tool-call-pre-execution-window-in-concurrent-multi-agent-plans.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-safe-speculative-tool-call-pre-execution-window-in-concurrent-multi-agent-plans.warrant.json
# Markdown SHA-256:   d0ef25fb662835a54dfc055aac301c8747bdb001f2fafbd76e2fb8ea902f5a44
# Code AST SHA-256:   4608d7fc97c21b191a8c76d035db7099bd16441bef354f0fb71e2f310a60d7b0
# Verified Classes:   UnsafeSpeculationError, ResolutionTrace, WarrantLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class UnsafeSpeculationError(RuntimeError):
    """Raised when a speculative pre-execution step escapes its declared effect
    or is not warrant-quiescent at the instant of write."""


@dataclass
class ResolutionTrace:
    declared_targets: frozenset
    resolved_targets: frozenset
    tool_undo_is_mutation: bool = False

    def fan_out(self) -> float:
        if not self.declared_targets:
            return float("inf")
        return len(self.resolved_targets) / len(self.declared_targets)

    def contained(self) -> bool:
        return self.resolved_targets.issubset(self.declared_targets)


@dataclass
class WarrantLedger:
    # target -> set of agent ids holding an uncommitted write warrant
    open_warrants: dict = field(default_factory=dict)

    def quiescent(self, targets: frozenset) -> bool:
        return all(not self.open_warrants.get(t) for t in targets)


def gate_speculation(
    step_id: str,
    trace: ResolutionTrace,
    ledger: WarrantLedger,
    now: Optional[float] = None,
) -> str:
    """Decide pre-execute / defer / abort for a single plan step.

    Returns one of: 'pre-execute', 'defer', 'abort'.
    Raises UnsafeSpeculationError if the step is forced to pre-execute
    outside the valid window (caller bug or override attempt).
    """
    now = now if now is not None else time.time()

    if trace.tool_undo_is_mutation:
        return "abort"

    if not trace.contained() or trace.fan_out() > 1.0:
        # Resolved effect escapes declared effect: detector verdict is void.
        # Must not speculate; defer to serialized commit.
        return "defer"

    if not ledger.quiescent(trace.resolved_targets):
        # Containment holds but a sibling holds an uncommitted warrant.
        # Retrying as transient is the known failure; abort speculation.
        return "abort"

    return "pre-execute"


def pre_execute(step_id: str, trace: ResolutionTrace, ledger: WarrantLedger,
                force: bool = False) -> str:
    decision = gate_speculation(step_id, trace, ledger)
    if decision != "pre-execute":
        if force:
            raise UnsafeSpeculationError(
                f"step {step_id!r} forced to pre-execute but gate returned "
                f"{decision!r}; fan_out={trace.fan_out():.2f}, "
                f"contained={trace.contained()}, "
                f"quiescent={ledger.quiescent(trace.resolved_targets)}"
            )
        return decision
    # ... issue nonce-bearing speculative write here ...
    return "pre-execute"
