# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-write-authority-invariant-when-automatic-context-compaction-summarizes-away-the-not-yet-permitted-half-of-a-tool-call-co.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-write-authority-invariant-when-automatic-context-compaction-summarizes-away-the-not-yet-permitted-half-of-a-tool-call-co.warrant.json
# Markdown SHA-256:   6540fb593f759cfbe98b82a33af27d3535546762730cc23aace6ce6896687223
# Code AST SHA-256:   1c189a709ef8f4794c8e6a75086d7cf2ff8c529e8d0bbd3343b219c5889efc0e
# Verified Classes:   GateNotDischarged, GateStatus, Obligation, ObligationLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class GateNotDischarged(RuntimeError):
    """Raised when a gated action is dispatched while its obligation is still open."""


class GateStatus(Enum):
    OPEN = "open"
    DISCHARGED = "discharged"
    VIOLATED = "violated"


@dataclass
class Obligation:
    gate_id: str
    precondition: str
    gated_action: str
    status: GateStatus = GateStatus.OPEN


@dataclass
class ObligationLedger:
    """Lives OUTSIDE the compactable context region. Never summarized."""
    obligations: dict[str, Obligation] = field(default_factory=dict)

    def open_gate(self, gate_id: str, precondition: str, gated_action: str) -> None:
        self.obligations[gate_id] = Obligation(gate_id, precondition, gated_action)

    def discharge(self, gate_id: str) -> None:
        if gate_id not in self.obligations:
            raise GateNotDischarged(f"unknown gate {gate_id!r}; cannot discharge")
        self.obligations[gate_id].status = GateStatus.DISCHARGED

    def check_dispatch(self, action: str) -> None:
        # Refuse any action whose gate is not discharged, regardless of
        # what the (possibly compacted) model context believes.
        for ob in self.obligations.values():
            if ob.gated_action == action and ob.status is not GateStatus.DISCHARGED:
                raise GateNotDischarged(
                    f"action {action!r} blocked: gate {ob.gate_id!r} "
                    f"({ob.precondition}) is {ob.status.value}"
                )


def dispatch(ledger: ObligationLedger, action: str, tool_fn, *args, **kwargs):
    ledger.check_dispatch(action)
    return tool_fn(*args, **kwargs)


# --- reproduction of the observed failure, now bounded ---
ledger = ObligationLedger()
ledger.open_gate(
    gate_id="budget_reserved",
    precondition="reserve_budget returned reserved=True",
    gated_action="issue_purchase_order",
)

# Step 2: soft failure. Gate stays OPEN. Context compacts. Summary drops the gate.
# Agent resumes and attempts the gated action:
try:
    dispatch(ledger, "issue_purchase_order", lambda: "PO-issued")
except GateNotDischarged as e:
    print(f"refused at boundary: {e}")
    # runtime re-injects verbatim obligation and forces escalation path

# Only after a confirmed discharge may the action proceed:
ledger.discharge("budget_reserved")
assert dispatch(ledger, "issue_purchase_order", lambda: "PO-issued") == "PO-issued"
