# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-lossy-auto-compaction-when-a-summarizer-preserves-commitments-but-drops-preconditions.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-lossy-auto-compaction-when-a-summarizer-preserves-commitments-but-drops-preconditions.warrant.json
# Markdown SHA-256:   1caabdd0efbf257b9d87c8f80ddfcc113fa449cb303c3e4cb349ace0393a4e85
# Code AST SHA-256:   bcd99cf1b4214c903014c2883cd5ab9f48cca6a73339b3c89393efd303e7a546
# Verified Classes:   ScopeErosionError, Commitment
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

IRREVERSIBLE_VERBS = {"deploy", "scale", "delete", "send", "migrate", "drop"}


class ScopeErosionError(RuntimeError):
    """Raised when a compacted commitment lost its scope/guard and cannot be safely executed."""
    pass


@dataclass
class Commitment:
    verb: str
    obj: str
    trigger: str
    scope: Optional[str]   # None == scope was elided by the summarizer
    guard: Optional[str]   # None == guard was elided by the summarizer

    def is_environment_widening(self) -> bool:
        return self.verb.lower() in IRREVERSIBLE_VERBS


def gate_compacted_commitment(c: Commitment, scope_revalidated: bool) -> Commitment:
    """
    Enforce the invariant: no irreversible commitment executes without a recovered scope.
    Called immediately after auto-compaction, before any tool dispatch.
    """
    if c.scope is None or c.guard is None:
        if c.is_environment_widening() and not scope_revalidated:
            # Downgrade to pending_scope; block execution until re-validation.
            raise ScopeErosionError(
                f"Commitment '{c.verb} {c.obj}' (trigger={c.trigger!r}) lost scope/guard "
                f"during compaction (scope={c.scope!r}, guard={c.guard!r}). "
                f"Irreversible and environment-widening: re-validate scope before dispatch."
            )
        # Reversible or scope-local: allowed to proceed under drop-and-replan.
        return Commitment(c.verb, c.obj, c.trigger, scope="*reversible*", guard=c.guard or "*")
    return c


def dispatch(c: Commitment, scope_revalidated: bool) -> str:
    safe = gate_compacted_commitment(c, scope_revalidated)
    return f"executed {safe.verb} {safe.obj} within scope={safe.scope} guard={safe.guard}"
