# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-auto-compaction-has-silently-orphaned-a-live-tool-call-dependency-before-the-next-turn-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-auto-compaction-has-silently-orphaned-a-live-tool-call-dependency-before-the-next-turn-executes.warrant.json
# Markdown SHA-256:   a90ec0fac42bbeb3d73cda935c29ed93c507be6851657bfefb898c9cc46525df
# Code AST SHA-256:   34edb761ded286aca2c230beac6131fa5b4685188f05f1686529e08ec3913639
# Verified Classes:   CompactionInvariantViolation, Msg, PendingRegister
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class CompactionInvariantViolation(RuntimeError):
    """Raised when a compaction plan would orphan a live tool-call or subgoal."""
    pass

@dataclass
class Msg:
    role: str
    kind: str                      # "text" | "tool_use" | "tool_result" | "subgoal"
    tool_use_id: str | None = None
    subgoal_id: str | None = None
    closed: bool = False           # for subgoal: postcondition verified?

@dataclass
class PendingRegister:
    tool_use_ids: set[str] = field(default_factory=set)
    subgoal_ids: set[str] = field(default_factory=set)

def open_frontier(msgs: Iterable[Msg]) -> PendingRegister:
    issued, resolved = set(), set()
    subgoals_open = set()
    for m in msgs:
        if m.kind == "tool_use" and m.tool_use_id:
            issued.add(m.tool_use_id)
        elif m.kind == "tool_result" and m.tool_use_id:
            resolved.add(m.tool_use_id)
        elif m.kind == "subgoal" and m.subgoal_id and not m.closed:
            subgoals_open.add(m.subgoal_id)
    return PendingRegister(issued - resolved, subgoals_open)

def plan_compaction(msgs: list[Msg], evict_upto: int) -> list[Msg]:
    """Return the messages safe to summarize/evict. Refuses to cross an open frontier."""
    span = msgs[:evict_upto]
    frontier = open_frontier(span)
    if frontier.tool_use_ids or frontier.subgoal_ids:
        raise CompactionInvariantViolation(
            f"evicting msgs[:{evict_upto}] would orphan "
            f"tool_use_ids={sorted(frontier.tool_use_ids)} "
            f"subgoal_ids={sorted(frontier.subgoal_ids)}; "
            f"defer or externalize to PendingRegister before compacting"
        )
    return span
