# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-in-place-context-rewrites-that-invalidate-the-provenance-anchors-of-already-emitted-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-in-place-context-rewrites-that-invalidate-the-provenance-anchors-of-already-emitted-tool-calls.warrant.json
# Markdown SHA-256:   5e972740d0b959ebfbfff7a329259ad19d9c7ebd1df3638a447c4831b32dc623
# Code AST SHA-256:   ae7e5c0d58f95b679a6552dd832ba46b967532ec3c0ec0e4e7bdac3293bb0284
# Verified Classes:   AnchorClosureViolation, Message, ContextWindow
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class AnchorClosureViolation(RuntimeError):
    """Raised when an in-place context rewrite severs a tool_call/tool_result binding."""


@dataclass
class Message:
    role: str                      # "assistant" | "tool" | "user" | "system"
    tool_call_id: str | None = None
    content: str = ""
    pinned: bool = False


@dataclass
class ContextWindow:
    messages: list[Message] = field(default_factory=list)
    pending_calls: set[str] = field(default_factory=set)

    def call_ids(self) -> set[str]:
        return {m.tool_call_id for m in self.messages
                if m.role == "assistant" and m.tool_call_id}

    def result_ids(self) -> set[str]:
        return {m.tool_call_id for m in self.messages
                if m.role == "tool" and m.tool_call_id}


def assert_anchor_closure(before: ContextWindow, after: ContextWindow) -> None:
    """Anchor-closure invariant: retained call IDs == retained result IDs,
    and no ID cited by a retained continuation may disappear."""
    a, r = after.call_ids(), after.result_ids()
    if a != r:
        raise AnchorClosureViolation(
            f"call/result asymmetry after rewrite: calls_only={a - r}, results_only={r - a}"
        )
    # Any ID that was pending before the rewrite must still be resolvable.
    lost_pending = before.pending_calls - (a & r)
    if lost_pending:
        raise AnchorClosureViolation(
            f"rewrite dropped anchors for outstanding tool calls: {lost_pending}"
        )


def safe_rewrite(window: ContextWindow,
                 drop_ids: Iterable[str],
                 merge_map: dict[str, str] | None = None) -> ContextWindow:
    """Apply a structural rewrite only at quiescent points, then verify closure."""
    if window.pending_calls:
        raise AnchorClosureViolation(
            f"structural rewrite attempted mid-tool-cycle; pending={window.pending_calls}. "
            "Defer and apply content-only truncation instead."
        )
    merge_map = merge_map or {}
    drop = set(drop_ids)

    # Merging two results is only legal if neither is the sole anchor of a
    # distinct retained call. Refuse merges that would orphan a call.
    for keep_id, drop_id in merge_map.items():
        if drop_id in window.pending_calls:
            raise AnchorClosureViolation(
                f"merge would orphan pending call {drop_id}"
            )
        # If both IDs are cited by separate assistant calls, merging is illegal.
        if keep_id in window.call_ids() and drop_id in window.call_ids():
            raise AnchorClosureViolation(
                f"merge of {keep_id}<-{drop_id} would collapse two distinct call anchors"
            )

    new_messages = []
    for m in window.messages:
        if m.tool_call_id in merge_map:
            new_messages.append(Message(m.role, merge_map[m.tool_call_id], m.content, m.pinned))
            continue
        if m.tool_call_id in drop and not m.pinned:
            continue
        new_messages.append(m)

    rewritten = ContextWindow(new_messages, set(window.pending_calls))
    assert_anchor_closure(window, rewritten)
    return rewritten
