# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-pressure-compaction-from-silently-severing-the-tool-call-result-pairing-in-an-agent-s-episodic-window.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-pressure-compaction-from-silently-severing-the-tool-call-result-pairing-in-an-agent-s-episodic-window.warrant.json
# Markdown SHA-256:   7d6ef221f1893e7871e25bfb4d52daa8712de298d86e65f721bb28b4555542c8
# Code AST SHA-256:   3fdce5e6a8138276b27847b5811a064e9625f4f8e11521f6ca3ae89281948af3
# Verified Classes:   CompactionPairViolation, Msg
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

SpanId = str
CallId = str


class CompactionPairViolation(RuntimeError):
    """Raised when a compaction plan would sever a tool_call/tool_result pair."""


@dataclass
class Msg:
    role: Literal["system", "user", "assistant", "tool", "tool_stub"]
    call_id: CallId | None = None
    tokens: int = 0
    retrievable: bool = False


def plan_eviction(window: list[Msg], target_tokens: int) -> list[int]:
    """Return indices to evict. Greedy oldest-first, but pair-closed."""
    evict: set[int] = set()
    live = sum(m.tokens for m in window)
    for i, m in enumerate(window):
        if live <= target_tokens:
            break
        if m.role in ("system", "user"):
            continue  # never evict anchors
        evict.add(i)
        live -= m.tokens
    # Pair-closure: expand the set to whole call/result pairs.
    by_call: dict[CallId, list[int]] = {}
    for i, m in enumerate(window):
        if m.call_id is not None:
            by_call.setdefault(m.call_id, []).append(i)
    for call_id, idxs in by_call.items():
        touched = [i for i in idxs if i in evict]
        if touched and len(touched) != len(idxs):
            # half-evicted pair: grow to include all, or shrink to none.
            evict.update(idxs)
    # Verify closure before returning.
    for call_id, idxs in by_call.items():
        present = [i for i in idxs if i not in evict]
        if present and len(present) != len(idxs):
            raise CompactionPairViolation(
                f"call_id={call_id} would be half-evicted: "
                f"present={present} of {idxs}"
            )
    return sorted(evict)


def apply_compaction(window: list[Msg], target_tokens: int) -> list[Msg]:
    evict = set(plan_eviction(window, target_tokens))
    out: list[Msg] = []
    i = 0
    while i < len(window):
        if i not in evict:
            out.append(window[i])
            i += 1
            continue
        # Collapse the whole contiguous evicted pair into one typed stub.
        call_id = window[i].call_id
        if call_id is None:
            raise CompactionPairViolation(
                f"evicted non-pair message at index {i} lacks call_id"
            )
        stub = Msg(role="tool_stub", call_id=call_id, tokens=8, retrievable=True)
        out.append(stub)
        while i < len(window) and i in evict and window[i].call_id == call_id:
            i += 1
    # Post-condition: no orphans in the assembled window.
    calls = {m.call_id for m in out if m.role == "assistant" and m.call_id}
    results = {m.call_id for m in out if m.role in ("tool", "tool_stub") and m.call_id}
    if calls != results:
        raise CompactionPairViolation(
            f"orphan set after compaction: calls_only={calls - results}, "
            f"results_only={results - calls}"
        )
    return out
