# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-parallel-agent-branches-and-a-rollback-re-exposes-a-side-effect-the-commit-path-already-externali.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-parallel-agent-branches-and-a-rollback-re-exposes-a-side-effect-the-commit-path-already-externali.warrant.json
# Markdown SHA-256:   63483a8f4cee8a1ada365239dce2b8747ee4bfbf8c49e323ca9f9d1da08b55b5
# Code AST SHA-256:   1ead6fd2810e56a90dcb20bd72f0ebded644dd4b33a7e8be9fe80a3165eb27c8
# Verified Classes:   SpeculationLeakError, ToolClass, ToolSpec, Episode
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SpeculationLeakError(RuntimeError):
    """Raised when a speculative branch applies a non-interceptable external effect."""


class ToolClass(Enum):
    STAGED = "staged"                  # journaled, no external effect until commit
    IDEMPOTENT_EXTERNAL = "idem_ext"   # escapes, but backend dedupes on intent key
    NON_IDEMPOTENT_EXTERNAL = "non_idem_ext"  # escapes, no dedupe, observable


@dataclass(frozen=True)
class ToolSpec:
    name: str
    tool_class: ToolClass
    intent_scoped: bool = False  # True => backend dedupes on (episode, intent_hash)


@dataclass
class Episode:
    episode_id: str
    journal: list = field(default_factory=list)
    committed: bool = False
    rolled_back: bool = False


def intent_key(episode_id: str, tool_name: str, semantic_args: dict) -> str:
    # Dedupe key MUST be derived from semantic intent, not branch identity,
    # so that two branches proposing the same refund collapse to one effect.
    payload = f"{episode_id}:{tool_name}:{sorted(semantic_args.items())}"
    return hashlib.sha256(payload.encode()).hexdigest()


def speculative_call(
    episode: Episode,
    branch_id: str,
    tool: ToolSpec,
    args: dict,
    backend,
) -> Optional[str]:
    """Invoke a tool from a speculative branch. Enforces the interception invariant."""
    if episode.committed or episode.rolled_back:
        raise SpeculationLeakError(
            f"episode {episode.episode_id} already reconciled; branch {branch_id} "
            f"attempted post-decision call to {tool.name}"
        )

    if tool.tool_class is ToolClass.STAGED:
        episode.journal.append(("staged", branch_id, tool.name, args))
        return None

    if tool.tool_class is ToolClass.IDEMPOTENT_EXTERNAL:
        if not tool.intent_scoped:
            # Escaping effect with no dedupe key: cannot be safely speculative.
            raise SpeculationLeakError(
                f"tool {tool.name} is external but not intent-scoped; "
                f"branch {branch_id} would leak a non-collapsible effect"
            )
        key = intent_key(episode.episode_id, tool.name, args)
        episode.journal.append(("idem_ext", branch_id, tool.name, key))
        return backend.apply_idempotent(key, tool.name, args)

    if tool.tool_class is ToolClass.NON_IDEMPOTENT_EXTERNAL:
        # The boundary: refuse to apply. Emit a proposal instead.
        raise SpeculationLeakError(
            f"tool {tool.name} is non-idempotent-external; branch {branch_id} "
            f"must emit a proposal, not call it speculatively"
        )

    raise SpeculationLeakError(f"unclassified tool {tool.name}")


def reconcile(episode: Episode, winner: str, backend) -> dict:
    """Commit the winner's proposals exactly once; discard all other branches."""
    if episode.committed or episode.rolled_back:
        raise SpeculationLeakError(f"episode {episode.episode_id} already reconciled")

    applied = {}
    for kind, branch_id, name, payload in episode.journal:
        if branch_id != winner:
            continue  # losers: staged entries discarded, idem_ext already deduped
        if kind == "staged":
            applied[name] = backend.apply(name, payload)
        elif kind == "idem_ext":
            applied[name] = backend.apply_idempotent(payload, name, {})

    episode.committed = True
    return applied


def replay(episode: Episode, backend) -> dict:
    """Replay must be invariant under rollback count. Rollback emits no effects."""
    if not episode.committed:
        raise SpeculationLeakError(
            f"cannot replay unreconciled episode {episode.episode_id}; "
            f"effects are not a function of the commit decision"
        )
    return {name: backend.lookup(name) for name in backend.keys()}
