# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-window-and-prunes-the-wrong-token-salience-miscalibration-collapse-in-model-driven-context-comp.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-window-and-prunes-the-wrong-token-salience-miscalibration-collapse-in-model-driven-context-comp.warrant.json
# Markdown SHA-256:   9e1bd0aedec1cec7b2435a52371935a524c49ebe14016973a44c91a2e58202cb
# Code AST SHA-256:   388cfc07f6b17bd034b782223c2fa3823162296010b993fff80a2341288a79f6
# Verified Classes:   SalienceCollapseError, Span, CompactionEvent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

PROTECTED_CLASSES = {"OPERAND", "NEGATION", "CONSTRAINT_LITERAL", "NUMERIC_WITH_UNIT"}


class SalienceCollapseError(RuntimeError):
    """Raised when a model-driven compaction would drop a protected operand."""


@dataclass
class Span:
    text: str
    cls: str
    salience: float


@dataclass
class CompactionEvent:
    kept: list[str] = field(default_factory=list)
    dropped: list[str] = field(default_factory=list)
    protected_retained: list[str] = field(default_factory=list)


def compact(
    spans: Iterable[Span],
    target_tokens: int,
    tau: float = 0.35,
    token_cost=lambda s: max(1, len(s.text) // 4),
) -> tuple[list[Span], CompactionEvent]:
    spans = list(spans)
    protected = [s for s in spans if s.cls in PROTECTED_CLASSES]
    derivable = [s for s in spans if s.cls not in PROTECTED_CLASSES]

    # Invariant 1: protected operands are never subject to model salience.
    kept = list(protected)
    budget = target_tokens - sum(token_cost(s) for s in kept)
    if budget < 0:
        raise SalienceCollapseError(
            f"protected operands alone exceed budget: "
            f"{sum(token_cost(s) for s in kept)} > {target_tokens}"
        )

    event = CompactionEvent(protected_retained=[s.text for s in protected])

    # Invariant 2: only derivable spans may be pruned, and only above tau.
    for s in sorted(derivable, key=lambda x: x.salience, reverse=True):
        cost = token_cost(s)
        if s.salience >= tau and cost <= budget:
            kept.append(s)
            budget -= cost
            event.kept.append(s.text)
        else:
            event.dropped.append(s.text)

    # Invariant 3: no protected operand may appear in dropped set.
    dropped_protected = set(event.dropped) & set(event.protected_retained)
    if dropped_protected:
        raise SalienceCollapseError(
            f"compaction dropped protected operands: {sorted(dropped_protected)}"
        )

    return kept, event


def apply_compaction(spans, target_tokens):
    kept, event = compact(spans, target_tokens)
    # Replay guard: the compacted set must be a strict superset of protected spans.
    original_protected = {s.text for s in spans if s.cls in PROTECTED_CLASSES}
    surviving = {s.text for s in kept}
    if not original_protected.issubset(surviving):
        raise SalienceCollapseError(
            "post-compaction context lost protected operand set; refusing to proceed"
        )
    return kept, event
