# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-rewrite-its-own-transcript-self-editing-context-loss-under-an-invariant-the-controller-cannot-re-derive.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-rewrite-its-own-transcript-self-editing-context-loss-under-an-invariant-the-controller-cannot-re-derive.warrant.json
# Markdown SHA-256:   536b5a75f09e4a092b28edb509ae963f79b25b5ee41c370f3119ec07dab3c709
# Code AST SHA-256:   e09e67ca53139858af016f10c6d26c1c4b2cabfed1ee0b07fb475e045f7a66e4
# Verified Classes:   InvariantRewriteError, Invariant, Turn
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field
from typing import Optional


class InvariantRewriteError(RuntimeError):
    """Raised when a context rewrite would demote a carry-forward-only invariant
    from a checkable predicate to an unverifiable gist."""


# Signals that a turn is invariant-bearing and must not be gist-compressed
# without predicate preservation.
_DEONTIC = re.compile(r"\b(must|do not|don't|never|only after|until|before)\b", re.I)
_BOUND = re.compile(r"\b(\d{1,2}:\d{2}\s*UTC|\d+\s*(?:s|m|min|h|hours?|rows?|ms))\b", re.I)


@dataclass
class Invariant:
    entity: str
    predicate: str
    bound: Optional[str]
    source_turn: int

    def key_terms(self) -> set[str]:
        terms = {self.entity.lower(), self.predicate.lower()}
        if self.bound:
            terms.add(self.bound.lower())
        return {t for t in terms if t}


@dataclass
class Turn:
    index: int
    text: str
    invariants: list[Invariant] = field(default_factory=list)


def extract_invariants(turn: Turn) -> list[Invariant]:
    """Conservative extraction: any turn with a deontic operator AND a bound
    is treated as invariant-bearing. Under-extraction is safer than
    over-extraction here because the cost of a missed invariant is a cliff."""
    if not (_DEONTIC.search(turn.text) and _BOUND.search(turn.text)):
        return []
    bound = _BOUND.search(turn.text)
    # Entity is approximated as the nearest noun-ish token before the bound;
    # in production this is a typed slot-filler, not a regex.
    entity_match = re.search(r"`([^`]+)`|(\b[a-z]+-[a-z]+\b)", turn.text)
    entity = (entity_match.group(1) or entity_match.group(2)) if entity_match else "unknown"
    return [Invariant(
        entity=entity,
        predicate=turn.text.strip(),
        bound=bound.group(0) if bound else None,
        source_turn=turn.index,
    )]


def rewrite_turn(turn: Turn, replacement: str, retained_window: list[Turn]) -> Turn:
    """Attempt to replace a turn. Refuses if the replacement does not
    re-assert every invariant the original carried, in predicate-preserving
    form, or if the retained window does not entail them."""
    invariants = extract_invariants(turn)
    if not invariants:
        return Turn(index=turn.index, text=replacement)

    replacement_lower = replacement.lower()
    window_text = " ".join(t.text for t in retained_window).lower()

    for inv in invariants:
        terms = inv.key_terms()
        # Condition (b): the rewrite itself must preserve the predicate.
        if not all(term in replacement_lower for term in terms):
            # Condition (a): the retained window must entail the invariant.
            if not all(term in window_text for term in terms):
                raise InvariantRewriteError(
                    f"Refusing rewrite of turn {turn.index}: invariant "
                    f"(entity={inv.entity!r}, bound={inv.bound!r}) is neither "
                    f"re-asserted in the replacement nor entailed by the "
                    f"retained window. Gist compression would demote a "
                    f"carry-forward-only invariant to an unchecked belief."
                )
    return Turn(index=turn.index, text=replacement, invariants=invariants)


def compact(window: list[Turn], target_index: int, digest: str) -> list[Turn]:
    target = next(t for t in window if t.index == target_index)
    retained = [t for t in window if t.index != target_index]
    rewritten = rewrite_turn(target, digest, retained)
    return [rewritten if t.index == target_index else t for t in window]
