# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-erase-its-own-recovery-instructions-when-pruning-context-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-erase-its-own-recovery-instructions-when-pruning-context-mid-task.warrant.json
# Markdown SHA-256:   bfc58c58955c3541b8f2c8706d397529fdcfa750f169787eacfa2cbc1f0434dd
# Code AST SHA-256:   edea829ded8744a8dace958ce6e9288655e5582a1d2fca0a3b17c86004c78f5a
# Verified Classes:   Provenance, UnrecoverablePruneError, Span, ContextStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Dict, List, Optional


class Provenance(Enum):
    PAYLOAD = "payload"
    HANDOFF = "handoff"
    TOOL_CONTRACT = "tool_contract"
    SAFETY = "safety"


PINNED_PROVENANCES = {Provenance.HANDOFF, Provenance.TOOL_CONTRACT, Provenance.SAFETY}


class UnrecoverablePruneError(RuntimeError):
    """Raised when a self-edit evicts a span whose protected resource cannot be re-verified."""


@dataclass
class Span:
    span_id: str
    text: str
    provenance: Provenance
    referenced_resource: Optional[str] = None


@dataclass
class ContextStore:
    spans: Dict[str, Span] = field(default_factory=dict)
    pinned: set = field(default_factory=set)

    def ingest(self, span: Span) -> None:
        self.spans[span.span_id] = span
        if span.provenance in PINNED_PROVENANCES:
            self.pinned.add(span.span_id)

    def evict_candidates(self, relevance: Callable[[Span], float], threshold: float) -> List[str]:
        # Pinned spans are structurally excluded from ranking, not merely skipped.
        return [
            sid
            for sid, span in self.spans.items()
            if sid not in self.pinned and relevance(span) < threshold
        ]


def recovery_adequacy_check(
    store: ContextStore,
    evicted: List[str],
    resource_exists: Callable[[str], bool],
) -> None:
    evicted_set = set(evicted)
    for sid, span in store.spans.items():
        if sid in evicted_set or span.referenced_resource is None:
            continue
        # A surviving span references a resource; confirm it still exists externally.
        if not resource_exists(span.referenced_resource):
            raise UnrecoverablePruneError(
                f"surviving span {sid!r} references {span.referenced_resource!r}, "
                f"which is absent from context and unverifiable externally; "
                f"evicted spans={evicted}"
            )


def self_edit(
    store: ContextStore,
    relevance: Callable[[Span], float],
    threshold: float,
    resource_exists: Callable[[str], bool],
) -> List[str]:
    evicted = store.evict_candidates(relevance, threshold)
    recovery_adequacy_check(store, evicted, resource_exists)
    for sid in evicted:
        del store.spans[sid]
    return evicted


if __name__ == "__main__":
    store = ContextStore()
    store.ingest(Span("s1", "pg_dump --schema-only before DDL", Provenance.HANDOFF,
                      referenced_resource="snapshot://schema_v3"))
    store.ingest(Span("s2", "stale file listing ...", Provenance.PAYLOAD))

    # Goal drifted: handoff instruction scores low, but pinning must prevent eviction.
    relevance = lambda span: 0.1 if span.span_id == "s1" else 0.9
    resource_exists = lambda uri: False  # snapshot was never actually taken

    try:
        self_edit(store, relevance, threshold=0.5, resource_exists=resource_exists)
    except UnrecoverablePruneError as exc:
        # s1 is pinned so it cannot be evicted; the check fires only if a surviving
        # span points at a resource that no longer exists.
        print(f"halted: {exc}")
