# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-context-compaction-as-a-lossy-write-ahead-log-rather-than-a-reversible-transform.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-context-compaction-as-a-lossy-write-ahead-log-rather-than-a-reversible-transform.warrant.json
# Markdown SHA-256:   62a5d172631eb87f18d6ff03ed4bfbb71fcc3b0fa140fa2a8d708a81794b126c
# Code AST SHA-256:   679c99c641783fd5d4c66e83e1bc607ea96c58f7b6b3c4e120b95b858f3a6bbb
# Verified Classes:   CompactionViolation, 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 CompactionViolation(RuntimeError):
    """Raised when an eviction would drop a span that gates a future action."""
    pass


class SpanClass(Enum):
    CONSTRAINT = "constraint"      # instructions, prohibitions, idempotency keys
    MUTATION = "mutation"          # already-applied tool effects
    NARRATIVE = "narrative"        # progress, dead ends, redundancy


@dataclass
class Span:
    span_id: str
    text: str
    span_class: SpanClass
    durable_logged: bool = False


@dataclass
class CompactionPlan:
    to_summarize: list = field(default_factory=list)
    to_evict: list = field(default_factory=list)


def plan_compaction(spans: list[Span], token_budget: int) -> CompactionPlan:
    """
    Deterministic gate: only NARRATIVE spans may be summarized or evicted.
    CONSTRAINT and MUTATION spans must be pinned verbatim and durable-logged.
    """
    plan = CompactionPlan()
    for span in spans:
        if span.span_class in (SpanClass.CONSTRAINT, SpanClass.MUTATION):
            if not span.durable_logged:
                raise CompactionViolation(
                    f"span {span.span_id} ({span.span_class.value}) is not in the "
                    f"durable log; eviction would sever the only record gating a "
                    f"future action"
                )
            # pinned: never summarized, never evicted
            continue
        plan.to_summarize.append(span)
        plan.to_evict.append(span)
    return plan


def apply_compaction(spans: list[Span], token_budget: int) -> CompactionPlan:
    plan = plan_compaction(spans, token_budget)
    # Post-condition: the set of legal next actions is unchanged by eviction.
    surviving = [s for s in spans if s not in plan.to_evict]
    if not any(s.span_class is SpanClass.CONSTRAINT for s in surviving):
        raise CompactionViolation(
            "compaction would leave context with zero pinned constraints; "
            "escalate to checkpoint-and-resume instead"
        )
    return plan
