# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-serialize-a-self-editing-context-policy-before-mutating-in-place-and-what-breaks-when-it-doesn-t.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-serialize-a-self-editing-context-policy-before-mutating-in-place-and-what-breaks-when-it-doesn-t.warrant.json
# Markdown SHA-256:   72c657b1ffbb976954ff80bf9deeac5cfbc87c0c09b9b0e2c3f5c8ce56443ae8
# Code AST SHA-256:   5e5873bcb9ef05bf41d37797e8f6b1427712f3e0d4f6d69d40712e59127e8d00
# Verified Classes:   ContextMutationError, JournalRecord, SelfEditingContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field

class ContextMutationError(RuntimeError):
    """Raised when an in-place context mutation cannot guarantee rollback integrity."""
    pass

@dataclass
class JournalRecord:
    span_id: str
    content: str
    content_hash: str
    generation: int

class SelfEditingContext:
    def __init__(self, window_tokens: int, protected_regions: set[str] | None = None):
        self.window_tokens = window_tokens
        self.buffer: list[str] = []
        self.journal: dict[str, JournalRecord] = {}
        self.protected_regions: set[str] = protected_regions or set()
        self.generation = 0

    def _hash(self, content: str) -> str:
        return hashlib.sha256(content.encode("utf-8")).hexdigest()

    def serialize_policy_before_mutation(self, evict_fraction: float, projected_len: int) -> None:
        # Invariant: journal must be disjoint from eviction region under PROJECTED length.
        unprotected = [i for i in range(projected_len) if str(i) not in self.protected_regions]
        evict_count = int(projected_len * evict_fraction)
        if evict_count > len(unprotected):
            raise ContextMutationError(
                f"eviction window ({evict_count}) exceeds unprotected region "
                f"({len(unprotected)}); journal would be destroyed by its own mutation"
            )
        if not self.journal and evict_count > 0:
            raise ContextMutationError(
                "no journal serialized before mutation; rollback record would be coupled to target"
            )

    def compact_in_place(self, evict_fraction: float, digest: str) -> None:
        projected = len(self.buffer) + 1  # digest will be spliced in
        self.serialize_policy_before_mutation(evict_fraction, projected)

        evict_count = int(len(self.buffer) * evict_fraction)
        evicted = self.buffer[:evict_count]

        # Journal BEFORE commit, with generation + hash for pointer validation.
        self.generation += 1
        span_id = f"span-{self.generation}"
        joined = "\n".join(evicted)
        self.journal[span_id] = JournalRecord(
            span_id=span_id,
            content=joined,
            content_hash=self._hash(joined),
            generation=self.generation,
        )
        self.protected_regions.add(span_id)

        self.buffer = [digest] + self.buffer[evict_count:]

    def rollback(self, span_id: str) -> str:
        rec = self.journal.get(span_id)
        if rec is None:
            raise ContextMutationError(f"rollback target {span_id} absent from journal")
        if self._hash(rec.content) != rec.content_hash:
            raise ContextMutationError(
                f"journal {span_id} failed integrity check; pointer displaced or overwritten"
            )
        # Restore only if integrity holds; never trust a plausible-but-unverified span.
        self.buffer = rec.content.split("\n") + self.buffer
        return rec.content
