# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-agent-trace-as-evidence-rather-than-as-a-fresh-execution-the-tool-side-effect-divergence-bound.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-agent-trace-as-evidence-rather-than-as-a-fresh-execution-the-tool-side-effect-divergence-bound.warrant.json
# Markdown SHA-256:   655391ec68321d83977f428f8172836ba73fb5ed5abb4cbc4b08306bf7a2f6da
# Code AST SHA-256:   bebb8850149dde088ac10298915bb4d5a0de9f0171dde4b161e02545d937b5a8
# Verified Classes:   EffectClass, ReplayBoundaryError, ToolCall
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class EffectClass(Enum):
    NONE = "none"            # pure read; safe to re-execute
    IDEMPOTENT = "idempotent"  # re-execution yields same world-state (needs key reuse)
    MUTATING = "mutating"    # non-idempotent; must be reverted or stubbed w/ precondition
    COMPENSATING = "compensating"  # has a declared inverse; revertible


class ReplayBoundaryError(RuntimeError):
    """Raised when a replayed trace crosses the tool-side-effect divergence boundary
    and can no longer be admitted as counterfactual evidence."""


@dataclass
class ToolCall:
    index: int
    name: str
    effect: Optional[EffectClass]          # None == undeclared
    idempotency_key: Optional[str]         # must be present for IDEMPOTENT reuse
    pre_state_fingerprint: Optional[str]   # hash of agent-observable state before call
    post_state_fingerprint: Optional[str]  # hash of agent-observable state after call
    stub_asserts_precondition: bool = False
    reverted: bool = False


def locate_boundary(trace: list[ToolCall]) -> int:
    """Return the index of the first call that breaks the Effect-Equivalence Invariant.
    Calls before the returned index are admissible evidence; the call at the index and
    everything after it are fresh execution, not counterfactual."""
    for call in trace:
        if call.effect is None:
            raise ReplayBoundaryError(
                f"call {call.index} ({call.name}) has no declared effect class; "
                f"refusing to replay — assuming idempotent is how the boundary moves"
            )
        if call.effect is EffectClass.NONE:
            continue
        if call.effect is EffectClass.IDEMPOTENT:
            if call.idempotency_key is None:
                raise ReplayBoundaryError(
                    f"call {call.index} ({call.name}) is IDEMPOTENT but no idempotency "
                    f"key was recorded; re-execution would apply a second effect"
                )
            continue
        if call.effect is EffectClass.COMPENSATING and call.reverted:
            continue
        if call.effect is EffectClass.MUTATING and call.stub_asserts_precondition:
            if call.pre_state_fingerprint is None or call.post_state_fingerprint is None:
                raise ReplayBoundaryError(
                    f"call {call.index} ({call.name}) is stubbed but lacks pre/post "
                    f"state fingerprints; cannot assert precondition equivalence"
                )
            continue
        # First non-idempotent, non-reverted, non-asserted call: the boundary.
        return call.index
    return len(trace)  # entire trace admissible


def attribute_divergence(trace: list[ToolCall], divergence_index: int) -> str:
    boundary = locate_boundary(trace)
    if divergence_index < boundary:
        return f"attributable to intervention (divergence {divergence_index} < boundary {boundary})"
    raise ReplayBoundaryError(
        f"divergence at {divergence_index} is at or past boundary {boundary} "
        f"({trace[boundary].name}); demote to fresh execution, claim not supported"
    )
