# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-auto-compaction-when-semantic-summarization-triggers-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-auto-compaction-when-semantic-summarization-triggers-mid-tool-call.warrant.json
# Markdown SHA-256:   2001a759f0425b1e7dd196c8d7766e7be9a40a9045ff82c5959d75d9822313b6
# Code AST SHA-256:   9b3ca5692c3b4fcb4c453e7306ec3293850a67fb197e8524601bc59be6c726ee
# Verified Classes:   IllegalCompactionPoint, Regime, Message
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Sequence


class IllegalCompactionPoint(RuntimeError):
    """Raised when a semantic compaction trigger fires at a context position
    that is not a dependency-closed, dangling-free boundary."""


class Regime(Enum):
    LEGAL = "legal"
    DEFERRABLE = "deferrable"
    NON_DEFERRABLE = "non_deferrable"


@dataclass(frozen=True)
class Message:
    index: int
    role: str                 # "assistant" | "tool" | "user"
    has_tool_call: bool = False
    is_tool_result: bool = False
    token_count: int = 0
    depends_on: tuple[int, ...] = ()   # indices this message semantically requires


def find_dangling(messages: Sequence[Message]) -> list[int]:
    """Return indices of assistant messages with an unanswered tool call."""
    answered = {m.index for m in messages if m.is_tool_result}
    return [
        m.index for m in messages
        if m.has_tool_call and (m.index + 1) not in answered
    ]


def region_is_dependency_closed(
    messages: Sequence[Message], lo: int, hi: int
) -> bool:
    """True iff no message inside [lo, hi] is depended on by a message
    outside [lo, hi], and no message inside depends on one outside."""
    inside = set(range(lo, hi + 1))
    for m in messages:
        for dep in m.depends_on:
            if (m.index in inside) != (dep in inside):
                return False
    return True


def classify_compaction_point(
    messages: Sequence[Message],
    region_lo: int,
    region_hi: int,
    current_tokens: int,
    hard_ceiling: int,
    expected_result_tokens_p99: int,
) -> Regime:
    if find_dangling(messages):
        # A call is in flight; cannot compact the live region.
        headroom = hard_ceiling - current_tokens - expected_result_tokens_p99
        return Regime.DEFERRABLE if headroom > 0 else Regime.NON_DEFERRABLE
    if not region_is_dependency_closed(messages, region_lo, region_hi):
        # Region boundary cuts a dependency edge.
        return Regime.NON_DEFERRABLE
    return Regime.LEGAL


def maybe_compact(
    messages: Sequence[Message],
    region_lo: int,
    region_hi: int,
    current_tokens: int,
    hard_ceiling: int,
    expected_result_tokens_p99: int,
) -> Regime:
    regime = classify_compaction_point(
        messages, region_lo, region_hi,
        current_tokens, hard_ceiling, expected_result_tokens_p99,
    )
    if regime is Regime.LEGAL:
        return regime
    if regime is Regime.DEFERRABLE:
        # Hold the trigger; cache its evidence; re-evaluate at next turn boundary.
        return regime
    # NON_DEFERRABLE: restricted policy only. Never summarize across a
    # dangling envelope or a cut dependency edge.
    if find_dangling(messages):
        raise IllegalCompactionPoint(
            "semantic trigger fired with an in-flight tool call and no "
            "deferral headroom; must cancel-and-replan, not summarize "
            f"(tokens={current_tokens}, ceiling={hard_ceiling}, "
            f"p99_result={expected_result_tokens_p99})"
        )
    raise IllegalCompactionPoint(
        f"region [{region_lo},{region_hi}] is not dependency-closed; "
        "summarizing would orphan a referenced value"
    )
