# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-hierarchical-summarization-loss-and-the-unrecoverable-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-hierarchical-summarization-loss-and-the-unrecoverable-checkpoint.warrant.json
# Markdown SHA-256:   106e1823d5ae1c114ef328e76afe025a120ba8d5eb1f87609d2f95752602b154
# Code AST SHA-256:   7616d938a2e108f42e5a6a73364a53dfbf89ba4d3113fe0134eb044fd346788d
# Verified Classes:   CompactionProvenanceError, Checkpoint
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CompactionProvenanceError(RuntimeError):
    """Raised when an agent attempts an irreversible action whose
    supporting facts originate from a lossy checkpoint with no
    re-verification path."""
    pass


class Checkpoint:
    def __init__(self, summary: str, compression_ratio: float,
                 raw_span_retrievable: bool, dropped_facts: list[str]):
        self.summary = summary
        self.compression_ratio = compression_ratio
        self.raw_span_retrievable = raw_span_retrievable
        self.dropped_facts = dropped_facts  # explicit negative space

    def is_authoritative(self) -> bool:
        # A checkpoint is only authoritative if it is lossless
        # (ratio ~ 1.0) or if raw spans remain retrievable.
        return self.raw_span_retrievable or self.compression_ratio >= 0.99


def guard_irreversible_action(checkpoint: Checkpoint,
                              action: str,
                              depends_on: list[str]) -> None:
    """Enforce the invariant: irreversible actions must not rest on
    lossy, non-retrievable checkpoints without re-verification."""
    if action not in {"write", "delete", "migrate", "send"}:
        return  # reversible actions are exempt

    if checkpoint.is_authoritative():
        return

    # Lossy checkpoint + irreversible action: the depended-on facts
    # may have been silently dropped (e.g. 'already migrated' -> 'migrated').
    unverified = [f for f in depends_on
                  if f not in checkpoint.summary
                  or f in checkpoint.dropped_facts]
    if unverified:
        raise CompactionProvenanceError(
            f"Irreversible action '{action}' depends on facts "
            f"{unverified} that are not verifiably present in a "
            f"lossy checkpoint (ratio={checkpoint.compression_ratio:.2f}, "
            f"raw_span_retrievable={checkpoint.raw_span_retrievable}). "
            f"Re-derive from raw span or live observation before proceeding."
        )
