# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-windows-from-corrupting-their-own-rewrite-base-during-in-place-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-windows-from-corrupting-their-own-rewrite-base-during-in-place-eviction.warrant.json
# Markdown SHA-256:   79abb8a44ce2c57b3c47602d49e12bb54e860fc57e90a0b07253142ec267aeba
# Code AST SHA-256:   89384ab2bda37cc2bd5b03c4bc9cbf8ed9db3433bedb69e1906b103de21efaa4
# Verified Classes:   StaleSpanError, SummaryLineageError, Span, ContextBuffer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class StaleSpanError(RuntimeError):
    """Raised when an edit or read is issued against a buffer version that no longer matches."""
    pass


class SummaryLineageError(RuntimeError):
    """Raised when re-summarization depth exceeds the integrity bound."""
    pass


@dataclass
class Span:
    start: int
    end: int
    version: int


@dataclass
class ContextBuffer:
    tokens: list
    version: int = 0
    _summary_depth: dict = field(default_factory=dict)

    def content_hash(self) -> str:
        return hashlib.sha256(" ".join(self.tokens).encode()).hexdigest()

    def read(self, span: Span) -> list:
        if span.version != self.version:
            raise StaleSpanError(
                f"span bound to v{span.version}, buffer at v{self.version}; "
                f"offsets [{span.start},{span.end}) no longer address the intended region"
            )
        if span.start < 0 or span.end > len(self.tokens) or span.start > span.end:
            raise StaleSpanError(f"span [{span.start},{span.end}) out of bounds at v{self.version}")
        return self.tokens[span.start:span.end]

    def splice(self, span: Span, replacement: list, depth: int = 0, max_depth: int = 2) -> None:
        if span.version != self.version:
            raise StaleSpanError(
                f"refusing stale-base splice: diff computed at v{span.version}, live v{self.version}"
            )
        if depth > max_depth:
            raise SummaryLineageError(
                f"summary depth {depth} exceeds bound {max_depth}; "
                f"re-summarize from pinned original instead"
            )
        removed = span.end - span.start
        self.tokens[span.start:span.end] = replacement
        self.version += 1
        # shift recorded depth of any downstream region is handled by version bump:
        # all prior spans are now stale and must be re-resolved.

    def append(self, new_tokens: list, expected_version: int) -> None:
        if expected_version != self.version:
            raise StaleSpanError(
                f"append raced with splice: expected v{expected_version}, live v{self.version}; "
                f"re-queue tool output"
            )
        self.tokens.extend(new_tokens)
        self.version += 1


def evict_and_compress(buf: ContextBuffer, span: Span, summarizer, depth: int = 0) -> None:
    """Summarizer must be called on the ORIGINAL pinned tokens, never on a prior summary."""
    original = buf.read(span)  # raises StaleSpanError if span.version != buf.version
    summary = summarizer(original)
    buf.splice(span, summary, depth=depth)
