# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-self-pruning-context-policy-silently-delete-the-very-evidence-it-needs-to-justify-the-prune.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-self-pruning-context-policy-silently-delete-the-very-evidence-it-needs-to-justify-the-prune.warrant.json
# Markdown SHA-256:   ab93058bef28a47aea5fa8408c08cab754b500d53578311641dfcb2c3976e5a4
# Code AST SHA-256:   fa3bbb993404e2606922c56cabe74d1f7107ffa584da88602a20dd6a40fb6372
# Verified Classes:   SpanKind, PruneViolation, Span, ContextPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SpanKind(Enum):
    INSTRUMENTAL = "instrumental"   # safe to score and evict
    CONSTRAINT = "constraint"       # standing prohibition / authorization
    WARRANT = "warrant"             # justifies a committed action


class PruneViolation(RuntimeError):
    """Raised when a self-editing policy attempts to evict a constitutive span."""
    pass


@dataclass
class Span:
    span_id: str
    kind: SpanKind
    text: str
    task_relevance: float = 0.0
    warrant_of: Optional[str] = None   # action_id this span justifies
    action_open: bool = False          # True until action audited/rolled back


@dataclass
class ContextPolicy:
    budget_tokens: int
    evict_threshold: float = 0.3
    pinned: set = field(default_factory=set)

    def classify_and_pin(self, span: Span) -> None:
        # Constitutive spans never enter the scorer's domain.
        if span.kind in (SpanKind.CONSTRAINT, SpanKind.WARRANT):
            self.pinned.add(span.span_id)

    def _is_protected(self, span: Span) -> bool:
        if span.span_id in self.pinned:
            return True
        if span.kind is SpanKind.CONSTRAINT:
            return True
        if span.kind is SpanKind.WARRANT and span.action_open:
            return True
        return False

    def prune(self, spans: list[Span], current_tokens: int) -> list[Span]:
        if current_tokens <= self.budget_tokens:
            return spans

        candidates = []
        for s in spans:
            if self._is_protected(s):
                # Guardrail: never let the scorer evict a warrant to
                # make room for a summary of that same warrant.
                if s.task_relevance < self.evict_threshold:
                    # Low task-relevance is EXPECTED for warrants; it is
                    # not grounds for eviction. Do not raise here — simply
                    # skip. Raising is reserved for explicit override.
                    continue
                continue
            if s.task_relevance < self.evict_threshold:
                candidates.append(s)

        if not candidates and current_tokens > self.budget_tokens:
            raise PruneViolation(
                f"Budget exceeded ({current_tokens}>{self.budget_tokens}) "
                f"but only protected spans remain; cannot satisfy budget "
                f"without violating a warrant/constraint invariant."
            )

        evicted = {s.span_id for s in candidates}
        return [s for s in spans if s.span_id not in evicted]

    def force_evict(self, span: Span) -> None:
        # Explicit override path — must be justified and logged.
        if self._is_protected(span):
            raise PruneViolation(
                f"Refusing to evict constitutive span {span.span_id} "
                f"({span.kind.value}); it is the sole warrant for "
                f"action {span.warrant_of!r}. Roll back or audit the "
                f"action before pruning its evidence."
            )
        self.pinned.discard(span.span_id)
