# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-model-driven-context-rewriting-has-invalidated-its-own-policy-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-model-driven-context-rewriting-has-invalidated-its-own-policy-state.warrant.json
# Markdown SHA-256:   b5c29bb27da029e7fc17feec71fec87c016e612ceaf1d829bf852daf83973d0e
# Code AST SHA-256:   0455efe971a58d9b749635b2e29314f0728494dd54197bd2366e9af7b23a40ff
# Verified Classes:   PolicyDriftError, RewriteResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class PolicyDriftError(RuntimeError):
    """Raised when a context rewrite mutates the policy segment without authorization."""
    pass


@dataclass
class RewriteResult:
    context_before: str
    context_after: str
    policy_span: tuple  # (start, end) offsets into context
    policy_edit_requested: bool


def _policy_hash(context: str, span: tuple) -> str:
    start, end = span
    return hashlib.sha256(context[start:end].encode("utf-8")).hexdigest()


def validate_rewrite(result: RewriteResult) -> None:
    before_hash = _policy_hash(result.context_before, result.policy_span)

    # Policy segment must still exist within bounds after rewrite.
    start, end = result.policy_span
    if end > len(result.context_after) or start >= end:
        raise PolicyDriftError(
            "policy segment absent or out of bounds after rewrite; "
            "refusing to commit self-editing context"
        )

    after_hash = _policy_hash(result.context_after, result.policy_span)

    if not result.policy_edit_requested and before_hash != after_hash:
        raise PolicyDriftError(
            f"policy segment mutated without authorization: "
            f"{before_hash[:12]} -> {after_hash[:12]}"
        )

    if result.policy_edit_requested and before_hash == after_hash:
        # Not an error, but worth flagging: a requested edit was a no-op.
        return


def commit_rewrite(result: RewriteResult) -> str:
    validate_rewrite(result)
    return result.context_after
