# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-mid-task-boundary-loss-invariant-for-long-horizon-agent-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-mid-task-boundary-loss-invariant-for-long-horizon-agent-context-windows.warrant.json
# Markdown SHA-256:   3a1f9af25b8168ed1e5ecfc3d6a953d2dc05484e497761bb60d0ace3c076d6cf
# Code AST SHA-256:   be62f711b0194b21cdd1e06b65cad271344074e56bf8571c2a62a174c179977f
# Verified Classes:   CompactionViolation, ContentClass, EvictionUnit, CompactionPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionViolation(RuntimeError):
    """Raised when a compaction event would evict non-recoverable, load-bearing state."""
    pass


class ContentClass(Enum):
    REDUNDANT_TOOL_OUTPUT = "redundant_tool_output"   # re-fetchable
    EXPLORATORY_REASONING = "exploratory_reasoning"    # conclusions already captured
    ENUMERATED_CONSTRAINT = "enumerated_constraint"    # negative constraint, high entropy
    REJECTED_BRANCH = "rejected_branch"                # decision not in environment
    VERIFICATION_WITNESS = "verification_witness"      # needed to check final result


NON_RECOVERABLE = {
    ContentClass.ENUMERATED_CONSTRAINT,
    ContentClass.REJECTED_BRANCH,
    ContentClass.VERIFICATION_WITNESS,
}


@dataclass
class EvictionUnit:
    content_class: ContentClass
    serializable: bool
    tokens: int
    externalized: bool = False


@dataclass
class CompactionPolicy:
    budget_remaining: int
    external_store_available: bool = True

    def decide(self, units: list[EvictionUnit]) -> str:
        """Return 'compact', 'externalize_then_compact', or 'halt'."""
        for unit in units:
            if unit.content_class not in NON_RECOVERABLE:
                continue
            if unit.serializable and self.external_store_available:
                unit.externalized = True
                continue
            # Non-recoverable, non-serializable: must halt, never silently compact.
            raise CompactionViolation(
                f"Refusing to compact: eviction unit {unit.content_class.value} "
                f"is non-recoverable and load-bearing; halt and checkpoint instead."
            )
        return "compact"


def enforce_constraint_superset(before: set[str], after: set[str]) -> None:
    """Post-compaction invariant: the enforceable constraint set may not shrink."""
    lost = before - after
    if lost:
        raise CompactionViolation(
            f"Compaction reduced enforceable constraints by {sorted(lost)}; "
            f"this is a correctness bug, not a capacity optimization."
        )
