# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-task-and-the-lossy-summary-silently-drops-the-causal-antecedent-of-a-pending-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-task-and-the-lossy-summary-silently-drops-the-causal-antecedent-of-a-pending-tool-call.warrant.json
# Markdown SHA-256:   a5bd7cdd7b7e376f6017decd2cc3e486b4d577aabc29461f50e01364435490f3
# Code AST SHA-256:   f2912b643a1eb5730fd1ef7a4c9a92a68e087a416374b0f0e4dd7952d86642f9
# Verified Classes:   AntecedentClosureError, PendingAction, CompactedState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AntecedentClosureError(RuntimeError):
    """Raised when a pending action in compacted context has no resolvable precondition."""
    pass


@dataclass
class PendingAction:
    name: str
    args: dict
    irreversible: bool
    precondition_ref: Optional[str] = None  # pointer into structured constraint ledger


@dataclass
class CompactedState:
    summary: str
    pending: list[PendingAction] = field(default_factory=list)
    constraint_ledger: dict[str, str] = field(default_factory=dict)


def execute_pending(state: CompactedState, action: PendingAction) -> str:
    # Fail closed: an irreversible pending action must carry a resolvable warrant.
    if action.irreversible:
        if action.precondition_ref is None:
            raise AntecedentClosureError(
                f"pending action {action.name} is irreversible but carries no "
                f"precondition_ref; compaction likely dropped its causal antecedent"
            )
        if action.precondition_ref not in state.constraint_ledger:
            raise AntecedentClosureError(
                f"precondition_ref {action.precondition_ref!r} for {action.name} "
                f"is absent from the constraint ledger; guard was evicted, not externalized"
            )
        guard = state.constraint_ledger[action.precondition_ref]
        if "unresolved" in guard or "provisional" in guard:
            raise AntecedentClosureError(
                f"pending action {action.name} is gated by unresolved precondition: {guard!r}"
            )
    return f"executed {action.name} with {action.args}"


# Trace of the observed failure, now bounded:
bad = CompactedState(
    summary="Next: transfer 400 from A to B to settle the discrepancy.",
    pending=[PendingAction("transfer_funds", {"from": "A", "to": "B", "amount": 400},
                           irreversible=True, precondition_ref=None)],
)
try:
    execute_pending(bad, bad.pending[0])
except AntecedentClosureError as e:
    print(f"BLOCKED (correct): {e}")
