# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-its-transcript-and-the-fidelity-guarantee-is-anchored-to-a-stale-token-count-watermark.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-its-transcript-and-the-fidelity-guarantee-is-anchored-to-a-stale-token-count-watermark.warrant.json
# Markdown SHA-256:   39b056fcda48f5eae92c5690178ea1007cc4930c2087e652924614c4ead74964
# Code AST SHA-256:   283822e4c7f82c277b9b7f7cf6bd3cb77f352a1b7037d7e74e390f44c77b9c17
# Verified Classes:   CompactionFidelityError, Transcript, CompactionPlan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction commit would leave a gap in the transcript."""


@dataclass
class Transcript:
    version: int = 0
    messages: Dict[str, str] = field(default_factory=dict)  # id -> content
    order: List[str] = field(default_factory=list)

    def append(self, msg_id: str, content: str) -> None:
        if msg_id in self.messages:
            raise CompactionFidelityError(f"duplicate message id {msg_id}")
        self.messages[msg_id] = content
        self.order.append(msg_id)
        self.version += 1  # every append bumps the fence

    def ids(self) -> Set[str]:
        return set(self.order)


@dataclass
class CompactionPlan:
    sampled_version: int
    evict_ids: Set[str]
    retain_ids: Set[str]
    summary: str


def plan_compaction(tx: Transcript, keep_tail: int) -> CompactionPlan:
    v0 = tx.version
    ids = tx.order
    cut = max(0, len(ids) - keep_tail)
    evict = set(ids[:cut])
    retain = set(ids[cut:])
    summary = f"<summary of {len(evict)} messages>"
    return CompactionPlan(sampled_version=v0, evict_ids=evict,
                          retain_ids=retain, summary=summary)


def commit_compaction(tx: Transcript, plan: CompactionPlan) -> None:
    # Fence: refuse to commit a plan computed against a stale version.
    if tx.version != plan.sampled_version:
        raise CompactionFidelityError(
            f"stale plan: sampled v{plan.sampled_version}, "
            f"transcript at v{tx.version}; re-plan required"
        )
    # Gap assertion: evicted ∪ retained must cover the whole transcript.
    covered = plan.evict_ids | plan.retain_ids
    if covered != tx.ids():
        raise CompactionFidelityError(
            f"gap in compaction: {tx.ids() - covered} would be dropped"
        )
    # Apply: replace evicted range with summary, keep retained verbatim.
    new_order = ["__summary__"] + [i for i in tx.order if i in plan.retain_ids]
    new_messages = {"__summary__": plan.summary}
    new_messages.update({i: tx.messages[i] for i in plan.retain_ids})
    tx.messages = new_messages
    tx.order = new_order
    tx.version += 1


def run_compaction(tx: Transcript, keep_tail: int) -> None:
    plan = plan_compaction(tx, keep_tail)
    # Simulate a tool result resolving mid-compaction (the race).
    tx.append("tool_result_42", "assertion failed at line 87")
    try:
        commit_compaction(tx, plan)
    except CompactionFidelityError:
        # Recoverable: re-sample and re-plan over the grown transcript.
        plan = plan_compaction(tx, keep_tail)
        commit_compaction(tx, plan)
