# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-scratchpad-mid-task-the-retention-gate-amnesia-boundary-in-self-editing-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-scratchpad-mid-task-the-retention-gate-amnesia-boundary-in-self-editing-context.warrant.json
# Markdown SHA-256:   00c1a144df1d00ea00d2a8b302cd92beb9434c1da0dc441c06fd05fe04ea646d
# Code AST SHA-256:   1214fd8951b2cf9ad8e922e67ec54159bb8b77f4b77fd583ab38bec74513a550
# Verified Classes:   UnhedgedPruneError, ContextItem, SnapshotStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnhedgedPruneError(RuntimeError):
    """Raised when a self-editing context manager attempts to prune content
    whose only recovery path is non-idempotent or summary-dependent."""
    pass


@dataclass
class ContextItem:
    item_id: str
    payload: bytes
    is_constraint: bool = False          # negative constraints: never prunable
    source_is_mutable: bool = False      # live API / mutable upstream
    snapshot_handle: str | None = None   # content-addressed, immutable


@dataclass
class SnapshotStore:
    _blobs: dict[str, bytes] = field(default_factory=dict)

    def put(self, payload: bytes) -> str:
        handle = "sha256:" + hashlib.sha256(payload).hexdigest()
        self._blobs[handle] = payload
        return handle

    def get(self, handle: str) -> bytes:
        if handle not in self._blobs:
            raise UnhedgedPruneError(f"snapshot {handle} missing; recovery not guaranteed")
        return self._blobs[handle]


def prune_item(item: ContextItem, store: SnapshotStore, relevance: float) -> None:
    """Model-driven relevance gate. Relevance score is necessary but NOT
    sufficient; the recovery path governs the decision boundary."""
    if item.is_constraint:
        # Constraints have no forward reference by construction; relevance
        # scores them near zero, which is exactly why they must be pinned.
        raise UnhedgedPruneError(
            f"refusing to prune constraint {item.item_id!r}: "
            "negative constraints are unprunable regardless of relevance"
        )

    if item.source_is_mutable and item.snapshot_handle is None:
        # Pruning here would leave re-fetch-from-live-source as the only
        # recovery path, which is non-idempotent. Snapshot first.
        raise UnhedgedPruneError(
            f"refusing to prune {item.item_id!r} (relevance={relevance:.2f}): "
            "source is mutable and no immutable snapshot exists; "
            "re-fetch is non-idempotent and would corrupt downstream verification"
        )

    if item.snapshot_handle is not None:
        # Lossless, independent recovery path exists: prune is hedged.
        store.get(item.snapshot_handle)  # assert recoverability now, not later
        return

    # In-memory, immutable, no external source: safe to drop.
    return


def self_edit(items: list[ContextItem], store: SnapshotStore,
              relevance_scores: dict[str, float]) -> list[str]:
    pruned: list[str] = []
    for item in items:
        score = relevance_scores.get(item.item_id, 1.0)
        if score < 0.10:
            prune_item(item, store, score)   # may raise UnhedgedPruneError
            pruned.append(item.item_id)
    return pruned
