# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-inflicted-context-loss-when-model-driven-pruning-evicts-the-evidence-it-needs-to-justify-the-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-inflicted-context-loss-when-model-driven-pruning-evicts-the-evidence-it-needs-to-justify-the-eviction.warrant.json
# Markdown SHA-256:   756e473bf853d31a23d84853160ca1c7271da337116290b531e6e74549e61f53
# Code AST SHA-256:   b1d2066641a00fadb02197c1eafdbd05d4c46907f6cd3a28ae908fa51918cce6
# Verified Classes:   UnverifiableRewriteError, EvictionRecord, ImmutableSpanStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnverifiableRewriteError(RuntimeError):
    """Raised when a pruned/rewritten span is used as evidence but its
    source cannot be resolved in the immutable store. This is the exact
    condition under which self-pruning becomes self-falsification."""


@dataclass(frozen=True)
class EvictionRecord:
    rewrite_text: str
    source_span_hash: str          # content hash of the ORIGINAL span
    scoring_frame_version: int     # pinned task frame the score was taken against
    relevance_score: float


class ImmutableSpanStore:
    def __init__(self) -> None:
        self._spans: dict[str, str] = {}

    def put(self, raw: str) -> str:
        h = hashlib.sha256(raw.encode()).hexdigest()
        self._spans[h] = raw
        return h

    def resolve(self, h: str) -> str | None:
        return self._spans.get(h)


NON_EVICTABLE_MARKERS = ("system:", "user_constraint:", "security_policy:")


def assert_rewrite_is_evidence(
    record: EvictionRecord,
    store: ImmutableSpanStore,
    current_frame_version: int,
) -> str:
    # 1. Provenance must survive: the source span must resolve.
    source = store.resolve(record.source_span_hash)
    if source is None:
        raise UnverifiableRewriteError(
            f"rewrite {record.rewrite_text!r} claims source "
            f"{record.source_span_hash[:12]}... but span is absent from store; "
            "cannot be used as evidence"
        )

    # 2. Relevance was scored against a frame that may since have drifted.
    if record.scoring_frame_version != current_frame_version:
        raise UnverifiableRewriteError(
            f"eviction scored under frame v{record.scoring_frame_version}, "
            f"now v{current_frame_version}; relevance is stale, re-score against "
            "pinned frame before trusting the rewrite"
        )

    # 3. Non-evictable content must never have been pruned at all.
    if any(m in source for m in NON_EVICTABLE_MARKERS):
        raise UnverifiableRewriteError(
            "pruned span contains a non-evictable marker "
            f"({record.source_span_hash[:12]}...); prune was illegal"
        )

    return source


def prune_with_guard(
    raw_span: str,
    rewrite_text: str,
    score: float,
    frame_version: int,
    store: ImmutableSpanStore,
) -> EvictionRecord:
    h = store.put(raw_span)  # provenance retained BEFORE eviction
    record = EvictionRecord(rewrite_text, h, frame_version, score)
    # Fail closed: validate the record is sound before it replaces the span.
    assert_rewrite_is_evidence(record, store, frame_version)
    return record
