# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-context-compaction-as-a-lossy-transform-and-re-derive-task-critical-invariants-rather-than-trusting-the-summary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-context-compaction-as-a-lossy-transform-and-re-derive-task-critical-invariants-rather-than-trusting-the-summary.warrant.json
# Markdown SHA-256:   1b64c9a873d74db4e164fa2e49cba5708f7591619cd94e1c6c758f373033369c
# Code AST SHA-256:   05114f912372aeb0571219c8552466258224ed59d614660697dadf0fe2b9e79c
# Verified Classes:   CompactionInvariantError, StepClass, Step, AgentState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionInvariantError(RuntimeError):
    """Raised when an irreversible step's precondition exists only in summarized state."""
    pass


class StepClass(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"


@dataclass
class Step:
    name: str
    cls: StepClass
    precondition_key: str


@dataclass
class AgentState:
    pinned_invariants: dict = field(default_factory=dict)   # verbatim, never summarized
    summary: str = ""                                        # lossy, narrative only
    external_store: dict = field(default_factory=dict)       # authoritative, re-readable


def compact(state: AgentState, folded_turns: list[str]) -> AgentState:
    # Summary is narrative-only; binding clauses are extracted to pinned_invariants
    # BEFORE folding, never through the summarizer.
    for turn in folded_turns:
        if turn.startswith("CONSTRAINT:"):
            key, _, val = turn[len("CONSTRAINT:"):].partition("=")
            state.pinned_invariants[key.strip()] = val.strip()
    state.summary = summarize_narrative(folded_turns)  # lossy, expected
    return state


def summarize_narrative(turns: list[str]) -> str:
    return " ".join(t for t in turns if not t.startswith("CONSTRAINT:"))


def confirm_precondition(state: AgentState, step: Step) -> str:
    key = step.precondition_key
    # Re-derive from pinned block + external store, never from summary.
    if key in state.pinned_invariants:
        return state.pinned_invariants[key]
    if key in state.external_store:
        return state.external_store[key]
    if step.cls is StepClass.IRREVERSIBLE:
        raise CompactionInvariantError(
            f"step '{step.name}' is irreversible but precondition '{key}' "
            f"exists only in summarized state; refusing to proceed on lossy summary"
        )
    return ""  # reversible step may proceed on best-effort state


def execute(state: AgentState, step: Step) -> str:
    precondition = confirm_precondition(state, step)
    return f"executed {step.name} under precondition={precondition!r}"


# Trace of the observed failure, now gated:
state = AgentState()
compact(state, [
    "CONSTRAINT: invoices_ddl_gate = advisory_lock_release_signal_step_31",
    "we will remediate billing then invoices",
])
# At step 24 the agent reaches an irreversible DDL; precondition not in pinned
# block because it was misclassified, and summary does not carry it.
ddl = Step("alter_invoices", StepClass.IRREVERSIBLE, "invoices_ddl_gate")
try:
    execute(state, ddl)  # pinned block present -> confirmed; if absent -> raises
    assert state.pinned_invariants["invoices_ddl_gate"].endswith("step_31")
except CompactionInvariantError as e:
    # Halts loudly instead of silently dropping the table.
    raise CompactionInvariantError(f"compaction boundary halt: {e}") from e
