# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-evict-the-wrong-token-when-a-self-editing-context-window-scores-relevance-against-its-own-mutating-summary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-evict-the-wrong-token-when-a-self-editing-context-window-scores-relevance-against-its-own-mutating-summary.warrant.json
# Markdown SHA-256:   dce312880a469be489d2229cfd7170cf3fe88fc146a4e459befacd57c16eccaa
# Code AST SHA-256:   c9a676d283a0e00038e75b8fdb2f75ecc79a22769c8ad3129b763376abc5ba70
# Verified Classes:   OrphanedEvictionError, Token, Summary
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class OrphanedEvictionError(RuntimeError):
    """Raised when a token would be evicted on the basis of a summary that
    never contained its fact, making the loss unrecoverable and invisible."""
    pass


@dataclass
class Token:
    tid: int
    text: str
    is_constraint: bool  # numeric literal, identifier, negation, explicit limit
    digest: str = ""

    def __post_init__(self):
        self.digest = hashlib.sha256(self.text.encode()).hexdigest()[:12]


@dataclass
class Summary:
    text: str
    # digests of every token whose fact the summary generation step actually saw
    covered_digests: frozenset = field(default_factory=frozenset)

    def covers(self, tok: Token) -> bool:
        return tok.digest in self.covered_digests


def select_evictions(
    window: list,
    scores: dict,
    summary: Summary,
    evict_fraction: float = 0.20,
    pinned: frozenset = frozenset(),
) -> list:
    """Return tokens to evict. Enforces the provenance invariant:
    a token may be evicted only if the summary that scored it actually
    covered it, OR it is background (non-constraint) and low-scoring.
    Constraint tokens not covered by the summary are never evictable."""
    ranked = sorted(window, key=lambda t: scores.get(t.tid, 0.0))
    n_evict = max(1, int(len(window) * evict_fraction))
    candidates = ranked[:n_evict]

    evictions = []
    for tok in candidates:
        if tok.tid in pinned:
            continue
        if tok.is_constraint and not summary.covers(tok):
            raise OrphanedEvictionError(
                f"token {tok.tid} ({tok.digest}) is a constraint that the "
                f"scoring summary never covered; evicting it would orphan "
                f"its fact. Promote it into the summary or pin it."
            )
        evictions.append(tok)
    return evictions


def compact(window, scores, summary, cold_store, **kw):
    evictions = select_evictions(window, scores, summary, **kw)
    for tok in evictions:
        cold_store.append(tok)  # reversibility: never discard outright
    kept = [t for t in window if t not in evictions]
    return kept, evictions
