# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-corrupt-its-own-reasoning-when-it-edits-the-context-window-in-place-over-a-live-kv-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-corrupt-its-own-reasoning-when-it-edits-the-context-window-in-place-over-a-live-kv-cache.warrant.json
# Markdown SHA-256:   3ba73ff538309e886619377f2717a34a24a6b2b3371cd6be8c1b60991d4012f6
# Code AST SHA-256:   3035daf833c7547e2b5d4554336685ac3fd59a52e1411e10c1cb490993fc95fa
# Verified Classes:   GhostCacheError, CachedSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class GhostCacheError(RuntimeError):
    """Raised when an in-place context edit would reuse K/V entries whose
    provenance no longer matches the token stream at those positions."""
    pass


@dataclass
class CachedSpan:
    start: int
    end: int
    token_hash: str  # hash of tokens[start:end] at cache-fill time


def _hash_tokens(tokens: list[int]) -> str:
    h = hashlib.sha256()
    for t in tokens:
        h.update(t.to_bytes(8, "little", signed=False))
    return h.hexdigest()


def apply_self_edit(
    tokens: list[int],
    cache: list[CachedSpan],
    edit_start: int,
    edit_end: int,
    replacement: list[int],
) -> tuple[list[int], list[CachedSpan]]:
    """Apply a mutating edit and return (new_tokens, valid_cache_suffix).

    The returned cache is truncated at the first token index whose
    provenance diverges from the pre-edit stream. Any span overlapping
    or following the divergence point is dropped; the caller MUST
    recompute K/V for the dropped suffix.
    """
    if edit_start < 0 or edit_end > len(tokens) or edit_start > edit_end:
        raise GhostCacheError(
            f"edit range [{edit_start},{edit_end}) out of bounds for {len(tokens)} tokens"
        )

    new_tokens = tokens[:edit_start] + replacement + tokens[edit_end:]

    # Find first divergence at token granularity, NOT turn granularity.
    divergence = edit_start
    limit = min(len(tokens), len(new_tokens))
    while divergence < limit and tokens[divergence] == new_tokens[divergence]:
        divergence += 1

    surviving: list[CachedSpan] = []
    for span in cache:
        if span.end <= divergence:
            # Fully before divergence: provenance intact, verify anyway.
            if span.token_hash != _hash_tokens(tokens[span.start:span.end]):
                raise GhostCacheError(
                    f"cache span [{span.start},{span.end}) has stale provenance "
                    f"even before divergence {divergence}; cache is untrustworthy"
                )
            surviving.append(span)
        else:
            # Overlaps or follows divergence: must be recomputed.
            break

    # A length-preserving edit is the dangerous case: positions look stable,
    # so a naive runtime reports a false prefix hit. Force truncation.
    if len(new_tokens) == len(tokens) and divergence < len(tokens):
        surviving = [s for s in surviving if s.end <= divergence]

    return new_tokens, surviving
