# 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-context-window-instead-of-summarizing-it-lossily.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-context-window-instead-of-summarizing-it-lossily.warrant.json
# Markdown SHA-256:   b8276aeda8241f57f257451ab1392f4d4629f0c11c835a9cbf9ba439688153c3
# Code AST SHA-256:   63d70e99595efce77ded01d1efd871a921fe8e699fe83de69d664636b08bb1ac
# Verified Classes:   UnsafeCompactionError, Obligation, Checkpoint, ContextState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnsafeCompactionError(RuntimeError):
    """Raised when auto-compaction is attempted while the safety predicate fails."""
    pass


@dataclass
class Obligation:
    tool_call_id: str
    args_hash: str
    resolved: bool = False


@dataclass
class Checkpoint:
    evicted_spans: dict = field(default_factory=dict)   # handle -> original bytes
    reconstructs_evicted: bool = False

    def reconstructs(self, handle: str, original: bytes) -> bool:
        return self.evicted_spans.get(handle) == original


@dataclass
class ContextState:
    token_budget: int
    tokens_used: int
    obligations: list = field(default_factory=list)
    externalized: dict = field(default_factory=dict)   # value -> durable handle
    replay_values: dict = field(default_factory=dict)  # name -> bytes needed later
    checkpoint: Optional[Checkpoint] = None

    @property
    def live_obligations(self):
        return [o for o in self.obligations if not o.resolved]

    @property
    def pressure(self) -> float:
        return self.tokens_used / self.token_budget

    def all_replay_externalized(self) -> bool:
        return all(name in self.externalized for name in self.replay_values)


def compact_allowed(state: ContextState) -> bool:
    if state.live_obligations:
        return False
    if not state.all_replay_externalized():
        return False
    if state.checkpoint is None or not state.checkpoint.reconstructs_evicted:
        return False
    return True


def maybe_auto_compact(state: ContextState, soft_threshold: float = 0.75) -> str:
    if state.pressure < soft_threshold:
        return "no_action"

    # Externalize replay-critical values BEFORE any summarization.
    for name, raw in state.replay_values.items():
        if name not in state.externalized:
            state.externalized[name] = f"handle://{name}"

    if not compact_allowed(state):
        unmet = []
        if state.live_obligations:
            unmet.append(f"{len(state.live_obligations)} live obligation(s)")
        if not state.all_replay_externalized():
            unmet.append("replay values not externalized")
        if state.checkpoint is None or not state.checkpoint.reconstructs_evicted:
            unmet.append("checkpoint fails reconstruction test")
        raise UnsafeCompactionError(
            "refusing lossy auto-compaction; budget exhausted with unmet safety "
            "conditions: " + "; ".join(unmet)
        )

    return "compacted_safely"


def resume_from_checkpoint(state: ContextState, handle: str, original: bytes) -> None:
    cp = state.checkpoint
    if cp is None or not cp.reconstructs(handle, original):
        raise UnsafeCompactionError(
            f"checkpoint cannot reconstruct span {handle!r}; resume would resume "
            "from a lossy summary, not real state"
        )
    # proceed with verified reconstruction only
