# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-the-lossy-summarization-integrity-boundary-in-long-horizon-agent-context.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-the-lossy-summarization-integrity-boundary-in-long-horizon-agent-context.warrant.json
# Markdown SHA-256:   64ecbb65c0c52e590b7a09faa472a274232ba92c320c1d5734eb49e0ed79bd34
# Code AST SHA-256:   f974706536df5dea17e18a53afa74c5f6cbe8916ac4b5c668ec7594d904378c9
# Verified Classes:   CompactionRefusedError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CompactionRefusedError(RuntimeError):
    """Raised when auto-compaction would evict an obligation literal that is
    not recoverable from the summary under measured class fidelity."""
    pass


# Per-obligation-class fidelity measured on held-out probes. Aggregate quality
# is deliberately NOT used: it masks class-specific cliffs.
CLASS_FIDELITY = {
    "bound_literal": 0.61,   # identifiers, paths, IDs
    "negation":      0.68,   # "do not drop", "never", "except"
    "numeric_bound": 0.74,
    "ordering":      0.83,
}
FIDELITY_THRESHOLD = 0.95


def obligation_is_recoverable(obligation, retained_tail_text, summary_text):
    """True iff the obligation is (a) verbatim in the retained tail, or
    (b) derivable from the summary at >= threshold class fidelity."""
    if obligation.literal in retained_tail_text:
        return True
    fidelity = CLASS_FIDELITY.get(obligation.klass)
    if fidelity is None:
        return False  # unknown class -> never assume recoverable
    if fidelity < FIDELITY_THRESHOLD:
        return False
    # Even at high fidelity, require the literal to actually appear in the
    # summary; fidelity is a prior, not a substitute for evidence.
    return obligation.literal in summary_text


def maybe_auto_compact(context, summary_text, retained_tail_text):
    """Gate auto-compaction on obligation recoverability, not capacity."""
    if not context.over_capacity_threshold():
        return context  # nothing to do

    # C2: if a durable transcript store exists, eviction is reversible.
    if context.has_durable_transcript():
        return context.compact(summary_text, retained_tail_text)

    # C3/C4: any live, downstream-bound obligation that cannot be recovered
    # blocks eviction outright.
    for obligation in context.live_bound_obligations():
        if not obligation_is_recoverable(
            obligation, retained_tail_text, summary_text
        ):
            raise CompactionRefusedError(
                f"refusing to compact: obligation {obligation.id!r} "
                f"(class={obligation.klass!r}, literal={obligation.literal!r}) "
                f"is not recoverable from retained tail or summary; "
                f"pin the span or externalize the literal before eviction"
            )

    return context.compact(summary_text, retained_tail_text)
