# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-pruning-context-policies-from-deleting-the-evidence-that-justified-their-own-relevance-scores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-pruning-context-policies-from-deleting-the-evidence-that-justified-their-own-relevance-scores.warrant.json
# Markdown SHA-256:   77f0e247d67823668409821397eb12c0341c17ae8fd8445cf75eb5edfc806308
# Code AST SHA-256:   8f0cfc6a8479b5ac28c9c8825350a05f06e9db2d5a934eb830a53e301f50daf5
# Verified Classes:   PruningInvariantViolation, SegmentType, Segment, ContextPruner
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class PruningInvariantViolation(RuntimeError):
    """Raised when a self-editing context policy attempts an unsafe eviction."""
    pass


class SegmentType(Enum):
    NOISE = "noise"
    CONTENT = "content"
    CONSTRAINT = "constraint"
    PROHIBITION = "prohibition"
    NEGATIVE_RESULT = "negative_result"
    PRUNING_RATIONALE = "pruning_rationale"


PINNED_TYPES = {
    SegmentType.CONSTRAINT,
    SegmentType.PROHIBITION,
    SegmentType.NEGATIVE_RESULT,
    SegmentType.PRUNING_RATIONALE,
}


@dataclass
class Segment:
    sid: str
    text: str
    stype: SegmentType
    source_ids: tuple = ()
    tool_sig: Optional[str] = None  # (tool_name, args_hash) for negative results
    live_plan_refs: set = field(default_factory=set)


def args_hash(tool_name: str, args: dict) -> str:
    canon = tool_name + "|" + "|".join(f"{k}={args[k]}" for k in sorted(args))
    return hashlib.sha256(canon.encode()).hexdigest()[:16]


class ContextPruner:
    def __init__(self, evict_threshold: float = 0.15):
        self.evict_threshold = evict_threshold
        self.hot: dict[str, Segment] = {}
        self.cold: dict[str, Segment] = {}          # recoverable by sid
        self.neg_index: dict[str, Segment] = {}     # tool_sig -> segment

    def add(self, seg: Segment) -> None:
        self.hot[seg.sid] = seg
        if seg.stype is SegmentType.NEGATIVE_RESULT and seg.tool_sig:
            self.neg_index[seg.tool_sig] = seg

    def prune(self, scores: dict[str, float]) -> None:
        for sid, score in list(scores.items()):
            seg = self.hot.get(sid)
            if seg is None or score >= self.evict_threshold:
                continue
            if seg.live_plan_refs:
                # use-after-free guard: plan still points at it
                raise PruningInvariantViolation(
                    f"segment {sid} is referenced by live plan edges "
                    f"{sorted(seg.live_plan_refs)}; eviction forbidden until subgoal closes"
                )
            if seg.stype in PINNED_TYPES:
                # demote to cold store, never destroy; keep provenance
                self.cold[sid] = seg
                del self.hot[sid]
                continue
            # only intrinsically-irrelevant, recoverable-by-nothing content may vanish
            del self.hot[sid]

    def stage_tool_call(self, tool_name: str, args: dict) -> Optional[Segment]:
        """Before executing, re-surface any pinned negative result or matching constraint."""
        sig = args_hash(tool_name, args)
        prior = self.neg_index.get(sig)
        if prior is not None:
            self.hot[prior.sid] = prior  # re-expand into attention
            return prior
        # re-expand any cold prohibition whose text names the tool
        for sid, seg in self.cold.items():
            if seg.stype is SegmentType.PROHIBITION and tool_name in seg.text:
                self.hot[sid] = seg
                return seg
        return None

    def expand_for_scoring(self, sid: str) -> str:
        """A digest must be scored against its sources, not itself."""
        seg = self.hot.get(sid) or self.cold.get(sid)
        if seg is None:
            raise PruningInvariantViolation(f"unknown segment {sid}")
        if seg.source_ids and not any(s in self.hot or s in self.cold for s in seg.source_ids):
            raise PruningInvariantViolation(
                f"cannot score {sid}: provenance {seg.source_ids} already destroyed — "
                f"lossy rewrite with no re-expansion path is outside the valid domain"
            )
        return seg.text


def run_pruning_cycle(pruner: ContextPruner, scores: dict[str, float]) -> None:
    try:
        pruner.prune(scores)
    except PruningInvariantViolation:
        raise
    except Exception as exc:  # noqa: BLE001
        raise PruningInvariantViolation(f"pruning cycle aborted: {exc}") from exc
