# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-silent-anchor-loss-boundary-in-long-horizon-agent-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-silent-anchor-loss-boundary-in-long-horizon-agent-context-compaction.warrant.json
# Markdown SHA-256:   74cd97567f832b270df0f25dd4a100044f851e65f74a6fce4c6854ab91716e77
# Code AST SHA-256:   4345ce0154216f61afb133a3ae39de14f69677f19997a3b3950f03f379f73fdb
# Verified Classes:   AnchorLossError, Anchor, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class AnchorLossError(RuntimeError):
    """Raised when compaction would destroy an invariant-bearing anchor."""


@dataclass(frozen=True)
class Anchor:
    key: str
    text: str            # verbatim form; must survive compaction
    form_dependent: bool # True => paraphrase loses meaning
    recoverable: bool    # True => re-fetchable, do not pin
    gates_irreversible: bool  # True => violation is silent/uncaught
    negated: bool = False


@dataclass
class CompactionPlan:
    pinned: list[Anchor] = field(default_factory=list)
    summarizable_tokens: int = 0
    budget_tokens: int = 0


def must_pin(anchor: Anchor) -> bool:
    # Condition of Validity: pin only when all clauses hold.
    return (
        anchor.gates_irreversible
        and not anchor.recoverable
        and (anchor.form_dependent or anchor.negated)
    )


def plan_compaction(
    anchors: Iterable[Anchor],
    summarizable_tokens: int,
    budget_tokens: int,
    prior_pinned_keys: set[str],
) -> CompactionPlan:
    pinned = [a for a in anchors if must_pin(a)]
    pinned_tokens = sum(len(a.text.split()) for a in pinned)

    # Pinned set must not shrink within a session without explicit retirement.
    current_keys = {a.key for a in pinned}
    lost = prior_pinned_keys - current_keys
    if lost:
        raise AnchorLossError(
            f"compaction would drop previously pinned anchors: {sorted(lost)}; "
            "retire explicitly or checkpoint instead of compacting"
        )

    if pinned_tokens + summarizable_tokens > budget_tokens:
        # Do not summarize harder. The session has exceeded its design horizon.
        raise AnchorLossError(
            f"pinned anchors ({pinned_tokens} tok) + minimum summary "
            f"({summarizable_tokens} tok) exceed budget ({budget_tokens} tok); "
            "checkpoint and reseed a fresh session from pinned anchors"
        )

    return CompactionPlan(
        pinned=pinned,
        summarizable_tokens=summarizable_tokens,
        budget_tokens=budget_tokens,
    )
