# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-introduced-by-its-own-context-pruning-rewrites.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-introduced-by-its-own-context-pruning-rewrites.warrant.json
# Markdown SHA-256:   b3a88e39f790d5e3365719388fd74ec2bbcc56bb820fe71baeb05bd9c1bd99a2
# Code AST SHA-256:   36ee04683efcb596827a7f942866bfeae7bf4c5c2518038bfb30480535fc4857
# Verified Classes:   RewriteFidelityError, ContentClass, Span, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class RewriteFidelityError(RuntimeError):
    """Raised when a self-authored rewrite is asked to authorize an
    irreversible action without a verifiable, unparaphrased source."""


class ContentClass(Enum):
    NARRATIVE = "narrative"      # reasoning traces; safe to paraphrase
    COMMITMENT = "commitment"    # identifiers, bounds, negations; NOT safe


@dataclass
class Span:
    span_id: str
    content_class: ContentClass
    text: str
    rewritten_from: str | None = None  # provenance tag; None = original


@dataclass
class ContextWindow:
    spans: list[Span] = field(default_factory=list)
    pinned: dict[str, str] = field(default_factory=dict)  # id -> exact token

    def pin(self, key: str, exact: str) -> None:
        # Commitments are pinned verbatim; never paraphrased.
        self.pinned[key] = exact

    def rewrite(self, span_id: str, new_text: str) -> Span:
        target = next(s for s in self.spans if s.span_id == span_id)
        if target.content_class is ContentClass.COMMITMENT:
            raise RewriteFidelityError(
                f"refusing to paraphrase commitment span {span_id!r}; "
                f"pin it verbatim instead"
            )
        return Span(
            span_id=span_id,
            content_class=target.content_class,
            text=new_text,
            rewritten_from=target.text,  # tag the rewrite
        )

    def authorize_irreversible(self, action: str, required_keys: list[str]) -> None:
        # An irreversible action may only proceed if every load-bearing
        # commitment is present verbatim in the pinned region -- not merely
        # present in a (possibly drifted) rewrite.
        missing = [k for k in required_keys if k not in self.pinned]
        if missing:
            raise RewriteFidelityError(
                f"action {action!r} blocked: commitments {missing} are not "
                f"pinned; current window contains only rewrites, which cannot "
                f"authorize irreversible execution"
            )


def compact(window: ContextWindow, span_id: str, summary: str) -> None:
    # Wrapper that enforces the boundary at the call site.
    try:
        window.spans.append(window.rewrite(span_id, summary))
    except RewriteFidelityError:
        # Do not silently fall back to paraphrasing a commitment.
        raise
