# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-pruned-salience-decay-before-it-commits-a-corrupted-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-pruned-salience-decay-before-it-commits-a-corrupted-context-window.warrant.json
# Markdown SHA-256:   47987d97ff57576ecc9a249e0ba8d2ed67f6156276a8b3a8af428882cccab595
# Code AST SHA-256:   f3f082f18a0054a019dbc732e34a067bf259c62dbd43ada903899af23f07ace0
# Verified Classes:   SalienceInversionError, Span, PruneCandidate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field

FALSIFIABLE = re.compile(
    r"(retry_after|quota_exceeded|\brejected\b|\bdenied\b|\bstatus\b\s*[:=]\s*\d{3})",
    re.IGNORECASE,
)
MAX_PRUNE_DEPTH = 1  # second-generation prunes are where salience inversion concentrates


class SalienceInversionError(RuntimeError):
    """Raised when a pruned window would evict the sole evidence for a claim it retains."""


@dataclass
class Span:
    id: str
    text: str
    salience: float
    prune_generation: int = 0


@dataclass
class PruneCandidate:
    surviving: list[Span] = field(default_factory=list)
    evicted: list[Span] = field(default_factory=list)
    generation: int = 0


def commit_prune(candidate: PruneCandidate) -> list[Span]:
    """Gate a model-driven prune before it replaces the live context window."""

    if candidate.generation > MAX_PRUNE_DEPTH:
        raise SalienceInversionError(
            f"prune generation {candidate.generation} exceeds depth {MAX_PRUNE_DEPTH}; "
            "re-ground from external store instead of compressing a compressed window"
        )

    evicted_claims = [
        s for s in candidate.evicted if FALSIFIABLE.search(s.text)
    ]
    surviving_text = " ".join(s.text for s in candidate.surviving)

    for span in evicted_claims:
        claim = FALSIFIABLE.search(span.text).group(1).lower()
        # A surviving span may only stand in for the evicted claim if it
        # preserves the falsifiable token verbatim, not a narrative summary.
        if claim not in surviving_text.lower():
            raise SalienceInversionError(
                f"evicting span {span.id!r} would drop the sole evidence for "
                f"claim {claim!r} while retaining a summary that asserts resolution; "
                "re-ground the claim verbatim before committing the window"
            )

    return candidate.surviving
