# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-trajectory-whose-summarization-would-cross-an-irreversible-semantic-loss-threshold.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-trajectory-whose-summarization-would-cross-an-irreversible-semantic-loss-threshold.warrant.json
# Markdown SHA-256:   db47b69359ed65289ab4dc8cebb86cd2131924450b073c4d31571bd2368d4de9
# Code AST SHA-256:   ec39fac3ecb24c4ce05166886729717d00668d9fb3f3bc3fd97b13da0420ae3f
# Verified Classes:   CompactionRefused, SpanClass, Span, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CompactionRefused(RuntimeError):
    """Raised when an auto-compaction pass would cross the semantic-loss boundary."""
    pass


class SpanClass(Enum):
    FILLER = "filler"          # safe to drop
    COORDINATE = "coordinate"  # IDs, error strings, numbers, decision records
    UNKNOWN = "unknown"        # classifier uncertain -> treat as coordinate


@dataclass
class Span:
    span_id: str
    text: str
    classification: SpanClass
    durable_handle: Optional[str] = None  # non-None => recoverable from store


@dataclass
class CompactionPlan:
    dropped: list[str] = field(default_factory=list)
    retained_handles: list[str] = field(default_factory=list)
    refused_spans: list[str] = field(default_factory=list)


def plan_compaction(spans: list[Span], budget_tokens: int) -> CompactionPlan:
    """
    Enforce the pointer-preserving invariant:
      - FILLER may be dropped.
      - COORDINATE with a durable handle may be dropped (handle retained).
      - COORDINATE without a handle, or UNKNOWN, must NOT be dropped.
    If keeping all non-droppable spans exceeds budget, refuse and escalate.
    """
    plan = CompactionPlan()
    kept_cost = 0

    for span in spans:
        if span.classification is SpanClass.FILLER:
            plan.dropped.append(span.span_id)
            continue

        if span.classification is SpanClass.COORDINATE and span.durable_handle:
            plan.dropped.append(span.span_id)
            plan.retained_handles.append(span.durable_handle)
            continue

        # COORDINATE without handle, or UNKNOWN: must stay in context.
        if span.classification is SpanClass.UNKNOWN:
            plan.refused_spans.append(span.span_id)
        kept_cost += len(span.text.split())

    if kept_cost > budget_tokens:
        # The only way to fit is to distill a non-droppable span. Forbidden.
        raise CompactionRefused(
            f"compaction would require lossy distillation: "
            f"{kept_cost} required tokens > {budget_tokens} budget; "
            f"refused spans={plan.refused_spans}. "
            f"Escalate: widen budget, checkpoint-to-store, or spawn scoped sub-agent."
        )
    return plan


def checkpoint_hierarchy(levels: list[list[Span]]) -> list[set[str]]:
    """
    Invariant: coordinate set must be monotone non-decreasing up the hierarchy.
    A phase summary that drops a coordinate its children carried is a lossy pyramid.
    """
    coord_sets: list[set[str]] = []
    prev: set[str] = set()

    for level in levels:
        coords = {
            s.span_id for s in level
            if s.classification in (SpanClass.COORDINATE, SpanClass.UNKNOWN)
        }
        if not prev.issubset(coords):
            missing = prev - coords
            raise CompactionRefused(
                f"checkpoint hierarchy is lossy: level dropped coordinates {missing}. "
                f"Higher levels must accumulate coordinates or retain handles to them."
            )
        coord_sets.append(coords)
        prev = coords

    return coord_sets
