# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-transcript-auto-compaction-preserve-replay-divergence-as-a-first-class-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-transcript-auto-compaction-preserve-replay-divergence-as-a-first-class-invariant.warrant.json
# Markdown SHA-256:   852a93f5743f1684012d05f7f5714de429144ed462588a83d3017686da4870ff
# Code AST SHA-256:   ebd360bbfb90767ea88271ed885506536dedae9a452b05bf01478b22c7e89f7c
# Verified Classes:   ReplayDivergenceError, Span, CompactedSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Iterable


class ReplayDivergenceError(RuntimeError):
    """Raised when a compacted span cannot be proven replay-equivalent
    to the span it replaced, and the region was not marked divergent."""


@dataclass(frozen=True)
class Span:
    turns: tuple[str, ...]
    tool_invocations: int = 0
    branched_on_error: bool = False

    def sha256(self) -> str:
        h = hashlib.sha256()
        for t in self.turns:
            h.update(t.encode("utf-8"))
        return h.hexdigest()


@dataclass(frozen=True)
class CompactedSpan:
    summary: str
    source_hash: str
    divergence_expected: bool = False
    nested: bool = False
    residual_turns: tuple[str, ...] = field(default_factory=tuple)


def decide_compaction(span: Span) -> CompactedSpan:
    """Apply the decision boundary. Returns a span that is either
    provably replay-safe or explicitly marked divergent."""
    source_hash = span.sha256()

    # Boundary: any branched-on tool invocation is load-bearing. Preserve
    # the invocation turns verbatim; never paraphrase them.
    if span.branched_on_error:
        return CompactedSpan(
            summary="<prose-summarized>",
            source_hash=source_hash,
            divergence_expected=False,
            residual_turns=span.turns,  # verbatim, not summarized
        )

    # Boundary: nested compaction has unbounded divergence.
    if span.tool_invocations > 0:
        return CompactedSpan(
            summary="<prose-summarized>",
            source_hash=source_hash,
            divergence_expected=True,
        )

    # Safe: no tool calls, no branches. Lossless hash summary is replay-safe.
    return CompactedSpan(
        summary=f"<hash:{source_hash[:16]}>",
        source_hash=source_hash,
        divergence_expected=False,
    )


def replay(spans: Iterable[CompactedSpan], require_equivalence: bool = True) -> None:
    for cs in spans:
        if require_equivalence and cs.divergence_expected:
            raise ReplayDivergenceError(
                f"span {cs.source_hash[:16]} was compacted with expected "
                f"divergence; cannot claim replay equivalence. Re-run with "
                f"require_equivalence=False to accept approximate replay."
            )
        if cs.nested:
            raise ReplayDivergenceError(
                f"span {cs.source_hash[:16]} is a summary of a summary; "
                f"divergence is unbounded and equivalence is undefined."
            )
