# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-in-place-and-the-rewrite-target-is-a-token-it-has-already-conditioned-on.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-in-place-and-the-rewrite-target-is-a-token-it-has-already-conditioned-on.warrant.json
# Markdown SHA-256:   94ccf87be7aebc0aea3f77b6bc18ece4b797f1a0e34bb7a442d6ee03ad231b9e
# Code AST SHA-256:   d40cbf1dfa61586f291ac8eaf48927594b12bf338284f38bd19740bcbae5583a
# Verified Classes:   SplitBrainPrefixError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SplitBrainPrefixError(RuntimeError):
    """Raised when an in-place context mutation targets a position the model
    has already conditioned on while retaining cached state for later positions."""


def apply_self_edit(context_tokens: list[str],
                    cache_frontier: int,
                    target_start: int,
                    target_end: int,
                    replacement: list[str]) -> list[str]:
    """Apply an in-place rewrite only if it does not split the causal prefix.

    cache_frontier is the index of the first position for which no cached
    conditioning exists (i.e., the model has attended over [0, cache_frontier)).
    A mutation at any index < cache_frontier while retaining cache for
    positions > target_end produces a split-brain prefix.
    """
    if target_start < 0 or target_end > len(context_tokens):
        raise SplitBrainPrefixError(
            f"mutation range [{target_start},{target_end}) out of bounds for "
            f"context of length {len(context_tokens)}"
        )

    # Unsound: mutating a span the model has already attended over, with any
    # retained cached state downstream of the mutation target.
    if target_start < cache_frontier and target_end < cache_frontier:
        raise SplitBrainPrefixError(
            f"in-place rewrite targets causally-antecedent span "
            f"[{target_start},{target_end}) below cache frontier {cache_frontier}; "
            f"downstream cached state would retain pre-rewrite conditioning. "
            f"Downgrade to append-only supersession or invalidate cache for "
            f"positions >= {target_start}."
        )

    # Sound: mutation at or beyond the frontier, or a tail rewrite.
    return context_tokens[:target_start] + replacement + context_tokens[target_end:]


def compact_scratchpad(context_tokens: list[str],
                       cache_frontier: int,
                       summarize) -> list[str]:
    """Compaction entry point that enforces the causal-barrier invariant."""
    if cache_frontier < len(context_tokens):
        # There is live cached conditioning over a prefix; an in-place rewrite
        # of that prefix is unsound. Convert to append-only supersession.
        summary = summarize(context_tokens[:cache_frontier])
        marker = ["<supersedes>", *summary, "</supersedes>"]
        return context_tokens + marker
    # No live conditioning over the prefix: in-place is safe.
    summary = summarize(context_tokens)
    return list(summary)
