# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-mid-task-and-evicts-the-very-span-that-justified-the-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-mid-task-and-evicts-the-very-span-that-justified-the-eviction.warrant.json
# Markdown SHA-256:   3fb48c7066c80f881e97475406d7f4b4d6174e540c2f03f3e890c38e9e56f161
# Code AST SHA-256:   c730fc72a69131bad0e0f299b1dbbbec4f628222028e7b73bc3e63ecb1a0a3d9
# Verified Classes:   SpanKind, EvictionViolation, Span, Context
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class SpanKind(Enum):
    TOOL_RESULT = "tool_result"
    ASSISTANT_CLAIM = "assistant_claim"
    ASSISTANT_ACTION = "assistant_action"


class EvictionViolation(RuntimeError):
    """Raised when a self-pruning step would evict a failure span without
    a verified supersession observation."""
    pass


@dataclass
class Span:
    span_id: str
    kind: SpanKind
    subject: str          # e.g. "test_parser.py::test_edge_case"
    is_failure: bool      # non-zero exit, exception, 4xx/5xx, parse error
    verified: bool        # True only for externally-observable tool results
    text: str


@dataclass
class Context:
    spans: list[Span] = field(default_factory=list)
    evicted: dict[str, Span] = field(default_factory=dict)  # span_id -> span
    irreversible_log: list[str] = field(default_factory=list)


def can_evict_as_superseded(ctx: Context, target: Span, later: list[Span]) -> bool:
    """A span may be evicted as superseded only if a later VERIFIED observation
    on the same subject establishes success. Assistant claims do not count."""
    if not target.is_failure:
        return True  # non-failure spans may be relevance-evicted freely

    for s in later:
        if s.subject != target.subject:
            continue
        if s.kind is not SpanKind.TOOL_RESULT:
            continue          # claims are hypotheses, not evidence
        if not s.verified:
            continue
        if s.is_failure:
            continue          # still red; not superseded
        return True           # verified green on same subject -> safe
    return False


def self_prune(ctx: Context, candidate: Span, later: list[Span]) -> None:
    if candidate.is_failure and not can_evict_as_superseded(ctx, candidate, later):
        # Do NOT silently drop. Pin it and record the irreversible commitment.
        ctx.irreversible_log.append(
            f"PINNED failure span {candidate.span_id} on {candidate.subject}: "
            f"no verified supersession; eviction refused."
        )
        raise EvictionViolation(
            f"Refusing to evict failure span {candidate.span_id} "
            f"({candidate.subject}) — only assistant claims post-date it, "
            f"no verified tool_result success on the same subject."
        )
    ctx.evicted[candidate.span_id] = candidate
    ctx.spans = [s for s in ctx.spans if s.span_id != candidate.span_id]
