# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-stop-trusting-its-own-salience-scores-the-summarization-lag-invariant-in-self-editing-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-stop-trusting-its-own-salience-scores-the-summarization-lag-invariant-in-self-editing-context-windows.warrant.json
# Markdown SHA-256:   08e032dca159d174278121a0521da3341d0512d9f2c799b51c752c349c3e1d0a
# Code AST SHA-256:   010623933cf103edcf98845297e96768722294cbcd1905459df93a575c35870f
# Verified Classes:   SalienceLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SalienceLaunderingError(RuntimeError):
    """Raised when a self-edit would evict material and replace it with a
    summary that asserts a completeness the summarizer cannot verify."""
    pass


def apply_self_edit(window, evictions, summary, enumerated_hypotheses):
    # An eviction is only sound if the span is recoverable OR provably
    # irrelevant under every enumerated hypothesis.
    for span in evictions:
        recoverable = span.external_ref is not None
        provably_irrelevant = all(
            not span.relevant_under(h) for h in enumerated_hypotheses
        )
        if not (recoverable or provably_irrelevant):
            if summary.asserts_completeness():
                raise SalienceLaunderingError(
                    f"evicting span {span.id} (recoverable={recoverable}, "
                    f"provably_irrelevant={provably_irrelevant}) while summary "
                    f"asserts completeness; consumer cannot detect loss"
                )
            summary.add_refetch_pointer(span)

    if summary.asserts_completeness() and not summary.scope_is_hypothesis_bounded():
        raise SalienceLaunderingError(
            "summary asserts unscoped completeness; scope it to a hypothesis "
            "or attach external references for all evicted spans"
        )

    return window.with_edit(evictions=evictions, summary=summary)
