# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-pruning-as-a-destructive-write-rather-than-a-read-optimization.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-pruning-as-a-destructive-write-rather-than-a-read-optimization.warrant.json
# Markdown SHA-256:   f0a08ee9a6a41cfec935a090bb53e0d10987638edfa740d4213b6721f11141e9
# Code AST SHA-256:   763aed0f43ff464e839d4933e0c610014136ac6b8fd6a154fa6d5216faf444f6
# Verified Classes:   PruneViolation, SpanKind, Span, ContextWindow
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class PruneViolation(RuntimeError):
    """Raised when a compaction would destroy a non-recoverable binding constraint."""
    pass


class SpanKind(Enum):
    CONTENT = "content"        # observations, tool output, traces — prunable
    CONSTRAINT = "constraint"  # prohibitions, schemas, numeric bounds — pinned


@dataclass
class Span:
    kind: SpanKind
    text: str
    source_ref: Optional[str] = None   # recoverable location, if any
    paraphrased_from: Optional[str] = None


@dataclass
class ContextWindow:
    pinned: list[Span] = field(default_factory=list)
    prunable: list[Span] = field(default_factory=list)
    eviction_log: list[dict] = field(default_factory=list)


def compact(window: ContextWindow, salience_score, threshold: float) -> ContextWindow:
    survivors: list[Span] = []
    for span in window.prunable:
        if salience_score(span) >= threshold:
            survivors.append(span)
            continue

        # A constraint is never in the prunable set by construction, but defend
        # against misclassification: if a binding span slipped in, refuse.
        if span.kind is SpanKind.CONSTRAINT:
            raise PruneViolation(
                f"binding constraint reached prune path: {span.text!r}"
            )

        # A paraphrase of an evicted source is now a primary, unverified claim.
        if span.paraphrased_from is not None and span.source_ref is None:
            raise PruneViolation(
                f"cannot evict paraphrase {span.text!r}: source "
                f"{span.paraphrased_from!r} already unrecoverable"
            )

        # Content is evictable only if recoverable post-prune.
        if span.source_ref is None:
            raise PruneViolation(
                f"non-recoverable content eviction: {span.text!r}"
            )

        window.eviction_log.append(
            {"evicted": span.text, "recoverable_at": span.source_ref}
        )

    window.prunable = survivors
    return window


def rederive(window: ContextWindow, fact: str) -> str:
    """Re-derive a fact from pinned region or recoverable source; never from a
    summary of a summary."""
    for span in window.pinned:
        if fact in span.text:
            return span.text
    raise PruneViolation(f"fact {fact!r} no longer derivable after compaction")
