# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-destroyed-a-load-bearing-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-destroyed-a-load-bearing-constraint.warrant.json
# Markdown SHA-256:   ca7a485e0f959091164c77d5e82e6165a46deb5d0c09d0186ecde40c0f830f29
# Code AST SHA-256:   09b05798a5da90a813ef881d55e40653edf248ba9cd23d93f9b0001550ed6171
# Verified Classes:   CompactionInvariantViolation, ConstraintLedger, CompactionTombstone, AgentWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionInvariantViolation(RuntimeError):
    """Raised when an irreversible action is attempted after a compaction
    boundary without a post-boundary constraint re-anchor."""
    pass


@dataclass
class ConstraintLedger:
    # Append-only; excluded from summarization by policy.
    entries: list[str] = field(default_factory=list)
    version: int = 0

    def append(self, constraint: str) -> None:
        self.entries.append(constraint)
        self.version += 1


@dataclass
class CompactionTombstone:
    boundary_step: int
    dropped_range: tuple[int, int]
    ledger_version_at_boundary: int


@dataclass
class AgentWindow:
    current_step: int = 0
    last_tombstone: Optional[CompactionTombstone] = None
    ledger: ConstraintLedger = field(default_factory=ConstraintLedger)

    def compact(self, dropped_range: tuple[int, int]) -> None:
        # Lossy summarization happens here; only the tombstone survives verbatim.
        self.last_tombstone = CompactionTombstone(
            boundary_step=self.current_step,
            dropped_range=dropped_range,
            ledger_version_at_boundary=self.ledger.version,
        )

    def re_anchor(self) -> None:
        # Re-inject ledger verbatim; must happen before irreversible actions.
        if self.last_tombstone is None:
            return
        if self.ledger.version < self.last_tombstone.ledger_version_at_boundary:
            raise CompactionInvariantViolation(
                f"Ledger version {self.ledger.version} predates boundary "
                f"{self.last_tombstone.boundary_step}; ledger was itself compacted."
            )
        self.last_tombstone = CompactionTombstone(
            boundary_step=self.current_step,
            dropped_range=self.last_tombstone.dropped_range,
            ledger_version_at_boundary=self.ledger.version,
        )

    def irreversible_call(self, tool: str, args: dict) -> None:
        # Structural predicate, NOT a judgment about summary quality.
        if self.last_tombstone is not None:
            anchored = (
                self.ledger.version
                >= self.last_tombstone.ledger_version_at_boundary
                and self.last_tombstone.boundary_step < self.current_step
            )
            if not anchored:
                raise CompactionInvariantViolation(
                    f"Irreversible call {tool} attempted at step {self.current_step} "
                    f"after compaction boundary {self.last_tombstone.boundary_step} "
                    f"without post-boundary re-anchor. Constraint set is unverified; "
                    f"the summary cannot prove a negative constraint survived."
                )
        # ... execute tool ...


def run_step(window: AgentWindow, step: int, tool: str, args: dict) -> None:
    window.current_step = step
    if step == 94:
        window.compact(dropped_range=(1, 80))
    if step == 117:
        # Agent "decides" to write legacy_id; guardrail fires before the write.
        window.irreversible_call(tool="db.update", args={"table": "users", "col": "legacy_id"})
