# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-driven-context-rewrite-it-cannot-prove-is-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-model-driven-context-rewrite-it-cannot-prove-is-idempotent.warrant.json
# Markdown SHA-256:   46334844fec43e7d230f1cc4a408e012fd7cb2b8fb7b263aff61ca7d62600426
# Code AST SHA-256:   fc34c392f0e9eff77fe972197fe487ca47e6a979aeb8b89f4a8abcdd3129ef02
# Verified Classes:   NonIdempotentRewriteError, UnretainedPreImageError, RewriteRequest, CheckpointStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class NonIdempotentRewriteError(RuntimeError):
    """Raised when a model-driven context rewrite cannot be proven safe."""
    pass


class UnretainedPreImageError(RuntimeError):
    """Raised when a rewrite would drop tokens with no external pre-image."""
    pass


@dataclass
class RewriteRequest:
    region_id: str
    instruction: str            # e.g. "drop completed items" (relative) vs literal replace
    is_absolute: bool           # True only if instruction is "replace R with literal L"
    touches_guard_region: bool  # region read by a downstream predicate
    pre_image_available: bool   # external store reachable and keyed by turn
    turn: int


@dataclass
class CheckpointStore:
    _store: dict = field(default_factory=dict)

    def has_pre_image(self, region_id: str, turn: int) -> bool:
        return (region_id, turn) in self._store

    def write_pre_image(self, region_id: str, turn: int, tokens: str) -> None:
        self._store[(region_id, turn)] = tokens


def authorize_rewrite(req: RewriteRequest, store: CheckpointStore) -> str:
    # Guard 1: relative instructions are non-idempotent by construction.
    if not req.is_absolute:
        raise NonIdempotentRewriteError(
            f"region {req.region_id!r} at turn {req.turn}: relative instruction "
            f"{req.instruction!r} cannot be proven idempotent; rewrite is a "
            f"function of its own output. Escalate to checkpointed literal replace."
        )

    # Guard 2: commitment-bearing regions must retain their pre-image.
    if req.touches_guard_region and not (
        req.pre_image_available and store.has_pre_image(req.region_id, req.turn)
    ):
        raise UnretainedPreImageError(
            f"region {req.region_id!r} at turn {req.turn}: rewrite touches a guard "
            f"region with no external pre-image; dropping these tokens would make a "
            f"future predicate silently unevaluable. Write pre-image before rewrite."
        )

    return "authorized: absolute rewrite, pre-image retained or region non-guarded"
