# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-windows-when-model-driven-pruning-evicts-the-very-evidence-its-own-eviction-policy-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-windows-when-model-driven-pruning-evicts-the-very-evidence-its-own-eviction-policy-depends-on.warrant.json
# Markdown SHA-256:   47a21ccd6659296f9d3890e7e1b44babad54dc35047ced7bb285ba85a8c21c3d
# Code AST SHA-256:   a9ecaf4f5ffae26321b2d7216b5b3ef95f33b0beebeb70797f673558b3edf0b8
# Verified Classes:   SelfEvictionViolation, Span, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SelfEvictionViolation(RuntimeError):
    """Raised when a context pruner attempts to evict its own adjudication ledger
    or re-admit content whose eviction was already adjudicated."""
    pass


@dataclass
class Span:
    span_id: str
    content: str
    score: float = 0.0

    @property
    def digest(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()[:16]


@dataclass
class ContextWindow:
    pinned: dict[str, Span] = field(default_factory=dict)      # immune to eviction
    candidate: dict[str, Span] = field(default_factory=dict)   # evictable
    adjudicated: dict[str, str] = field(default_factory=dict)  # digest -> reason

    def admit(self, span: Span) -> None:
        if span.digest in self.adjudicated:
            raise SelfEvictionViolation(
                f"re-admission of adjudicated-evicted content {span.span_id} "
                f"(digest {span.digest}): {self.adjudicated[span.digest]}"
            )
        self.candidate[span.span_id] = span

    def prune(self, threshold: float) -> list[str]:
        victims = [s for s in self.candidate.values() if s.score < threshold]
        evicted = []
        for v in victims:
            if v.span_id in self.pinned:
                raise SelfEvictionViolation(
                    f"pruner targeted pinned ledger span {v.span_id}; "
                    "ledger must be outside the eviction candidate set"
                )
            self.adjudicated[v.digest] = f"pass evicted {v.span_id} score={v.score:.3f}"
            del self.candidate[v.span_id]
            evicted.append(v.span_id)
        return evicted
