# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-the-pre-compaction-replay-divergence-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-the-pre-compaction-replay-divergence-invariant.warrant.json
# Markdown SHA-256:   432d5b32cef33e3eff84f3ea68c58f79e5e5d672621e86753c2723919bf2a38c
# Code AST SHA-256:   b12627203c35612f65c8ae55e95a258ecf4c4fea11e3f1f8d72bbf7f4eca8655
# Verified Classes:   CompactionState, UncertifiedCompactionError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class CompactionState(Enum):
    CERTIFIED_IRRELEVANT = "certified_irrelevant"
    CERTIFIED_REACHABLE = "certified_reachable"
    UNCERTIFIED = "uncertified"


class UncertifiedCompactionError(RuntimeError):
    """Raised when an agent attempts to auto-compact a span whose
    derivational reachability has not been certified. Compacting such a
    span risks replay divergence: the agent later treats the digest as a
    premise that no longer entails its own prior evidence."""


@dataclass
class Span:
    span_id: str
    token_count: int
    state: CompactionState
    reachable_obligations: int = 0
    provenance_stub_tokens: int = 0


def auto_compact(span: Span, budget_remaining: int) -> Span:
    """Compact a span only if its reachability is certified.

    Returns the compacted (or stubbed) span. Raises if the span is
    uncertified and the caller has not supplied a human checkpoint.
    """
    if span.state is CompactionState.UNCERTIFIED:
        raise UncertifiedCompactionError(
            f"span {span.span_id!r} has uncertified derivational reachability; "
            f"refusing to auto-compact. Defer, expand budget, or escalate."
        )

    if span.state is CompactionState.CERTIFIED_IRRELEVANT:
        return Span(span.span_id, token_count=8, state=span.state)

    # CERTIFIED_REACHABLE: retain facts plus provenance stub.
    compacted = span.token_count // 20 + span.provenance_stub_tokens
    if compacted > budget_remaining:
        raise UncertifiedCompactionError(
            f"span {span.span_id!r} reachable but compacted size {compacted} "
            f"exceeds remaining budget {budget_remaining}; cannot certify."
        )
    return Span(span.span_id, token_count=compacted, state=span.state)


def run_compaction_pass(spans: list[Span], budget: int) -> list[Span]:
    remaining = budget
    out = []
    for span in spans:
        result = auto_compact(span, remaining)
        remaining -= result.token_count
        out.append(result)
    return out
