# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-auto-compaction-of-its-own-context-window-before-the-salience-scorer-has-observed-a-full-task-cycle.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-auto-compaction-of-its-own-context-window-before-the-salience-scorer-has-observed-a-full-task-cycle.warrant.json
# Markdown SHA-256:   dbbd60643e9b7a35a0ae0bca8aacffed395261a53c25c4192fc4aa05de1e835b
# Code AST SHA-256:   c410e73fe67e85893b105dc962f606128fc6eb981f748b2618558f5e3a26f62e
# Verified Classes:   PrematureCompactionError, Token, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class PrematureCompactionError(RuntimeError):
    """Raised when an instance attempts to self-compact before eligibility holds."""
    pass


@dataclass
class Token:
    id: str
    birth_turn: int
    last_use_turn: Optional[int] = None
    pinned: bool = False          # constraint-grammar match; never scored
    text: str = ""


@dataclass
class ContextWindow:
    tokens: list = field(default_factory=list)
    occupancy: float = 0.0
    compaction_threshold: float = 0.60
    scorer_weights_version: int = 1

    def cycle_closed(self, tok: Token, now: int) -> bool:
        return (
            tok.last_use_turn is not None
            and tok.last_use_turn > tok.birth_turn
            and tok.last_use_turn < now
        )


def assert_compaction_eligible(
    window: ContextWindow,
    now: int,
    scorer_weights_version_at_entry: int,
    replay_anchor_present: bool,
) -> list:
    """Return the set of tokens eligible for eviction, or raise."""
    if scorer_weights_version_at_entry != window.scorer_weights_version:
        raise PrematureCompactionError(
            "scorer retuned mid-window; prior salience rankings invalid"
        )
    if not replay_anchor_present:
        raise PrematureCompactionError(
            "no cold-store replay anchor for pre-compaction transcript"
        )

    eligible = []
    for tok in window.tokens:
        if tok.pinned:
            continue  # constraints carried verbatim, never summarized
        if not window.cycle_closed(tok, now):
            # young token, still open cycle: ineligible, do not score
            continue
        eligible.append(tok)

    if window.occupancy >= window.compaction_threshold:
        # pressure demands eviction; verify the eligible set can satisfy it
        evictable_frac = len(eligible) / max(len(window.tokens), 1)
        if evictable_frac < 0.5:
            raise PrematureCompactionError(
                f"occupancy {window.occupancy:.2f} exceeds threshold but only "
                f"{evictable_frac:.2f} of tokens are cycle-closed; "
                "premature compaction would evict unobserved state"
            )
    return eligible


def maybe_compact(
    window: ContextWindow,
    now: int,
    scorer_weights_version_at_entry: int,
    replay_anchor_present: bool,
) -> list:
    eligible = assert_compaction_eligible(
        window, now, scorer_weights_version_at_entry, replay_anchor_present
    )
    # evict only eligible tokens; pinned constraints survive verbatim
    window.tokens = [t for t in window.tokens if t not in eligible]
    return eligible
