# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-self-editing-context-windows-that-silently-evict-the-very-evidence-it-needs-to-justify-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-self-editing-context-windows-that-silently-evict-the-very-evidence-it-needs-to-justify-eviction.warrant.json
# Markdown SHA-256:   5eebe3324016eb95e0ab0d511f74aa0482d44f674807e191f88d0702c6a23d67
# Code AST SHA-256:   cf1dee171f125bd98690e3a092029f3892808e1eba9a4d7a7ba88319c4802534
# Verified Classes:   JustificationEvictionInversion, Span, ContextEditor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class JustificationEvictionInversion(RuntimeError):
    """Raised when a pruning pass would evict a span whose removal makes a
    later aggregate/comparative constraint unsatisfiable, or when the
    eviction ledger itself is being scored for eviction."""
    pass


@dataclass
class Span:
    span_id: str
    tokens: int
    tags: set = field(default_factory=set)  # e.g. {"quote_set", "summary_source"}
    evicted_at: Optional[int] = None


AGGREGATE_OPERATORS = {"median", "majority", "reconcile", "diff", "consensus", "which_of"}


class ContextEditor:
    def __init__(self, spans: list[Span], task_operators: set[str]):
        self.spans = {s.span_id: s for s in spans}
        self.task_operators = task_operators & AGGREGATE_OPERATORS
        self.ledger: list[dict] = []  # non-evictable tombstones

    def prune(self, scores: dict[str, float], step: int, ledger_span_id: str = "ledger") -> list[str]:
        # Guard 1: never score the ledger for eviction.
        if ledger_span_id in scores:
            raise JustificationEvictionInversion(
                f"step {step}: ledger span '{ledger_span_id}' present in scoring domain; "
                "a scorer must not be able to prune its own audit trail"
            )

        evicted = []
        for sid, score in scores.items():
            span = self.spans.get(sid)
            if span is None or span.evicted_at is not None:
                continue
            # Guard 2: comparison-set members are non-evictable while an
            # aggregate operator is live in the task.
            if self.task_operators and "comparison_member" in span.tags:
                raise JustificationEvictionInversion(
                    f"step {step}: refusing to evict '{sid}' (score {score:.2f}) — it is a "
                    f"comparison operand for live operator(s) {sorted(self.task_operators)}; "
                    "eviction would destroy the operator's input domain"
                )
            # Guard 3: a summary cannot justify evicting its own source.
            if "summary_source" in span.tags and any(
                f"derived_from:{sid}" in other.tags
                for other in self.spans.values()
                if other.evicted_at is None
            ):
                raise JustificationEvictionInversion(
                    f"step {step}: refusing to evict '{sid}' — a resident summary is derived "
                    "from it; marginal relevance of source-given-derivative is not task relevance"
                )
            span.evicted_at = step
            self.ledger.append({"span_id": sid, "score": score, "step": step,
                                "contrast_set": sorted(scores)})
            evicted.append(sid)
        return evicted

    def readmit(self, span_id: str, step: int, reason: str) -> None:
        span = self.spans.get(span_id)
        if span is None or span.evicted_at is None:
            raise JustificationEvictionInversion(
                f"step {step}: cannot re-admit '{span_id}' — not present or not evicted"
            )
        span.evicted_at = None
        self.ledger.append({"span_id": span_id, "action": "readmit", "step": step, "reason": reason})
