# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-self-pruning-of-its-own-context-as-irreversible-loss-rather-than-compression-and-refuse-to-rewri.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-self-pruning-of-its-own-context-as-irreversible-loss-rather-than-compression-and-refuse-to-rewri.warrant.json
# Markdown SHA-256:   7df8aa4a152189d819af689ab6142a6f9881404b0fe5aaba6bb00e38b4b2d90d
# Code AST SHA-256:   024ee5baf24298aed1efc864fb135d9513571a7cfb9b41150c8b64ca3357d864
# Verified Classes:   UnrecoverablePruningError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class UnrecoverablePruningError(RuntimeError):
    """Raised when a self-edit would drop the only copy of a non-recoverable fact."""
    pass


@dataclass
class Span:
    content: str
    kind: str  # "derivation" | "observation" | "constraint" | "redundant"
    recovery: Optional[Callable[[], str]] = None  # None => not re-queryable


def span_hash(span: Span) -> str:
    return hashlib.sha256(span.content.encode()).hexdigest()[:16]


def safe_prune(window: list[Span], checkpoint: dict[str, str]) -> list[Span]:
    """
    Drop low-relevance spans ONLY if each is re-derivable, re-queryable,
    or already checkpointed. Otherwise emit a tombstone and persist first.
    """
    survivors: list[Span] = []
    for span in window:
        if span.kind in ("redundant", "derivation"):
            continue  # safe to drop: re-derivable by construction
        if span.kind == "observation" and span.recovery is not None:
            continue  # safe to drop: re-queryable on demand
        # constraint, or observation with no recovery path => must persist
        key = span_hash(span)
        if key not in checkpoint:
            if span.recovery is None and span.kind == "constraint":
                # cannot even re-fetch: checkpoint is the ONLY recovery
                checkpoint[key] = span.content
            elif span.recovery is not None:
                checkpoint[key] = span.recovery()
            else:
                raise UnrecoverablePruningError(
                    f"span {key} ({span.kind}) has no recovery path and no "
                    f"checkpoint; refusing destructive rewrite"
                )
        survivors.append(Span(
            content=f"[tombstone {key} kind={span.kind}]",
            kind="tombstone",
        ))
    return survivors
