# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-context-compaction-before-summarization-destroys-the-evidence-needed-to-resume-a-task.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-context-compaction-before-summarization-destroys-the-evidence-needed-to-resume-a-task.warrant.json
# Markdown SHA-256:   1ce6f3962f6b5d3aa3d5f9020469bc3be352d28f5ebed1a41499d72ac182d617
# Code AST SHA-256:   d8ec5665fa462537f257164d99b9db33a2a101e4b7e4927f8d4a6f32ae49404a
# Verified Classes:   CompactionFidelityError, ToolCall, CompactionRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionFidelityError(RuntimeError):
    """Raised when compaction would evict evidence at or after the side-effect frontier
    without a durable, verbatim decision ledger to survive the summary."""
    pass


@dataclass
class ToolCall:
    index: int
    tool: str
    args_digest: str
    returned_ids: dict          # verbatim identifiers, never paraphrased
    irreversible: bool
    failed_then_retried: bool = False
    retry_count: int = 0


@dataclass
class CompactionRequest:
    transcript_len: int
    evict_from: int             # first message index the summarizer would drop
    calls: list
    durable_ledger_present: bool = False
    summary_ledger: Optional[list] = field(default=None)


def side_effect_frontier(calls: list) -> int:
    frontier = -1
    for c in calls:
        if c.irreversible:
            frontier = max(frontier, c.index)
    return frontier


def guard_compaction(req: CompactionRequest) -> None:
    frontier = side_effect_frontier(req.calls)

    # If the eviction window reaches the frontier, a lossy summary would destroy
    # the only record of an irreversible action and its dependent verification.
    evicts_frontier = frontier >= 0 and req.evict_from <= frontier

    if not evicts_frontier:
        return  # safe: only pre-frontier prose is being compressed

    if not req.durable_ledger_present:
        raise CompactionFidelityError(
            f"Compaction at evict_from={req.evict_from} crosses side-effect "
            f"frontier={frontier} with no durable ledger; refusing to summarize "
            f"irreversible evidence into prose."
        )

    # With a durable ledger, the summary must still carry every post-frontier
    # atom verbatim, including retry counts and ordering.
    required = {
        (c.index, c.tool, c.args_digest, tuple(sorted(c.returned_ids.items())),
         c.retry_count)
        for c in req.calls
        if c.irreversible and c.index >= req.evict_from
    }
    emitted = set()
    for entry in (req.summary_ledger or []):
        emitted.add((
            entry["index"], entry["tool"], entry["args_digest"],
            tuple(sorted(entry["returned_ids"].items())), entry.get("retry_count", 0),
        ))

    missing = required - emitted
    if missing:
        raise CompactionFidelityError(
            f"Summary dropped {len(missing)} post-frontier decision atom(s), "
            f"e.g. {sorted(missing)[0][:3]}; resume would reconstruct wrong state."
        )


def compact(req: CompactionRequest) -> str:
    guard_compaction(req)
    return f"<summary len={req.transcript_len - req.evict_from} tokens, ledger_verified>"
