# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-relevance-scored-eviction-has-silently-inverted-its-own-retrieval-prior.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-relevance-scored-eviction-has-silently-inverted-its-own-retrieval-prior.warrant.json
# Markdown SHA-256:   ef29edaf016176aba34f4467465ff064c473303ebfaee12fba41ff95d9ed24b4
# Code AST SHA-256:   768a96bca188e0ee1b79b3190ed42c78c2c6b5bce696379f14971f3005c59310
# Verified Classes:   ContextPolicyError, ConstraintDriftError, AnchorInstabilityError, RewriteMonotonicityError, EntryTag, Entry, EvictionPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class ContextPolicyError(RuntimeError):
    """Base for self-editing context policy violations."""


class ConstraintDriftError(ContextPolicyError):
    """A pinned constraint scored low against a rolling anchor: drift, not staleness."""


class AnchorInstabilityError(ContextPolicyError):
    """Relevance eviction attempted against a non-pinned (rolling) anchor."""


class RewriteMonotonicityError(ContextPolicyError):
    """A rewrite would drop a discriminating token with no successor entry."""


class EntryTag(Enum):
    ORDINARY = "ordinary"
    CONSTRAINT = "constraint"
    CORRECTION = "correction"
    PINNED = "pinned"


DISCRIMINATING = ("usd", "eur", "1.08", "do not", "must", "fixed")


@dataclass
class Entry:
    id: str
    text: str
    tag: EntryTag
    age_turns: int = 0


@dataclass
class EvictionPolicy:
    capacity_threshold: float = 0.70
    relevance_threshold: float = 0.24
    anchor_pinned: bool = True
    constraint_register: dict = field(default_factory=dict)

    def _discriminating_tokens(self, text: str) -> set:
        low = text.lower()
        return {t for t in DISCRIMINATING if t in low}

    def rewrite(self, entry: Entry, new_text: str) -> Entry:
        dropped = self._discriminating_tokens(entry.text) - self._discriminating_tokens(new_text)
        if dropped and not self._has_successor(entry, dropped):
            raise RewriteMonotonicityError(
                f"rewrite of {entry.id} drops discriminating tokens {sorted(dropped)} "
                f"with no successor; reject compression"
            )
        return Entry(id=entry.id, text=new_text, tag=entry.tag, age_turns=entry.age_turns)

    def _has_successor(self, entry: Entry, tokens: set) -> bool:
        return any(tok in self.constraint_register.get(entry.id, "") for tok in tokens)

    def consider_eviction(self, entry: Entry, score: float, window_usage: float) -> bool:
        if window_usage < self.capacity_threshold:
            return False

        if entry.tag in (EntryTag.CONSTRAINT, EntryTag.CORRECTION, EntryTag.PINNED):
            if score < self.relevance_threshold:
                # A constraint scoring low on relevance is a drift alarm, not an eviction trigger.
                raise ConstraintDriftError(
                    f"constraint {entry.id} scored {score:.2f} < {self.relevance_threshold}; "
                    f"query has drifted from the constraint's domain — re-anchor, do not evict"
                )
            # Even when relevant, constraints are only capacity-evicted after externalization.
            self.constraint_register[entry.id] = entry.text
            return True

        if not self.anchor_pinned:
            raise AnchorInstabilityError(
                f"relevance eviction of {entry.id} attempted against rolling anchor; "
                f"downgrade to recency-only eviction"
            )

        return score < self.relevance_threshold


def run_eviction_cycle(policy: EvictionPolicy, entries: list, scores: dict, window_usage: float) -> list:
    survivors = []
    for entry in entries:
        try:
            evicted = policy.consider_eviction(entry, scores.get(entry.id, 1.0), window_usage)
        except ConstraintDriftError:
            # Re-inject from the pinned task spec rather than deleting.
            policy.constraint_register.setdefault(entry.id, entry.text)
            survivors.append(entry)
            continue
        if not evicted:
            survivors.append(entry)
    return survivors
