# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-its-own-context-pruning-rewrite-has-silently-invalidated-an-in-flight-tool-call-argument-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-its-own-context-pruning-rewrite-has-silently-invalidated-an-in-flight-tool-call-argument-binding.warrant.json
# Markdown SHA-256:   cab1b1559388e8b0204cb0c03b4a04d68d2b9af5019bd13195a57ddfb7b786ce
# Code AST SHA-256:   d3121b359d12eb765959c6bf57239f92b55d4d1b8ff86b88b1b7e1c9ebb22851
# Verified Classes:   ReferentInvalidatedError, Region, PendingCall, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ReferentInvalidatedError(RuntimeError):
    """Raised when a self-edit would mutate a transcript region bound by a pending tool call."""
    pass


@dataclass
class Region:
    region_id: str
    content: str

    def digest(self) -> str:
        return hashlib.sha256(self.content.encode("utf-8")).hexdigest()


@dataclass
class PendingCall:
    call_id: str
    tool: str
    bound_region_id: str
    bound_digest: str  # digest of region content at emission time


@dataclass
class ContextWindow:
    regions: dict[str, Region] = field(default_factory=dict)
    pending: dict[str, PendingCall] = field(default_factory=dict)

    def emit_call(self, call_id: str, tool: str, region_id: str) -> PendingCall:
        region = self.regions[region_id]
        call = PendingCall(call_id, tool, region_id, region.digest())
        self.pending[call_id] = call
        return call

    def apply_self_edit(self, mutated_region_ids: set[str], new_contents: dict[str, str]) -> None:
        # Invariant: a self-edit may not mutate any region pinned by a pending call.
        pinned = {c.bound_region_id for c in self.pending.values()}
        collision = mutated_region_ids & pinned
        if collision:
            raise ReferentInvalidatedError(
                f"self-edit would mutate pinned region(s) {sorted(collision)} "
                f"bound by pending calls "
                f"{[c.call_id for c in self.pending.values() if c.bound_region_id in collision]}; "
                f"defer the edit or fail the call closed"
            )
        for rid, content in new_contents.items():
            self.regions[rid] = Region(rid, content)

    def resolve_call(self, call_id: str) -> None:
        call = self.pending[call_id]
        region = self.regions.get(call.bound_region_id)
        if region is None or region.digest() != call.bound_digest:
            # Defense in depth: even if a rewrite slipped past apply_self_edit,
            # resolution must fail closed rather than proceed against a changed referent.
            raise ReferentInvalidatedError(
                f"tool call {call_id} ({call.tool}) resolved against a mutated referent "
                f"{call.bound_region_id}; re-emit with self-contained arguments"
            )
        del self.pending[call_id]


def safe_compact(window: ContextWindow, region_id: str, summary: str) -> None:
    window.apply_self_edit(mutated_region_ids={region_id}, new_contents={region_id: summary})
    # If we reach here, no pending call referenced region_id.
    if region_id in {c.bound_region_id for c in window.pending.values()}:
        raise ReferentInvalidatedError("post-condition violated: pinned region survived edit")
