# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-as-a-lossy-semantic-transaction-rather-than-a-buffer-resize.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-as-a-lossy-semantic-transaction-rather-than-a-buffer-resize.warrant.json
# Markdown SHA-256:   08a7f0133b22f0daaaa1b8eb56aa0b60c256ac4bac42bf1e6e3d16764fa10044
# Code AST SHA-256:   2ad5b70aeedab460692ff5041bbd75f9581ef4370e051edaa5f1de354f53ab0d
# Verified Classes:   CompactionRefused, AgentState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionRefused(RuntimeError):
    """Raised when auto-compaction would destroy uncheckpointed live state."""
    pass


@dataclass
class AgentState:
    token_usage: int
    window_limit: int
    # Live obligation set: predicates, guards, committed IDs, negations.
    active_predicates: list[str] = field(default_factory=list)
    unresolved_guards: list[str] = field(default_factory=list)
    committed_ids: set[str] = field(default_factory=set)
    negative_constraints: list[str] = field(default_factory=list)
    # In-flight side-effect tracking.
    outstanding_tool_call: Optional[str] = None
    # External checkpoint: obligations already durably persisted.
    checkpointed: bool = False

    def obligation_set(self) -> set[str]:
        return (
            set(self.active_predicates)
            | set(self.unresolved_guards)
            | {f"committed:{i}" for i in self.committed_ids}
            | set(self.negative_constraints)
        )


def maybe_compact(state: AgentState, watermark: float = 0.90) -> bool:
    """Return True iff compaction is permitted and performed.

    Compaction is a lossy semantic transaction. It is only valid when the
    live obligation set is empty or externally checkpointed, and no tool
    call is outstanding. Otherwise we refuse rather than silently amputate.
    """
    over_watermark = state.token_usage >= int(state.window_limit * watermark)
    if not over_watermark:
        return False

    obligations = state.obligation_set()

    if state.outstanding_tool_call is not None:
        raise CompactionRefused(
            f"cannot compact mid-mutation: tool call "
            f"{state.outstanding_tool_call!r} outstanding; "
            f"in-flight status would be lost and side effect re-applied"
        )

    if obligations and not state.checkpointed:
        raise CompactionRefused(
            f"cannot compact with {len(obligations)} uncheckpointed "
            f"obligations: {sorted(obligations)}; summary would drop "
            f"predicates/guards/committed IDs and trigger misattribution"
        )

    # Safe: either no obligations, or all externally checkpointed.
    # Perform obligation-preserving transform (re-emit verbatim) or resize.
    state.token_usage = int(state.window_limit * 0.40)
    return True
