# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-evict-the-wrong-scratchpad-page-when-a-hierarchical-working-set-crosses-a-summarization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-evict-the-wrong-scratchpad-page-when-a-hierarchical-working-set-crosses-a-summarization-boundary.warrant.json
# Markdown SHA-256:   4f5fb79475f9b50f1789a0e090761ed8edd667a8a8ab313e62a371215ec20921
# Code AST SHA-256:   6e76dadd503560a131f1fd08b1f8af904fd0df22e32289a9fd5e31edbd882acb
# Verified Classes:   ReferenceInversionError, ScratchpadPage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set


class ReferenceInversionError(RuntimeError):
    """Raised when eviction would drop a summary before its sources, or when
    a re-summarization diverges from the digest it replaces."""
    pass


@dataclass
class ScratchpadPage:
    page_id: str
    tier: int                      # 0 = verbatim, 1 = task summary, 2 = episode digest
    content_score: float           # staleness/recency score from surface features
    anchors: Set[str] = field(default_factory=set)   # entities, tool IDs, error codes
    summarizes: Set[str] = field(default_factory=set)  # provenance: child page IDs


def effective_score(page: ScratchpadPage, pages: Dict[str, ScratchpadPage],
                    _memo: Dict[str, float] = None) -> float:
    if _memo is None:
        _memo = {}
    if page.page_id in _memo:
        return _memo[page.page_id]
    score = page.content_score
    for child_id in page.summarizes:
        child = pages.get(child_id)
        if child is None:
            continue
        score = max(score, effective_score(child, pages, _memo))
    _memo[page.page_id] = score
    return score


def plan_eviction(pages: Dict[str, ScratchpadPage], budget: int,
                  current_tokens: int) -> List[str]:
    """Return eviction order, ascending effective score, respecting provenance:
    a parent is never evicted before any child it summarizes."""
    if current_tokens <= budget:
        return []
    memo: Dict[str, float] = {}
    ranked = sorted(pages.values(),
                    key=lambda p: effective_score(p, pages, memo))
    order: List[str] = []
    evicted: Set[str] = set()
    for page in ranked:
        # invariant: all children of this page must already be evicted
        if not page.summarizes.issubset(evicted):
            raise ReferenceInversionError(
                f"page {page.page_id} (tier {page.tier}) would be evicted "
                f"before its sources {page.summarizes - evicted}; "
                f"effective_score={effective_score(page, pages, memo):.3f}"
            )
        order.append(page.page_id)
        evicted.add(page.page_id)
    return order


def check_resummarization(old: ScratchpadPage, new: ScratchpadPage) -> None:
    """Quarantine a re-summarization whose anchors diverge from the original."""
    if not old.anchors:
        raise ReferenceInversionError(
            f"digest {old.page_id} has no anchors; cannot verify re-summarization"
        )
    overlap = old.anchors & new.anchors
    if not overlap:
        raise ReferenceInversionError(
            f"re-summarization of {old.page_id} -> {new.page_id} has disjoint "
            f"anchors (old={sorted(old.anchors)}, new={sorted(new.anchors)}); "
            f"task frame drifted, escalate before acting"
        )
