# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-divergence-when-idempotency-tokens-collide-across-merged-agent-branches.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-divergence-when-idempotency-tokens-collide-across-merged-agent-branches.warrant.json
# Markdown SHA-256:   1bdf2e2c9e61d72186b386c44544d0ddf71582b9e48208f28cc3032a8c3ca9e2
# Code AST SHA-256:   6b607da0b635846d416946b417cfc1a1f779cc58fcf4cebcba0df09254c12dc1
# Verified Classes:   SpeculativeDivergence, PlanNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SpeculativeDivergence(RuntimeError):
    """Raised when a branch's runtime tool arguments diverge from the
    plan node's declared arguments under a fixed idempotency token."""


@dataclass(frozen=True)
class PlanNode:
    node_id: str
    tool: str
    declared_args: dict
    idempotency_token: str  # minted at fork point, inherited by branches


def mint_token(node_id: str, tool: str, declared_args: dict) -> str:
    # Token is a function of the PLAN NODE, not of branch execution.
    payload = json.dumps(
        {"node_id": node_id, "tool": tool, "args": declared_args},
        sort_keys=True,
        separators=(",", ":"),
    )
    return "tok_" + hashlib.sha256(payload.encode()).hexdigest()[:16]


def canonical(args: dict) -> str:
    return json.dumps(args, sort_keys=True, separators=(",", ":"))


def execute_speculative_branch(node: PlanNode, runtime_args: dict) -> dict:
    # Guard: a branch may execute a node zero or one times, never with
    # arguments other than the node's declared arguments.
    if canonical(runtime_args) != canonical(node.declared_args):
        raise SpeculativeDivergence(
            f"branch args {canonical(runtime_args)} diverge from declared "
            f"{canonical(node.declared_args)} for node {node.node_id} "
            f"(token {node.idempotency_token}); refusing to mint a new token"
        )

    # Safe: arguments match the token's commitment. The gateway may collapse
    # this call with any sibling carrying the same token.
    return {
        "node_id": node.node_id,
        "token": node.idempotency_token,
        "args": runtime_args,
        "status": "applied",
    }


def merge_branches(results: list[dict]) -> dict:
    # Group by node_id, not by token. Same node + different args is a
    # divergence, not a duplicate; same node + same args is a safe collapse.
    by_node: dict[str, list[dict]] = {}
    for r in results:
        by_node.setdefault(r["node_id"], []).append(r)

    merged = {}
    for node_id, group in by_node.items():
        applied = [r for r in group if r["status"] == "applied"]
        divergent = [r for r in group if r["status"] == "divergence"]
        if divergent:
            merged[node_id] = {"state": "diverged", "applied": applied,
                               "divergent": divergent}
        elif len({canonical(r["args"]) for r in applied}) > 1:
            # Should be unreachable if the guard held; catch it anyway.
            raise SpeculativeDivergence(
                f"merge saw multiple argument sets for node {node_id} "
                f"without a divergence marker"
            )
        else:
            merged[node_id] = {"state": "committed", "result": applied[0]}
    return merged
