# 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-deletes-the-eviction-witness.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-windows-when-model-driven-pruning-deletes-the-eviction-witness.warrant.json
# Markdown SHA-256:   60fb5b4ea58c8b0a2f6806e7bf4d9872a0112a99cc3b635b174090863424f142
# Code AST SHA-256:   83fa422c346fbb6c7943417df7ca6a9aa88956308d60c1e3274ff42aec5b44c6
# Verified Classes:   EvictionReason, ReAdmissionViolation, ExclusionLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class EvictionReason(Enum):
    LOW_RELEVANCE = "low_relevance"
    SUPERSEDED = "superseded"
    RETRACTED = "retracted"
    UNTRUSTED = "untrusted"
    CONTRADICTED = "contradicted"


EPISTEMIC = {
    EvictionReason.SUPERSEDED,
    EvictionReason.RETRACTED,
    EvictionReason.UNTRUSTED,
    EvictionReason.CONTRADICTED,
}


class ReAdmissionViolation(RuntimeError):
    """Raised when a segment excluded for epistemic reasons is re-admitted."""


@dataclass
class ExclusionLedger:
    entries: dict = field(default_factory=dict)
    cap: int = 64

    @staticmethod
    def _hash(content: str) -> str:
        return hashlib.sha256(content.strip().encode()).hexdigest()[:16]

    def record(self, content: str, reason: EvictionReason, step: int) -> None:
        h = self._hash(content)
        self.entries[h] = {"reason": reason, "step": step}
        if len(self.entries) > self.cap:
            oldest = min(self.entries, key=lambda k: self.entries[k]["step"])
            del self.entries[oldest]

    def check_readmission(self, content: str, current_step: int) -> None:
        h = self._hash(content)
        entry = self.entries.get(h)
        if entry is None:
            return
        if entry["reason"] in EPISTEMIC:
            raise ReAdmissionViolation(
                f"segment {h} excluded at step {entry['step']} as "
                f"{entry['reason'].value}; re-admission blocked at step "
                f"{current_step}. Treat as known-stale, do not re-derive."
            )
        # LOW_RELEVANCE: re-admissible, but log the oscillation.
        return


def prune_and_guard(ledger: ExclusionLedger, segment: str,
                    score: float, step: int, threshold: float = 0.4) -> None:
    if score >= threshold:
        return
    # Fail closed: ambiguous scores default to epistemic exclusion.
    reason = EvictionReason.LOW_RELEVANCE if score < threshold * 0.6 \
        else EvictionReason.SUPERSEDED
    ledger.record(segment, reason, step)


def safe_fetch(ledger: ExclusionLedger, source: str,
               fetched: str, step: int) -> str:
    ledger.check_readmission(fetched, step)
    return fetched
