# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-the-compaction-boundary-invariant-that-silently-severs-tool-call-result-pairs-and-poisons-post-resume-exe.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-the-compaction-boundary-invariant-that-silently-severs-tool-call-result-pairs-and-poisons-post-resume-exe.warrant.json
# Markdown SHA-256:   c8c9f6ea77887b6e141bcf10750474e365eb7b59b8ce2042b9ff2f24e0d29c85
# Code AST SHA-256:   a6a2e1d670640ae76bc659964bfa5562e4920d0e3dab6a2e7fe726a077fc8c85
# Verified Classes:   FrameClosureViolation, Frame, Message
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

class FrameClosureViolation(RuntimeError):
    """Raised when a compaction cut would sever an open tool-call frame."""
    pass

@dataclass
class Frame:
    call_id: str
    has_result: bool
    mutating: bool

@dataclass
class Message:
    frames: list[Frame] = field(default_factory=list)

def select_compaction_cut(
    messages: list[Message],
    target_reduction_tokens: int,
    token_cost: list[int],
) -> Literal["compact", "defer"]:
    """Return the index of a frame-closed cut, or 'defer' if none is legal.

    A cut at index i excises messages[:i]. It is legal iff every open frame in
    messages[:i] is paired with a result inside messages[:i] or in durable state.
    """
    accumulated = 0
    best_closed_cut = None
    for i, msg in enumerate(messages):
        # A cut *before* msg i is legal only if msg i-1 left no dangling frame
        # that msg i would have resolved. Check the boundary at i.
        if i > 0 and any(not f.has_result for f in messages[i - 1].frames):
            # boundary i is NOT frame-closed; cannot cut here
            accumulated += token_cost[i]
            continue
        if accumulated >= target_reduction_tokens:
            best_closed_cut = i
            break
        accumulated += token_cost[i]

    if best_closed_cut is None:
        # No frame-closed boundary reaches the target reduction.
        # Forcing a cut would sever an open frame -> defer, never force.
        return "defer"

    # Invariant re-check on the chosen span before committing.
    for msg in messages[:best_closed_cut]:
        for f in msg.frames:
            if not f.has_result and f.mutating:
                raise FrameClosureViolation(
                    f"cut at {best_closed_cut} excises unpaired mutating call "
                    f"{f.call_id}; refusing to compact over an open frame"
                )
    return "compact"
