# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-model-driven-retention-score-as-a-pruning-decision-rather-than-a-retrieval-hint-and-what-breaks-when-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-model-driven-retention-score-as-a-pruning-decision-rather-than-a-retrieval-hint-and-what-breaks-when-it.warrant.json
# Markdown SHA-256:   6b3eaec58b41431232abc5b6f725816243cb5968d28a865924133b9f75c01b7e
# Code AST SHA-256:   488d5f0c16adac352c40641cc41c535e45fe206c2974949e33dd24364f085078
# Verified Classes:   PruningInvariantViolation, ContextItem, PrunePolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

class PruningInvariantViolation(RuntimeError):
    """Raised when a retention score is consumed as an eviction decision
    without satisfying recoverability, precondition, or calibration gates."""

@dataclass
class ContextItem:
    item_id: str
    kind: Literal["fact", "constraint", "open_precondition", "closed_artifact", "restatement"]
    retention: float          # model-emitted score in [0,1]
    durable: bool             # present in external store keyed by item_id
    pinned: bool = False      # tracked by obligation side-channel

@dataclass
class PrunePolicy:
    tau: float
    validated_saturation_band: tuple[float, float]  # (lo, hi) occupancy where tau is calibrated
    current_occupancy: float

    def admissible(self, item: ContextItem) -> bool:
        # Gate 3: calibration stability. Outside the validated band, the score
        # is a position proxy, not a relevance measure.
        lo, hi = self.validated_saturation_band
        if not (lo <= self.current_occupancy <= hi):
            return False
        if item.retention >= self.tau:
            return True
        # Gate 2: constraints and open preconditions are never evicted on score.
        if item.kind in ("constraint", "open_precondition") or item.pinned:
            return False
        # Gate 1: facts require recoverability before lossy eviction.
        if item.kind == "fact" and not item.durable:
            return False
        return True

def prune(items: list[ContextItem], policy: PrunePolicy) -> tuple[list[ContextItem], list[str]]:
    kept, tombstones = [], []
    for it in items:
        if policy.admissible(it):
            kept.append(it)
        else:
            if it.kind in ("constraint", "open_precondition") and it.retention < policy.tau:
                # A pinned item scored below tau is a calibration defect, not a
                # pruning opportunity: the pruner under-scored a live obligation.
                raise PruningInvariantViolation(
                    f"pinned {it.kind} {it.item_id!r} scored {it.retention} < tau "
                    f"{policy.tau} at occupancy {policy.current_occupancy:.2f}; "
                    f"refusing score-based eviction"
                )
            if not it.durable:
                raise PruningInvariantViolation(
                    f"evicting non-durable {it.kind} {it.item_id!r} on score alone; "
                    f"no recoverability path — would force silent reconstruction"
                )
            tombstones.append(
                f"[evicted: {it.item_id} {it.kind} — retrievable via ctx.get({it.item_id!r})]"
            )
    return kept, tombstones
