# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-when-model-driven-pruning-has-inverted-the-relevance-gradient-inside-a-self-editing-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-when-model-driven-pruning-has-inverted-the-relevance-gradient-inside-a-self-editing-context-window.warrant.json
# Markdown SHA-256:   70684fdcc4a20c005914808327f2c7b0457685abcbafa0ba14ad6265f9b1ab29
# Code AST SHA-256:   39611c2da2f42e35f6eb5b31c202e83fa89d84296a7e25147b4da971dcf0e579
# Verified Classes:   SpanKind, PruningGradientInversion, Span, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SpanKind(Enum):
    PROCEDURAL = "procedural"
    CONSTRAINT = "constraint"


class PruningGradientInversion(RuntimeError):
    """Raised when a self-edit pass would evict constraint spans below saturation."""
    pass


@dataclass
class Span:
    id: str
    kind: SpanKind
    text: str
    trajectory_relevance: float  # score relative to current plan; drifts


@dataclass
class ContextWindow:
    spans: list[Span] = field(default_factory=list)
    token_budget: int = 100_000
    saturation_threshold: float = 0.80

    def utilization(self) -> float:
        used = sum(len(s.text.split()) for s in self.spans)
        return used / self.token_budget


def self_prune(window: ContextWindow, keep_ratio: float = 0.5) -> ContextWindow:
    """
    Model-driven pruning: evict lowest trajectory-relevance spans.
    Guard: constraint spans may only be evicted under budget saturation,
    and never summarized by the active (plan-committed) model.
    """
    saturated = window.utilization() >= window.saturation_threshold
    ranked = sorted(window.spans, key=lambda s: s.trajectory_relevance)
    n_evict = int(len(ranked) * (1 - keep_ratio))
    evict = ranked[:n_evict]

    constraint_evictions = [s for s in evict if s.kind is SpanKind.CONSTRAINT]
    if constraint_evictions and not saturated:
        raise PruningGradientInversion(
            f"Pruning pass at {window.utilization():.0%} utilization would evict "
            f"{len(constraint_evictions)} constraint span(s) "
            f"({[s.id for s in constraint_evictions]}) on trajectory-relative score. "
            f"Relevance gradient inverted: prohibitions are off-trajectory by definition. "
            f"Refusing irreversible mutation; evict procedural spans or surface conflict."
        )

    evicted_ids = {s.id for s in evict}
    window.spans = [s for s in window.spans if s.id not in evicted_ids]
    return window


def run_edit_pass(window: ContextWindow) -> ContextWindow:
    try:
        return self_prune(window)
    except PruningGradientInversion as e:
        # Do not retry with the same model; the committed plan biases the summary.
        raise PruningGradientInversion(
            f"Edit pass aborted and must be escalated to an external controller: {e}"
        ) from e
