# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-lossy-compaction-summary-has-silently-dropped-a-precondition-still-needed-by-a-pending-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-lossy-compaction-summary-has-silently-dropped-a-precondition-still-needed-by-a-pending-tool-call.warrant.json
# Markdown SHA-256:   34aad61b483496de29e83b55c75aa5090ad9889628f2e6311904fc44a3b2eae0
# Code AST SHA-256:   2ef0d13682f63d357f84f44f1f791b9e9ed8a4e47330ec403384915a0d6f5491
# Verified Classes:   UnboundPreconditionError, Binding, PendingCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class UnboundPreconditionError(RuntimeError):
    """Raised when a pending tool call's argument has no surviving binding."""


@dataclass
class Binding:
    name: str
    value: Any
    source: str  # "observed", "compaction", "user"


@dataclass
class PendingCall:
    tool: str
    args: dict
    bindings: dict = field(default_factory=dict)


def verify_pending_call(call: PendingCall) -> None:
    """Refuse to execute a call whose args are not each bound to a surviving fact."""
    unbound = [a for a in call.args if a not in call.bindings]
    if unbound:
        raise UnboundPreconditionError(
            f"tool={call.tool!r} has unbound args {unbound}; "
            f"summary dropped their provenance. Re-derive or escalate, do not default."
        )
    for name, b in call.bindings.items():
        if b.source == "compaction" and b.value is None:
            raise UnboundPreconditionError(
                f"arg {name!r} bound by compaction but value is None "
                f"(summary hollowed the binding); treat as UNBOUND."
            )


def execute(call: PendingCall, dispatch) -> Any:
    verify_pending_call(call)
    return dispatch(call.tool, call.args)


# Failure trace from the observed session:
bad = PendingCall(
    tool="edit_file",
    args={"path": "migrate.py", "ctor": "BatchWriter(flush_interval=0)"},
    bindings={
        # summary mentioned "constructor signature" but emitted no value
        "ctor": Binding("ctor", None, "compaction"),
        # path was re-derived from summary prose, not bound
    },
)
try:
    execute(bad, lambda t, a: {"ok": True})
except UnboundPreconditionError as e:
    print("halted before silent violation:", e)
