# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-guard-salience-score-collapse-when-a-model-prunes-its-own-context-window-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-guard-salience-score-collapse-when-a-model-prunes-its-own-context-window-mid-task.warrant.json
# Markdown SHA-256:   ad9a6789885f3414c8f350af250bd1b2459d32cf323d9f0663a9380f6e1ee9e0
# Code AST SHA-256:   fc5458d40c8ad75e60b6af97322cc564167c5d8957f0e84cfffa6c7623afbf57
# Verified Classes:   FrameEvictionViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class FrameEvictionViolation(RuntimeError):
    """Raised when a model-driven pruner selects a pinned-frame token for eviction,
    or when the frame cannot be reconstructed after a prune."""
    pass


PINNED_FRAME_KEYS = frozenset({"goal", "constraints", "active_subgoal", "tool_schema_contract"})


def apply_prune(window: dict, scores: dict, target_usage: float,
                durable_store: dict) -> dict:
    """
    window: mapping of segment_id -> {"key": str, "tokens": int, "text": str}
    scores: mapping of segment_id -> salience 0..1 from the model pruner
    target_usage: fraction of budget to fall to (e.g. 0.50)
    durable_store: segment_id -> text, the only recoverable copy
    """
    total = sum(s["tokens"] for s in window.values())
    budget = int(total / target_usage) if target_usage else total
    evict = sorted(
        (sid for sid in window if window[sid]["key"] not in PINNED_FRAME_KEYS),
        key=lambda sid: scores.get(sid, 0.0),
    )

    pruned = dict(window)
    usage = total
    for sid in evict:
        if usage <= budget * target_usage:
            break
        seg = pruned[sid]
        # Invariant 1: frame is never scoreable / never evictable.
        if seg["key"] in PINNED_FRAME_KEYS:
            raise FrameEvictionViolation(
                f"pruner attempted to evict pinned-frame segment {sid!r} "
                f"(key={seg['key']!r}); frame region must be outside the pruner's action space"
            )
        # Invariant 2: eviction must be reversible from durable state.
        if sid not in durable_store:
            raise FrameEvictionViolation(
                f"segment {sid!r} has no durable backing store; eviction would be irreversible"
            )
        usage -= seg["tokens"]
        del pruned[sid]

    # Invariant 3: post-prune frame integrity re-assertion.
    surviving = {s["key"] for s in pruned.values()}
    missing = PINNED_FRAME_KEYS - surviving
    if missing:
        raise FrameEvictionViolation(
            f"post-prune frame integrity check failed; missing {sorted(missing)}"
        )
    return pruned


def guard_salience_drift(prev_frame_scores: dict, curr_frame_scores: dict,
                         curr_content_scores: dict) -> None:
    """Detect self-referential salience: frame scores falling while content rises."""
    frame_delta = sum(curr_frame_scores.values()) - sum(prev_frame_scores.values())
    content_mean = sum(curr_content_scores.values()) / max(len(curr_content_scores), 1)
    if frame_delta < 0 and content_mean > 0.7:
        raise FrameEvictionViolation(
            "salience reference is self-referential: frame scores falling while "
            "content scores rise; re-anchor scoring to the pinned frame before pruning"
        )
