# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-context-pruning-as-an-irreversible-destructive-operation-rather-than-a-lossless-compression.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-model-driven-context-pruning-as-an-irreversible-destructive-operation-rather-than-a-lossless-compression.warrant.json
# Markdown SHA-256:   387e0170b7a9c508f88619ae8a7220bdac8701fd56dc22f781b1e0d6857ca313
# Code AST SHA-256:   7e0da12ffce655f351841684540d241b6e88508825a1b226976efac4d6431398
# Verified Classes:   IrrecoverablePruneError, Span, DurableStore, SelfEditingContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class IrrecoverablePruneError(RuntimeError):
    """Raised when a context edit destroys a span without a recoverable pointer."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    digest: str = field(init=False)

    def __post_init__(self) -> None:
        self.digest = hashlib.sha256(self.text.encode()).hexdigest()


class DurableStore:
    """Append-only external store; survives context rewrites."""

    def __init__(self) -> None:
        self._blobs: dict[str, Span] = {}

    def put(self, span: Span) -> str:
        self._blobs[span.span_id] = span
        return span.span_id

    def get(self, span_id: str) -> Optional[Span]:
        return self._blobs.get(span_id)


class SelfEditingContext:
    def __init__(self, store: DurableStore, mirror_ratio_cap: float = 0.6) -> None:
        self.store = store
        self.live: list[str] = []          # verbatim spans still in context
        self.pointers: list[str] = []      # compact pointers to evicted spans
        self.summary_chars = 0
        self.verbatim_chars = 0
        self.mirror_ratio_cap = mirror_ratio_cap

    def prune(self, span: Span, summary: str, scorer_rationale: str) -> None:
        # Guard 1: span must be persisted before eviction.
        if self.store.get(span.span_id) is None:
            stored = self.store.put(span)
            if stored != span.span_id:
                raise IrrecoverablePruneError(
                    f"store rejected span {span.span_id}; cannot evict safely"
                )
        # Guard 2: rationale must never be evicted; it is the audit trail.
        if not scorer_rationale.strip():
            raise IrrecoverablePruneError(
                f"prune of {span.span_id} has empty rationale; refusal to destroy audit trail"
            )
        # Guard 3: hall-of-mirrors ratio must stay bounded.
        projected = self.summary_chars + len(summary)
        total = projected + self.verbatim_chars
        if total and projected / total > self.mirror_ratio_cap:
            raise IrrecoverablePruneError(
                f"prune of {span.span_id} would push model-authored ratio to "
                f"{projected / total:.2f} > cap {self.mirror_ratio_cap}; "
                f"descend to underlying pointers instead of summarizing summaries"
            )
        # Commit: evict verbatim, leave recoverable pointer + summary cache.
        self.live = [s for s in self.live if s != span.span_id]
        self.pointers.append(span.span_id)
        self.summary_chars += len(summary)
        self.verbatim_chars = max(0, self.verbatim_chars - len(span.text))

    def resolve(self, span_id: str) -> Span:
        # Resume-time recovery: pointer miss is a loud failure, not a hallucination.
        span = self.store.get(span_id)
        if span is None:
            raise IrrecoverablePruneError(
                f"pointer {span_id} has no durable backing; context was destroyed, not compressed"
            )
        if span.digest != hashlib.sha256(span.text.encode()).hexdigest():
            raise IrrecoverablePruneError(f"pointer {span_id} digest mismatch; store corrupted")
        return span
