# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-context-rewriting-policy-has-silently-invalidated-a-mid-execution-tool-call-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-context-rewriting-policy-has-silently-invalidated-a-mid-execution-tool-call-contract.warrant.json
# Markdown SHA-256:   2a7508c717ef05189d1573fd771afbb5d07e369d2deec5660c9771df62b8ef22
# Code AST SHA-256:   09237dec97507f652c7b3f428bf79952537ce22202df73be820b8fd9b88a2348
# Verified Classes:   OpenFrameOrphaned, ToolFrame, FrameLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class OpenFrameOrphaned(RuntimeError):
    """Raised when a context rewrite drops or mutates an open tool-call frame."""
    pass


@dataclass
class ToolFrame:
    call_id: str
    arg_binding_hash: str
    closed: bool = False


@dataclass
class FrameLedger:
    frames: Dict[str, ToolFrame] = field(default_factory=dict)

    def open_frame(self, call_id: str, arg_binding_hash: str) -> None:
        self.frames[call_id] = ToolFrame(call_id, arg_binding_hash)

    def close_frame(self, call_id: str) -> None:
        if call_id not in self.frames:
            raise OpenFrameOrphaned(f"close of unknown frame {call_id}")
        self.frames[call_id].closed = True

    def open_ids(self) -> Set[str]:
        return {cid for cid, f in self.frames.items() if not f.closed}


def verify_rewrite_preconditions(
    ledger: FrameLedger,
    pre_rewrite_open: Set[str],
    post_rewrite_open: Set[str],
    post_rewrite_bindings: Dict[str, str],
) -> None:
    """
    Enforce the frame-pinning invariant: a rewrite may not orphan or rebind
    any frame that was open before the rewrite.
    """
    orphaned = pre_rewrite_open - post_rewrite_open
    if orphaned:
        raise OpenFrameOrphaned(
            f"rewrite orphaned open frames: {sorted(orphaned)}; "
            f"these results will return to no live frame and be misfolded"
        )

    for call_id in pre_rewrite_open & post_rewrite_open:
        expected = ledger.frames[call_id].arg_binding_hash
        actual = post_rewrite_bindings.get(call_id)
        if actual != expected:
            raise OpenFrameOrphaned(
                f"rewrite rebound frame {call_id}: "
                f"expected {expected!r}, got {actual!r}; "
                f"result merge would key on drifted arguments"
            )


def apply_model_rewrite(ledger: FrameLedger, rewrite_fn, transcript: str) -> str:
    pre_open = ledger.open_ids()
    rewritten = rewrite_fn(transcript)  # model-driven, opaque
    # The rewrite is only trusted if it can prove it preserved open frames.
    post_open = ledger.open_ids()  # ledger is source of truth, not the text
    post_bindings = {cid: ledger.frames[cid].arg_binding_hash for cid in post_open}
    verify_rewrite_preconditions(ledger, pre_open, post_open, post_bindings)
    return rewritten
