# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-summarizable-history-and-non-compactable-working-state-when-the-context-window-saturates-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-summarizable-history-and-non-compactable-working-state-when-the-context-window-saturates-mid-task.warrant.json
# Markdown SHA-256:   aaca3880f088eb8f839a16972baa01381690e55dc3e8a6b900000eecb45a4bea
# Code AST SHA-256:   dddbdcf11cfbf8343cd2e8377bc3eea3690b48c9b041e96e05f14e99c43d6163
# Verified Classes:   InvariantClass, CompactionConservationError, Ledger, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum

class InvariantClass(Enum):
    PROHIBITION = "prohibition"
    FALSIFICATION = "falsification"
    PENDING_OBLIGATION = "pending_obligation"
    BINDING = "binding"

class CompactionConservationError(RuntimeError):
    """Raised when compaction would drop non-reconstructible working state."""
    pass

@dataclass
class Ledger:
    entries: dict = field(default_factory=dict)  # InvariantClass -> list[str]
    def has(self, cls: InvariantClass) -> bool:
        return bool(self.entries.get(cls))

@dataclass
class ContextWindow:
    utilization: float
    threshold: float
    pinned_tokens: set = field(default_factory=set)

def compact(window: ContextWindow, ledger: Ledger,
            required: set) -> str:
    if window.utilization < window.threshold:
        return "no-op"

    # Conservation check: every required invariant class must be externalized
    # to the ledger AND pinned, or compaction is refused.
    missing = [c for c in required if not ledger.has(c)]
    if missing:
        raise CompactionConservationError(
            f"refusing to compact: unexternalized working state {missing}; "
            f"pin constraint turns or escalate"
        )

    unpinned = [c for c in required if c.value not in window.pinned_tokens]
    if unpinned:
        raise CompactionConservationError(
            f"invariant classes {unpinned} present in ledger but not pinned "
            f"in window; post-compaction instance cannot re-read them"
        )

    # Safe: compact only the reconstructible middle, keep head constraints pinned.
    return "compacted-middle"

def run_compaction(window: ContextWindow, ledger: Ledger) -> str:
    required = {InvariantClass.PROHIBITION,
                InvariantClass.FALSIFICATION,
                InvariantClass.PENDING_OBLIGATION,
                InvariantClass.BINDING}
    return compact(window, ledger, required)
