# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-ordering-when-auto-compaction-rewrites-a-tool-call-transcript-across-a-token-ceiling.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-ordering-when-auto-compaction-rewrites-a-tool-call-transcript-across-a-token-ceiling.warrant.json
# Markdown SHA-256:   43e514497febeb54504e139f23f43e263109af010b214bc87c5fb8e65c60c4fa
# Code AST SHA-256:   39c8fdc30e31bdd36869c9631963b636cff8d70db7834cb2ab23f32d8b17856e
# Verified Classes:   CompactionClosureError, ToolCall, Turn
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionClosureError(RuntimeError):
    """Raised when a compaction plan would break referential closure of the transcript."""


@dataclass
class ToolCall:
    call_id: str
    entity: Optional[str] = None          # file path, resource id, etc.
    result_present: bool = False
    result_hash: Optional[str] = None


@dataclass
class Turn:
    index: int
    calls: list[ToolCall] = field(default_factory=list)
    references: list[str] = field(default_factory=list)   # ids/hashes/paths cited in prose
    mutating: bool = False


def plan_compaction(turns: list[Turn], evict: range) -> list[Turn]:
    """
    Return the surviving transcript after evicting `evict`, or raise if the
    eviction would split a call/result pair or orphan a referenced entity.
    """
    evicted = {t.index for t in evict}
    surviving = [t for t in turns if t.index not in evicted]

    # 1. Split-pair check: no call may survive without its result, and no
    #    result may survive without its call, across the eviction boundary.
    live_calls: dict[str, ToolCall] = {}
    for t in surviving:
        for c in t.calls:
            live_calls[c.call_id] = c
    for t in turns:
        if t.index not in evicted:
            continue
        for c in t.calls:
            if c.call_id in live_calls and not live_calls[c.call_id].result_present:
                raise CompactionClosureError(
                    f"eviction splits call/result pair for call_id={c.call_id!r}: "
                    f"call survives, result evicted"
                )

    # 2. Referential closure: every entity cited by a surviving turn must
    #    resolve to a surviving observation (or a rehydration stub).
    surviving_entities = {
        c.entity for t in surviving for c in t.calls
        if c.result_present and c.entity
    }
    for t in surviving:
        for ref in t.references:
            if ref not in surviving_entities:
                raise CompactionClosureError(
                    f"turn {t.index} references {ref!r} which is not live "
                    f"post-compaction; emit rehydration stub or block mutating call"
                )

    # 3. Mutating actions in the tail must not depend on evicted observations.
    for t in surviving:
        if t.mutating:
            for c in t.calls:
                if c.entity and c.entity not in surviving_entities:
                    raise CompactionClosureError(
                        f"mutating call in turn {t.index} touches {c.entity!r} "
                        f"with no live observation; force re-read before commit"
                    )
    return surviving


def guarded_compact(turns: list[Turn], evict: range) -> list[Turn]:
    try:
        return plan_compaction(turns, evict)
    except CompactionClosureError:
        # Fall back to the largest causally-closed prefix of the eviction set,
        # never a partial split.
        raise CompactionClosureError(
            "compaction refused: boundary not causally closed; "
            "shrink eviction window or insert rehydration stubs"
        )
