# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-self-pruning-its-context-window-lose-the-very-precondition-that-justified-the-prune.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-self-pruning-its-context-window-lose-the-very-precondition-that-justified-the-prune.warrant.json
# Markdown SHA-256:   0d8296e5ff89644329ec96af6ca2022ee6b48edd11dc13ec7d1bef84c9ffad0a
# Code AST SHA-256:   b9549b6eae910199303b555f8abee894f26cdd079800e602358c7317d7033d17
# Verified Classes:   UnverifiablePruneError, Span, EvictionLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class UnverifiablePruneError(RuntimeError):
    """Raised when an eviction cannot be justified from post-eviction state."""
    pass


@dataclass
class Span:
    text: str
    score_vector: dict = field(default_factory=dict)  # objective -> score

    @property
    def span_hash(self) -> str:
        return hashlib.sha256(self.text.encode()).hexdigest()[:16]


@dataclass
class EvictionLedger:
    entries: dict = field(default_factory=dict)  # span_hash -> (tokens, score_vector, objective)

    def record(self, span: Span, objective: str, threshold: float) -> None:
        if span.span_hash in self.entries:
            return
        self.entries[span.span_hash] = {
            "tokens": span.text,
            "score_vector": dict(span.score_vector),
            "objective_at_eviction": objective,
        }

    def resurrect(self, new_objective: str, threshold: float) -> list:
        revived = []
        for h, e in self.entries.items():
            score = e["score_vector"].get(new_objective, 0.0)
            if score >= threshold:
                revived.append(Span(text=e["tokens"], score_vector=e["score_vector"]))
        return revived


def prune(transcript: list, objective: str, threshold: float,
          ledger: EvictionLedger, reversible: bool) -> list:
    kept = []
    for span in transcript:
        score = span.score_vector.get(objective, 0.0)
        if score >= threshold:
            kept.append(span)
            continue
        # Low score against current objective: evict only if we can justify it later.
        if not reversible and span.span_hash not in ledger.entries:
            raise UnverifiablePruneError(
                f"span {span.span_hash} scored {score:.2f} < {threshold} against "
                f"objective '{objective}', but eviction is irreversible and no "
                f"ledger entry exists to justify or resurrect it"
            )
        ledger.record(span, objective, threshold)
    return kept
