# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-model-driven-context-rewrite-operator-has-silently-invalidated-a-pending-tool-call-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-model-driven-context-rewrite-operator-has-silently-invalidated-a-pending-tool-call-obligation.warrant.json
# Markdown SHA-256:   9175bae2fdbb9fe267256ab483db91d6f4b2be38940aee7d4f54b30f3c64fafe
# Code AST SHA-256:   b8a25c77024c9c723b3892dab2478ad0b2caf8a9cf2858b162ad6245f5915986
# Verified Classes:   OrphanedObligation, RewriteRejected, Obligation, Context
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class OrphanedObligation(RuntimeError):
    """Raised when a tool result resolves against a context that no longer
    contains a byte-exact copy of the dispatched argument set."""


class RewriteRejected(RuntimeError):
    """Raised when a model-authored rewrite operator's write-set intersects
    the obligation pin-set."""


@dataclass(frozen=True)
class Obligation:
    call_id: str
    arg_fingerprint: str  # byte-exact, frozen at dispatch
    span_ids: FrozenSet[str]


@dataclass
class Context:
    spans: dict = field(default_factory=dict)  # span_id -> text
    open_calls: dict = field(default_factory=dict)  # call_id -> Obligation

    def pin_set(self) -> FrozenSet[str]:
        pinned = set()
        for ob in self.open_calls.values():
            pinned |= ob.span_ids
        return frozenset(pinned)


def apply_rewrite(ctx: Context, op_write_set: FrozenSet[str], apply_fn) -> Context:
    if op_write_set & ctx.pin_set():
        raise RewriteRejected(
            f"operator write-set {sorted(op_write_set)} intersects "
            f"obligation pin-set {sorted(ctx.pin_set())}"
        )
    return apply_fn(ctx)


def resolve_tool_result(ctx: Context, call_id: str, result: str) -> Context:
    ob = ctx.open_calls.get(call_id)
    if ob is None:
        raise OrphanedObligation(f"no open obligation for {call_id}")
    live = "".join(ctx.spans.get(s, "") for s in ob.span_ids)
    if ob.arg_fingerprint not in live:
        raise OrphanedObligation(
            f"argument fingerprint for {call_id} absent from rewritten context; "
            f"refusing auto-resolve, escalate to re-plan"
        )
    del ctx.open_calls[call_id]
    return ctx
