# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-self-editing-context-policy-silently-corrupt-its-own-drift-detector-after-the-rewrite-budget-is-exhausted.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-self-editing-context-policy-silently-corrupt-its-own-drift-detector-after-the-rewrite-budget-is-exhausted.warrant.json
# Markdown SHA-256:   5f26373f9f03e16efa01004ec1c9ae17484455d194c7a37cdf805392f19c1852
# Code AST SHA-256:   1535c4ae800f3c5c5968ba6da8343645212c1ec12c15b0eb592f217316c45b01
# Verified Classes:   BaselineMutationError, DriftReference, SelfEditingContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class BaselineMutationError(RuntimeError):
    """Raised when an instance attempts to write the drift baseline it is scored against."""


@dataclass
class DriftReference:
    _embedding: tuple
    _version: int = 0
    _frozen: bool = True

    def read(self) -> tuple:
        return self._embedding

    def overwrite(self, new_embedding: tuple, actor: str) -> None:
        # The core invariant: no instance-reachable path may mutate the reference.
        if self._frozen and actor != "authority":
            raise BaselineMutationError(
                f"actor={actor!r} attempted to overwrite drift baseline "
                f"(version={self._version}); baseline is write-once per episode. "
                f"Use the authority re-baseline path, which resets the rewrite budget."
            )
        self._embedding = new_embedding
        self._version += 1


@dataclass
class SelfEditingContext:
    working_block: str
    budget: int
    edits_used: int = 0
    reference: DriftReference = field(default_factory=lambda: DriftReference(("emb",)))

    def _assert_not_exhausted(self) -> None:
        if self.edits_used >= self.budget:
            raise BaselineMutationError(
                "rewrite budget exhausted; working block is frozen for this episode. "
                "Consolidation/reconciliation writes are disallowed after exhaustion."
            )

    def rewrite(self, new_block: str, actor: str = "instance") -> None:
        self._assert_not_exhausted()
        # Any mutation of detector-read state consumes budget, including baseline-adjacent writes.
        self.edits_used += 1
        self.working_block = new_block

    def reconcile_baseline(self, actor: str = "instance") -> None:
        # This is the trap: budget-exhausted path that tries to sync the reference.
        self._assert_not_exhausted()  # raises once budget is spent -> blocks the corruption
        self.reference.overwrite(("emb", self.working_block[:8]), actor=actor)


def run_episode(ctx: SelfEditingContext, edits: list[str]) -> None:
    for i, e in enumerate(edits):
        try:
            ctx.rewrite(e)
        except BaselineMutationError:
            # Budget spent: only revert-to-accepted is legal now.
            ctx.reconcile_baseline(actor="instance")  # must raise, not silently absorb
            raise BaselineMutationError(
                f"episode aborted at edit {i}: attempted self-reconcile after budget exhaustion"
            )
