# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-pruning-corruption-of-its-own-context-window-when-model-driven-relevance-rewriting-invalidates-prior-reasoning-premis.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-pruning-corruption-of-its-own-context-window-when-model-driven-relevance-rewriting-invalidates-prior-reasoning-premis.warrant.json
# Markdown SHA-256:   c31496b7fbb71299c9de5e18e3dcb2c0709f7ab0d99fa071611a45c4ebab952e
# Code AST SHA-256:   828954edef346176551438f8d8118d6411f15549e81f9209bd8e7e6a8ac4db4f
# Verified Classes:   ContextRewriteCorruption, Provenance, Turn
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ContextRewriteCorruption(RuntimeError):
    """Raised when a derived (rewritten) turn is about to be used as an
    evidentiary premise and its asserted constraints contradict the
    authored turn it replaced."""


class Provenance(Enum):
    AUTHORED = "authored"   # original model/user/tool output
    DERIVED = "derived"     # machine-rewritten, must be shadowed


@dataclass
class Turn:
    index: int
    content: str
    provenance: Provenance
    # For DERIVED turns: the authored turn this rewrite shadows.
    replaces: Optional[int] = None
    # Constraints extracted from the authored original at rewrite time.
    constraints: list[str] = field(default_factory=list)


LOAD_BEARING_MARKERS = ("do not", "never", "only if", "because",
                        "not ", "global", "per-key", "must not")


def is_load_bearing(content: str) -> bool:
    low = content.lower()
    return any(m in low for m in LOAD_BEARING_MARKERS)


def safe_rewrite(window: list[Turn], target_idx: int,
                 rewritten: str) -> Turn:
    """Produce a DERIVED turn only if the authored original is preserved
    as a shadow. Refuses in-place overwrite of load-bearing turns."""
    original = window[target_idx]
    if original.provenance is not Provenance.AUTHORED:
        raise ContextRewriteCorruption(
            f"turn {target_idx} is already derived; refusing to rewrite "
            f"a rewrite (provenance laundering)."
        )
    if is_load_bearing(original.content):
        # Must shadow, not replace: keep original readable.
        return Turn(
            index=len(window),
            content=rewritten,
            provenance=Provenance.DERIVED,
            replaces=target_idx,
            constraints=_extract_constraints(original.content),
        )
    return Turn(index=len(window), content=rewritten,
                provenance=Provenance.DERIVED, replaces=target_idx)


def _extract_constraints(content: str) -> list[str]:
    # Minimal polarity/scope extraction; production systems use a
    # dedicated constraint parser over tool outputs.
    return [s.strip() for s in content.split(";")
            if is_load_bearing(s)]


def assert_premise_safe(window: list[Turn], turn: Turn) -> None:
    """Call before any decision that depends on `turn`."""
    if turn.provenance is not Provenance.DERIVED:
        return
    if turn.replaces is None:
        raise ContextRewriteCorruption(
            f"derived turn {turn.index} has no shadow link; "
            f"premise is unresolvable."
        )
    authored = window[turn.replaces]
    for c in turn.constraints:
        if not _constraint_preserved(c, turn.content):
            raise ContextRewriteCorruption(
                f"derived turn {turn.index} dropped or inverted a "
                f"load-bearing constraint from authored turn "
                f"{authored.index}: {c!r}. Refusing to reason on it; "
                f"checkpoint and cold-start against transcript."
            )


def _constraint_preserved(constraint: str, rewritten: str) -> bool:
    # Negation/scope must survive verbatim or be explicitly re-asserted.
    return constraint.lower() in rewritten.lower()
