# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-lossy-context-compaction-has-silently-destroyed-a-load-bearing-commitment-before-the-next-tool-call-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-lossy-context-compaction-has-silently-destroyed-a-load-bearing-commitment-before-the-next-tool-call-executes.warrant.json
# Markdown SHA-256:   7a21d203af81171aaf6bdba13a2911fce0fbba4a1afdaabde1699f4deef01d70
# Code AST SHA-256:   221bd691b61d452d80047035d8bd3411b1d4d2b75f09f79345a4a065a7af3214
# Verified Classes:   CommitmentViolation, Commitment, ObligationRegister
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class CommitmentViolation(RuntimeError):
    """Raised when a side-effecting tool call would breach a registered,
    compaction-fragile obligation that lossy summarization may have erased."""


@dataclass
class Commitment:
    cid: str
    scope: str                      # e.g. "accounts.svc-billing"
    satisfied: Callable[[dict], bool]
    description: str                # verbatim, never summarized


@dataclass
class ObligationRegister:
    entries: dict[str, Commitment] = field(default_factory=dict)

    def register(self, c: Commitment) -> None:
        # Written at formation time, outside the summarized region.
        self.entries[c.cid] = c

    def reinject(self) -> list[str]:
        # Re-injected verbatim after every compaction pass.
        return [f"[{c.cid}] {c.description}" for c in self.entries.values()]


def dispatch_side_effecting(call: dict, register: ObligationRegister) -> dict:
    """Gate every side-effecting call against the obligation register.
    The model does not need to remember the constraint; the dispatcher refuses."""
    target = call.get("target", "")
    for c in register.entries.values():
        if target.startswith(c.scope) and not c.satisfied(call):
            raise CommitmentViolation(
                f"call to {target!r} blocked: obligation {c.cid!r} "
                f"({c.description!r}) unsatisfied; compaction may have erased it"
            )
    return {"status": "dispatched", "call": call}


def run_turn(agent_call: dict, register: ObligationRegister) -> dict:
    if agent_call.get("kind") == "side_effecting":
        return dispatch_side_effecting(agent_call, register)
    return {"status": "read_only", "call": agent_call}


# --- trace of the observed failure, now bounded ---
reg = ObligationRegister()
reg.register(Commitment(
    cid="fin-signoff",
    scope="accounts.svc-billing",
    satisfied=lambda call: call.get("authorized_by") == "finance-signoff",
    description="Do not modify svc-billing rows until finance signs off.",
))

# turn 31, post-compaction: agent has forgotten the constraint and tries the write
post_compaction_call = {
    "kind": "side_effecting",
    "target": "accounts.svc-billing",
    "op": "reconcile_write",
    "rows": 1204,
}

try:
    run_turn(post_compaction_call, reg)
except CommitmentViolation as e:
    print("BLOCKED:", e)
    # agent now sees the constraint it had lost, via refusal rather than recall
