# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-salience-weighted-retention-collapse-under-self-editing-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-salience-weighted-retention-collapse-under-self-editing-context-windows.warrant.json
# Markdown SHA-256:   01af2908fcfd95115a961d947c8c27eaaa73074559af1bd3e300881a2fed2501
# Code AST SHA-256:   45cc0fa426c62451a04b5ef69d1c239fa3a77ed9dd48622182631b4667aa2957
# Verified Classes:   RetentionCollapse, Claim, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RetentionCollapse(RuntimeError):
    """Raised when a prune would evict the sole support for an open plan precondition."""
    pass


@dataclass
class Claim:
    text: str
    provenance: Optional[str] = None   # pointer to raw observation, or None if unfalsifiable
    supports_plan_step: Optional[int] = None


@dataclass
class ContextWindow:
    claims: list = field(default_factory=list)
    open_plan_steps: dict = field(default_factory=dict)   # step_id -> required claim text


def prune(window: ContextWindow, eviction_set: list, active_plan_steps: dict) -> ContextWindow:
    # Guard: refuse to evict any claim that is the sole support for an unexecuted step
    # or that lacks provenance while being used as a premise for an irreversible action.
    for claim in eviction_set:
        if claim.supports_plan_step is not None and claim.supports_plan_step in active_plan_steps:
            raise RetentionCollapse(
                f"refusing to prune {claim.text!r}: sole support for open plan step "
                f"{claim.supports_plan_step}; externalize to durable store instead"
            )
        if claim.provenance is None and claim.text.startswith("premise:"):
            raise RetentionCollapse(
                f"refusing to prune unfalsifiable premise {claim.text!r}: no provenance pointer"
            )
    remaining = [c for c in window.claims if c not in eviction_set]
    return ContextWindow(claims=remaining, open_plan_steps=window.open_plan_steps)


def self_edit(window: ContextWindow, scorer, threshold: float, active_plan_steps: dict) -> ContextWindow:
    scored = [(scorer(c), c) for c in window.claims]
    eviction_set = [c for s, c in scored if s < threshold]
    # The prune call is the boundary; it either succeeds or raises RetentionCollapse.
    return prune(window, eviction_set, active_plan_steps)
