# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-introduced-by-its-own-context-compaction-and-why-do-token-savings-metrics-certify-lossy-summaries-as-faithf.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-introduced-by-its-own-context-compaction-and-why-do-token-savings-metrics-certify-lossy-summaries-as-faithf.warrant.json
# Markdown SHA-256:   8963d9ea26a81d25b65208bc9867940dbfca76532a8ecf2d92db2b282519e46f
# Code AST SHA-256:   1a4014978434f69e52286d7d6f01bda18e56859a1d6a65aef7db6e39f4e9578e
# Verified Classes:   CompactionFidelityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionFidelityError(RuntimeError):
    """Raised when a compacted context fails decision-equivalence against its origin."""
    pass


# Tokens that carry control flow, not content. Their survival is non-negotiable.
PROTECTED_CLASSES = ("negation", "modality", "actor_binding", "threshold_polarity")


def audit_compaction(origin_predicates, compacted_state, *, chained=False, origin_anchor=None):
    """
    Differential audit: a predicate survives only if its polarity, bound actor,
    and threshold are intact in the compacted state. Similarity is ignored.
    """
    if chained and origin_anchor is None:
        # Chained compaction without an origin anchor cannot be audited against
        # ground truth; drift compounds while per-step scores stay high.
        raise CompactionFidelityError(
            "chained compaction has no origin anchor; cannot certify decision-equivalence"
        )

    reference = origin_anchor if chained else origin_predicates
    lost = []
    for pred in reference:
        surviving = compacted_state.get(pred.id)
        if surviving is None:
            lost.append((pred.id, "dropped"))
            continue
        if surviving.polarity != pred.polarity:
            # The catastrophic case: negation inverted, summary still reads fluent.
            lost.append((pred.id, "polarity_inverted"))
        elif surviving.bound_actor != pred.bound_actor:
            # Constraint re-bound from agent-prohibition to state-fact.
            lost.append((pred.id, "actor_rebound"))
        elif surviving.threshold != pred.threshold:
            lost.append((pred.id, "threshold_drift"))

    if lost:
        raise CompactionFidelityError(
            f"compaction failed decision-equivalence on {len(lost)} predicate(s): {lost}"
        )
    return True


def resume_from_compaction(compacted_state, pending_decisions, *, chained=False, origin=None):
    # Fidelity is certified by replaying decisions, never by scoring the summary text.
    audit_compaction(pending_decisions, compacted_state, chained=chained, origin_anchor=origin)
    return compacted_state
