# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-suspends-a-tool-call-for-mcp-elicitation-and-the-sampling-loop-resumes-against-a-mutated-conversation-prefix.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-suspends-a-tool-call-for-mcp-elicitation-and-the-sampling-loop-resumes-against-a-mutated-conversation-prefix.warrant.json
# Markdown SHA-256:   815d167ca728dac7071405e948ad52d9b2ada0fc2f0b628339bf8fc1e1081261
# Code AST SHA-256:   7c43d30f400b34b74fe97335d6470e05c0df57d81cf9e8236be0bf8520fa12e6
# Verified Classes:   PrefixMutationError, SuspendedCall
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class PrefixMutationError(RuntimeError):
    """Raised when a suspended tool call is resumed against a mutated prefix."""


@dataclass
class SuspendedCall:
    tool_call_id: str
    tool_name: str
    arguments: dict[str, Any]
    prefix_fingerprint: str


def fingerprint(messages: list[dict], tool_schemas: list[dict], system: str, model_id: str) -> str:
    payload = json.dumps(
        {"messages": messages, "tools": tool_schemas, "system": system, "model": model_id},
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def resolve_elicitation(
    suspended: SuspendedCall,
    elicitation_response: dict[str, Any],
    current_messages: list[dict],
    current_tool_schemas: list[dict],
    current_system: str,
    current_model_id: str,
) -> dict[str, Any]:
    current_fp = fingerprint(current_messages, current_tool_schemas, current_system, current_model_id)

    merged_args = {**suspended.arguments, **elicitation_response}

    if current_fp == suspended.prefix_fingerprint:
        # Prefix stable: splice into the pending slot and continue.
        return {
            "mode": "splice",
            "tool_call_id": suspended.tool_call_id,
            "arguments": merged_args,
        }

    # Prefix mutated: splicing would misalign the tool-result slot.
    # Re-issue as a fresh call with a new ID; retire the old one.
    if suspended.tool_call_id in json.dumps(current_messages):
        # A dangling reference to the retired call still exists in context.
        # Continuing would let the model treat the new result as answering the old call.
        raise PrefixMutationError(
            f"Tool call {suspended.tool_call_id} ({suspended.tool_name}) suspended against "
            f"prefix {suspended.prefix_fingerprint[:12]}, resumed against {current_fp[:12]}; "
            f"intervening events mutated the transcript. Re-issuing with merged arguments "
            f"{merged_args!r} under a new tool_call_id; caller must strip the stale reference "
            f"before generation continues."
        )

    return {
        "mode": "reissue",
        "tool_call_id": f"{suspended.tool_call_id}_reissued",
        "arguments": merged_args,
    }
