# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-lossy-context-compaction-as-a-reversible-operation-rather-than-a-destructive-one.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-lossy-context-compaction-as-a-reversible-operation-rather-than-a-destructive-one.warrant.json
# Markdown SHA-256:   65ba893448363b6c6858833824a81beca67bba4e0a35e782dd87db63ed22e38d
# Code AST SHA-256:   61e9ec9555451203a0a78c4f637b2027e3ed7cdd262007778ae9936bbb88f8de
# Verified Classes:   CompactionFidelityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionFidelityError(RuntimeError):
    """Raised when a context compaction is treated as reversible but no
    pre-causal, sufficient, reachable recovery checkpoint exists."""
    pass


def compact_context(
    context_tokens: list[str],
    summary: str,
    checkpoint_id: str | None,
    checkpoint_is_pre_causal: bool,
    checkpoint_sufficient: bool,
    checkpoint_reachable: bool,
    drop_manifest: list[str] | None,
) -> dict:
    """Compact working context, asserting reversibility preconditions.

    Returns a compaction record. Raises CompactionFidelityError if the
    caller intends to rely on the summary as ground truth but the
    recovery checkpoint does not satisfy the reversibility invariant.
    """
    reversible = (
        checkpoint_id is not None
        and checkpoint_is_pre_causal
        and checkpoint_sufficient
        and checkpoint_reachable
        and drop_manifest is not None
    )

    if not reversible:
        # The summary now replaces the ground truth. The instance must
        # operate under a degraded-state assumption.
        return {
            "mode": "destructive",
            "summary": summary,
            "checkpoint_id": checkpoint_id,
            "degraded": True,
            "instruction": (
                "Do not perform irreversible actions depending on "
                "summarized facts. Re-acquire from source or escalate."
            ),
        }

    # Guard against the most common silent failure: a checkpoint that
    # exists but is causally downstream of the compaction (i.e., it
    # checkpoints the summary, not the source).
    if checkpoint_id is not None and not checkpoint_is_pre_causal:
        raise CompactionFidelityError(
            f"Checkpoint {checkpoint_id!r} is post-causal: it captures the "
            "summary, not the pre-compaction source. Recovery would "
            "reproduce the loss. Treat compaction as destructive."
        )

    return {
        "mode": "reversible",
        "summary": summary,
        "checkpoint_id": checkpoint_id,
        "dropped": list(drop_manifest or []),
        "degraded": False,
        "instruction": (
            "Summary is a cache. Re-derive from checkpoint before any "
            "constraint-sensitive or irreversible action."
        ),
    }


def act_on_summarized_fact(record: dict, fact: str, irreversible: bool) -> str:
    """Decide whether a summarized fact may be trusted for an action."""
    if record["mode"] == "destructive" and irreversible:
        raise CompactionFidelityError(
            f"Cannot perform irreversible action on summarized fact {fact!r}: "
            "no pre-causal recovery checkpoint; the fact may have been "
            "dropped by lossy compaction. Re-acquire from source."
        )
    if record["mode"] == "reversible" and irreversible:
        return "re-derive from checkpoint before acting"
    return "trust summary (reversible or non-irreversible action)"
