# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-pruning-context-windows-from-evicting-their-own-continuation-anchors.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-pruning-context-windows-from-evicting-their-own-continuation-anchors.warrant.json
# Markdown SHA-256:   d103da898eda07101002d6b543e21f20c3438f2a6a61790571baa332111ca2f1
# Code AST SHA-256:   15d74ca37d0efd53be26d31fa49080466d5fb940acd90899fa42b0b34b9eeace
# Verified Classes:   AnchorEvictionError, SpanClass, Span, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class AnchorEvictionError(RuntimeError):
    """Raised when a self-edit would drop the only copy of a pinned span."""


class SpanClass(Enum):
    CONSTRAINT = "constraint"
    LIVE_BINDING = "live_binding"
    PROGRESS_ANCHOR = "progress_anchor"
    COMPLETED_DETAIL = "completed_detail"
    CURRENT_STEP_SCRATCH = "current_step_scratch"


PINNED = {SpanClass.CONSTRAINT, SpanClass.LIVE_BINDING, SpanClass.PROGRESS_ANCHOR}


@dataclass
class Span:
    span_id: str
    text: str
    cls: SpanClass
    relevance: float = 0.0


@dataclass
class ContextWindow:
    spans: list[Span] = field(default_factory=list)

    def pinned_ids(self) -> set[str]:
        return {s.span_id for s in self.spans if s.cls in PINNED}


def self_prune(window: ContextWindow, evict_below: float, current_step: int) -> ContextWindow:
    """Model-driven eviction with pin-before-score gating.

    Refuses to evict pinned spans and refuses to score the current step's
    own scratch spans (the author cannot judge its own scaffolding).
    """
    pinned = window.pinned_ids()
    survivors: list[Span] = []
    evicted_pinned: list[str] = []

    for span in window.spans:
        # Hard gate: pinning is decided before relevance is consulted.
        if span.span_id in pinned:
            survivors.append(span)
            continue

        # Do not let the current step score its own authored scratch.
        if span.cls is SpanClass.CURRENT_STEP_SCRATCH:
            survivors.append(span)
            continue

        if span.relevance < evict_below:
            # Guard: never evict the only copy of a pinned-class span.
            if span.cls in PINNED:
                evicted_pinned.append(span.span_id)
                continue
            continue  # evict: drop from survivors

        survivors.append(span)

    if evicted_pinned:
        # Should be unreachable given the gate, but enforce the invariant.
        raise AnchorEvictionError(
            f"self-edit at step {current_step} would evict pinned anchors "
            f"{evicted_pinned}; refusing degraded window"
        )

    # Continuation invariant: a progress anchor must survive every edit.
    if not any(s.cls is SpanClass.PROGRESS_ANCHOR for s in survivors):
        raise AnchorEvictionError(
            f"post-edit window at step {current_step} has no progress anchor; "
            "executor cannot answer 'what step am I on'"
        )

    return ContextWindow(spans=survivors)


def run_step(window: ContextWindow, step: int) -> ContextWindow:
    try:
        return self_prune(window, evict_below=0.25, current_step=step)
    except AnchorEvictionError as exc:
        # Saturate and escalate rather than continue on a degraded window.
        raise AnchorEvictionError(f"halting step {step}: {exc}") from exc
