# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-self-rewriting-context-so-that-a-summarization-pass-cannot-silently-delete-the-precondition-of-a-pending-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-self-rewriting-context-so-that-a-summarization-pass-cannot-silently-delete-the-precondition-of-a-pending-tool-call.warrant.json
# Markdown SHA-256:   831c70b7915d04b81203f21e0550f4dfcb39ce173c525328f9e982e76b65adcc
# Code AST SHA-256:   c812a43c66dc9b7d0719853c9024b8dc23126d817290e3ac7bb715aefd5effd3
# Verified Classes:   PreconditionLossError, PendingObligation, RewriteCandidate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PreconditionLossError(RuntimeError):
    """Raised when a self-rewrite would drop a precondition of a pending obligation."""
    pass


@dataclass
class PendingObligation:
    tool_call_id: str
    tool_name: str
    bound_args: dict
    # Preconditions derived from the tool schema + bound args, NOT from prose salience.
    preconditions: list[str] = field(default_factory=list)
    handle: Optional[str] = None  # dereference target in external store, if any


@dataclass
class RewriteCandidate:
    text: str
    verbatim_spans: set[str] = field(default_factory=set)
    dereferenceable_handles: set[str] = field(default_factory=set)


def enumerate_preconditions(obligation: PendingObligation) -> list[str]:
    # Structured extraction: schema constraints + argument bindings.
    # Deliberately excludes any salience-scored prose.
    required = []
    for key, value in obligation.bound_args.items():
        required.append(f"{obligation.tool_name}.{key}={value!r}")
    required.extend(obligation.preconditions)
    return required


def gate_rewrite(
    obligations: list[PendingObligation],
    candidate: RewriteCandidate,
) -> None:
    """Refuse the rewrite if any pending precondition is neither verbatim nor dereferenceable."""
    violations: list[str] = []
    for ob in obligations:
        for pre in enumerate_preconditions(ob):
            verbatim = pre in candidate.verbatim_spans or pre in candidate.text
            deref = ob.handle is not None and ob.handle in candidate.dereferenceable_handles
            if not (verbatim or deref):
                violations.append(f"{ob.tool_call_id}:{pre}")
    if violations:
        raise PreconditionLossError(
            "rewrite would drop preconditions of pending obligations: "
            + ", ".join(violations)
            + "; refuse rewrite, defer to quiescence or use handle dereference"
        )


def apply_rewrite(obligations: list[PendingObligation], candidate: RewriteCandidate) -> str:
    # Gate runs against the CANDIDATE window, not the source window.
    gate_rewrite(obligations, candidate)
    return candidate.text
