# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-pruning-agents-from-deleting-the-evidence-that-justifies-their-own-pruning-decisions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-pruning-agents-from-deleting-the-evidence-that-justifies-their-own-pruning-decisions.warrant.json
# Markdown SHA-256:   b5adedbd44c2a27e589c6e17df135d4c1e030d4ea18d8ab474606168979fd9ef
# Code AST SHA-256:   45ff5864367de6137ca92b70a34b56b9095ee5ddadd5b6914887ebbccac0e30a
# Verified Classes:   EvidenceEvicted, Span, Context
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class EvidenceEvicted(RuntimeError):
    """Raised when a downstream step depends on a span that was pruned without a recoverable tombstone."""
    pass


@dataclass
class Span:
    text: str
    tag: str = "generic"  # "constraint" spans are non-evictable
    def digest(self) -> str:
        return hashlib.sha256(self.text.encode()).hexdigest()


@dataclass
class Context:
    active: list[Span] = field(default_factory=list)
    cold: dict[str, Span] = field(default_factory=dict)      # hash -> raw span
    tombstones: dict[str, dict] = field(default_factory=dict)  # hash -> {score, scorer, reason}

    def prune(self, span: Span, score: float, scorer: str, reason: str) -> None:
        if span.tag == "constraint":
            raise EvidenceEvicted(
                f"refusing to evict constraint span {span.digest()[:8]}: constraints are non-evictable by score"
            )
        if score >= 0.5:
            return  # keep high-relevance spans in the active window
        h = span.digest()
        self.cold[h] = span
        self.tombstones[h] = {"score": score, "scorer": scorer, "reason": reason}
        self.active = [s for s in self.active if s.digest() != h]

    def require(self, h: str) -> Span:
        if h in self.cold:
            return self.cold[h]
        raise EvidenceEvicted(
            f"span {h[:8]} was evicted with no recoverable record; cannot justify downstream decision"
        )


def self_prune_pass(ctx: Context, scores: dict[str, float], scorer: str) -> None:
    for span in list(ctx.active):
        h = span.digest()
        if h not in scores:
            raise EvidenceEvicted(f"span {h[:8]} has no score; cannot adjudicate eviction")
        ctx.prune(span, scores[h], scorer, reason="low relevance at self-prune pass")
