# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-under-salience-pressure-but-retains-the-pruning-rationale.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-under-salience-pressure-but-retains-the-pruning-rationale.warrant.json
# Markdown SHA-256:   156475b544b90a75b0f490d87f62db94f24f451bc86fa53cedd97c901926d7a9
# Code AST SHA-256:   0a92f9d10b61e6224161894aa9bed8cf7cbe910606d464ab2f18140f212e9fbb
# Verified Classes:   ProvenanceCollapseError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceCollapseError(RuntimeError):
    """Raised when a self-pruning step would retain an unmarked summary
    of contested content whose falsifier tokens are being evicted."""
    pass


CONTESTED = "contested"
STABLE = "stable"


def self_prune(buffer, eviction_set, summary, region_class, rederivable):
    """
    buffer: list of token records still in context
    eviction_set: ids of records the model wants to drop
    summary: the rationale the model wants to retain in their place
    region_class: STABLE or CONTESTED
    rederivable: whether an external source can still be queried
    """
    if region_class == CONTESTED:
        if not rederivable:
            # No surviving falsifier and no external re-derivation path:
            # retaining an unmarked summary here is provenance collapse.
            raise ProvenanceCollapseError(
                f"refusing unmarked summary of contested region {eviction_set!r}: "
                f"falsifier would be evicted with no re-derivation path; "
                f"retain a falsifier token or tag summary as unverified"
            )
        # Contested but re-derivable: summary must carry an unverified tag
        # naming the evicted set.
        summary = {"tag": "unverified", "evicted": list(eviction_set), "text": summary}

    kept = [r for r in buffer if r["id"] not in eviction_set]
    kept.append({"id": "__summary__", "content": summary})
    return kept
