# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-relevance-score-inversion-during-self-editing-context-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-relevance-score-inversion-during-self-editing-context-eviction.warrant.json
# Markdown SHA-256:   2861227c56d76226b35a115b18bd4e15fc8b037f3af83b088859e1284f3c87db
# Code AST SHA-256:   5e70c0cdfa7bf9ea2fe00d91b44a849d091d6868660a65377ea9b8f7bd8acb10
# Verified Classes:   MisEvictionError, StaleScoreError, Segment, Tombstone, SelfEditingWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class MisEvictionError(RuntimeError):
    """Raised when a committed eviction removed a segment the live turn now depends on."""
    pass


class StaleScoreError(RuntimeError):
    """Raised when a relevance score was computed against a query proxy that has since drifted."""
    pass


@dataclass
class Segment:
    seg_id: str
    content: str
    protected: bool = False
    content_hash: str = field(default="")

    def __post_init__(self):
        if not self.content_hash:
            self.content_hash = hashlib.sha256(self.content.encode()).hexdigest()[:16]


@dataclass
class Tombstone:
    seg_id: str
    score: float
    query_proxy_hash: str
    turn: int
    content_hash: str


class SelfEditingWindow:
    def __init__(self, budget_tokens: int, stability_margin: float = 0.15):
        self.budget = budget_tokens
        self.stability_margin = stability_margin
        self.segments: dict[str, Segment] = {}
        self.tombstones: list[Tombstone] = []

    def _score(self, seg: Segment, query_proxy: str) -> float:
        # Placeholder for LLM-judge / embedding cosine against a proxy query.
        return 0.5

    def _proxy_hash(self, query_proxy: str) -> str:
        return hashlib.sha256(query_proxy.encode()).hexdigest()[:16]

    def evict(self, query_proxy: str, turn: int, threshold: float = 0.2) -> list[str]:
        live_hash = self._proxy_hash(query_proxy)
        evicted = []
        for seg in list(self.segments.values()):
            if seg.protected:
                continue
            score = self._score(seg, query_proxy)
            if score >= threshold:
                continue
            # Re-score-at-commit is implicit: we just scored against the live proxy.
            # Guard: never evict a segment whose live score is within the margin of the threshold.
            if abs(score - threshold) < self.stability_margin:
                continue
            self.tombstones.append(
                Tombstone(seg.seg_id, score, live_hash, turn, seg.content_hash)
            )
            del self.segments[seg.seg_id]
            evicted.append(seg.seg_id)
        return evicted

    def require(self, seg_id: str, live_turn: int) -> Segment:
        if seg_id in self.segments:
            return self.segments[seg_id]
        for t in self.tombstones:
            if t.seg_id == seg_id:
                raise MisEvictionError(
                    f"segment {seg_id} was evicted at turn {t.turn} "
                    f"(score={t.score:.2f}) but is required at turn {live_turn}; "
                    f"agent must distinguish amnesia from ignorance before proceeding"
                )
        raise StaleScoreError(
            f"segment {seg_id} was never present in this window; "
            f"this is ignorance, not mis-eviction — do not retry re-fetch blindly"
        )

    def verify_refetch(self, seg_id: str, fresh: Segment) -> None:
        for t in self.tombstones:
            if t.seg_id == seg_id and t.content_hash != fresh.content_hash:
                raise MisEvictionError(
                    f"re-fetched {seg_id} has changed since eviction "
                    f"({t.content_hash} -> {fresh.content_hash}); plan may be stale"
                )
