# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-the-self-eviction-paradox-and-the-recency-relevance-inversion.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-the-self-eviction-paradox-and-the-recency-relevance-inversion.warrant.json
# Markdown SHA-256:   3b28333b66379627595f6778ac50d7d0454bbd0d8e3b68ef9fd90102b8929b9b
# Code AST SHA-256:   1da6a8eeefb065f958a234b75fe2bec6a39fd4786b3b356be41a75d89a553d83
# Verified Classes:   SelfEvictionViolation, SpanType, Span, EvictionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class SelfEvictionViolation(RuntimeError):
    """Raised when a self-editing pass attempts to evict a non-evictable span."""


class SpanType(Enum):
    CONSTRAINT = "constraint"   # global invariant; enforced by absence-of-violation
    IDENTITY = "identity"       # binding that must persist across the horizon
    UNIT = "unit"               # unit / format convention
    FACT = "fact"               # recoverable via re-retrieval
    ARTIFACT = "artifact"       # recoverable via re-derivation
    RATIONALE = "rationale"     # eviction justification; must never survive in-window


NON_EVICTABLE_BY_SELF = frozenset(
    {SpanType.CONSTRAINT, SpanType.IDENTITY, SpanType.UNIT}
)


@dataclass
class Span:
    span_id: str
    span_type: SpanType
    text: str
    relevance: float = 0.0
    last_referenced_turn: int = 0


@dataclass
class EvictionPlan:
    turn: int
    to_evict: list[str] = field(default_factory=list)
    rationales: list[str] = field(default_factory=list)


def apply_self_edit(
    window: list[Span],
    plan: EvictionPlan,
    *,
    external_scheduler: bool = False,
) -> list[Span]:
    """
    Apply a model-produced eviction plan to the instance's own window.

    Invariant: a self-editing pass (external_scheduler=False) may not evict
    CONSTRAINT / IDENTITY / UNIT spans, and may not retain RATIONALE spans
    in the surviving window. Violations raise SelfEvictionViolation.
    """
    by_id = {s.span_id: s for s in window}

    for sid in plan.to_evict:
        span = by_id.get(sid)
        if span is None:
            continue
        if not external_scheduler and span.span_type in NON_EVICTABLE_BY_SELF:
            raise SelfEvictionViolation(
                f"turn {plan.turn}: self-edit attempted to evict "
                f"{span.span_type.value} span {sid!r} "
                f"(relevance={span.relevance:.2f}); "
                f"non-reversible — requires external scheduler"
            )

    surviving = [s for s in window if s.span_id not in set(plan.to_evict)]

    # Rationales must not survive as in-window spans: they become a
    # persistent negative prior that defends the deletion on later passes.
    leaked = [s for s in surviving if s.span_type is SpanType.RATIONALE]
    if leaked and not external_scheduler:
        raise SelfEvictionViolation(
            f"turn {plan.turn}: eviction rationale leaked into surviving "
            f"window as {[s.span_id for s in leaked]}; "
            f"rationales belong in the out-of-context audit log"
        )

    return surviving


def self_edit_pass(window: Iterable[Span], plan: EvictionPlan) -> list[Span]:
    return apply_self_edit(list(window), plan, external_scheduler=False)
