# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-and-deletes-the-evidence-that-justified-the-prune.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-window-and-deletes-the-evidence-that-justified-the-prune.warrant.json
# Markdown SHA-256:   fbd5c38c61a331007f9b8b20f0791ec4786d2e63811c0d3eaf51c675aa21d587
# Code AST SHA-256:   2bf5f2096d8854a7514003fbed64b7705dbb24f47eaffe1175676669b046eabd
# Verified Classes:   PruneProvenanceError, EvictionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class PruneProvenanceError(RuntimeError):
    """Raised when a prune decision cannot be externally reconstructed."""
    pass


@dataclass
class EvictionLedger:
    """Append-only, outside the mutable window. The model may not write here."""
    _records: dict = field(default_factory=dict)

    def record(self, span_id: str, reason: str, evidence_hash: str, generation: int) -> None:
        # Append-only: never overwrite, never delete.
        if span_id in self._records:
            raise PruneProvenanceError(
                f"span {span_id} already evicted at gen "
                f"{self._records[span_id]['generation']}; re-eviction is a provenance bug"
            )
        self._records[span_id] = {
            "reason": reason,
            "evidence_hash": evidence_hash,
            "generation": generation,
        }

    def status(self, span_id: str) -> Optional[str]:
        rec = self._records.get(span_id)
        return "known_evicted" if rec else "never_seen"


def prune_span(
    span_id: str,
    span_text: str,
    reason: str,
    generation: int,
    ledger: EvictionLedger,
    in_window_log_writable: bool,
) -> None:
    """
    Drop a span from the mutable window. Enforces the invariant that the
    rationale survives outside the region being edited.
    """
    if in_window_log_writable:
        # The prune log lives in the same buffer the next prune can score.
        raise PruneProvenanceError(
            f"refusing to prune {span_id}: rationale would be stored in the "
            f"mutable window and is reachable by the next prune pass"
        )

    evidence_hash = hashlib.sha256(span_text.encode()).hexdigest()
    ledger.record(span_id, reason, evidence_hash, generation)


def assert_reconstructable(span_id: str, ledger: EvictionLedger) -> None:
    """Before any negative claim, verify absence is known, not assumed."""
    status = ledger.status(span_id)
    if status == "never_seen":
        # The instance believes this never existed. It may be wrong.
        raise PruneProvenanceError(
            f"span {span_id} is absent from window AND ledger; cannot "
            f"distinguish never-seen from silently-forgotten. Block negative claim."
        )
    # status == "known_evicted": safe to reason about the absence.
