# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-model-initiated-context-pruning-as-an-irreversible-state-mutation-rather-than-a-reversible-optimization.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-model-initiated-context-pruning-as-an-irreversible-state-mutation-rather-than-a-reversible-optimization.warrant.json
# Markdown SHA-256:   7358be9ee4e1d99aef55ffa8ad267a0dcedd305af5d2e16a04a74d80387739b5
# Code AST SHA-256:   615e49f0b83849e98878a192f9120ac38a00c9e38f34295399d06889eed09d6b
# Verified Classes:   PruneSafety, UnsafePruneError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class PruneSafety(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"


class UnsafePruneError(RuntimeError):
    """Raised when a model-initiated prune would destroy non-recoverable evidence."""


@dataclass(frozen=True)
class Span:
    span_id: str
    source_id: str | None      # pointer into immutable store, if any
    deterministic: bool | None  # None = unknown -> treat as irreversible
    rewrite_depth: int
    tokens: int


def classify_prune(span: Span) -> PruneSafety:
    # Unknown determinism or missing provenance => irreversible mutation.
    if span.source_id is None or span.deterministic is None:
        return PruneSafety.IRREVERSIBLE
    if not span.deterministic:
        return PruneSafety.IRREVERSIBLE
    # Deterministic + pointer, but already rewritten => must re-derive, not re-summarize.
    if span.rewrite_depth >= 1:
        return PruneSafety.IRREVERSIBLE
    return PruneSafety.REVERSIBLE


def prune(span: Span, durable_store: dict[str, str]) -> str:
    safety = classify_prune(span)
    if safety is PruneSafety.IRREVERSIBLE:
        # Gate: externalize before pruning, or refuse.
        if span.span_id not in durable_store:
            raise UnsafePruneError(
                f"refusing to prune span {span.span_id!r}: "
                f"source={span.source_id!r} deterministic={span.deterministic!r} "
                f"depth={span.rewrite_depth}; externalize to durable store first"
            )
        return f"[pruned:{span.span_id} -> durable:{span.span_id}]"
    # Reversible: keep pointer, summarize as a view.
    return f"[view:{span.span_id} -> source:{span.source_id}]"


def apply_prune_batch(spans: list[Span], durable_store: dict[str, str]) -> list[str]:
    out = []
    for s in spans:
        out.append(prune(s, durable_store))
    return out
