# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-corrupted-context-during-model-driven-pruning-and-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-corrupted-context-during-model-driven-pruning-and-rewrite.warrant.json
# Markdown SHA-256:   8da45333747ecffedb0867213c721a193db77b83797d49e9abecc129ee2822d0
# Code AST SHA-256:   5dafb640adeb72d481e28ec257e7cb0f89ee85ed28488dbfefd16b281b02d6f2
# Verified Classes:   ContextConservationError, Span, ContextStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ContextConservationError(RuntimeError):
    """Raised when a model-driven rewrite/prune violates claim-atom conservation."""
    pass


# Atoms that, if dropped by a rewrite, indicate a corruption candidate.
ATOM_MARKERS = ("not ", "no ", "for ", "only ", "except ", "=", "%", "ms", "prod", "staging")


def extract_atoms(text: str) -> set[str]:
    low = text.lower()
    return {m for m in ATOM_MARKERS if m in low}


@dataclass
class Span:
    span_id: int
    text: str
    rewrite_generation: int = 0
    pruned: bool = False


@dataclass
class ContextStore:
    spans: dict[int, Span] = field(default_factory=dict)
    MAX_GENERATION: int = 1  # observed safe cap; drift compounds past this

    def stage_rewrite(self, span_id: int, new_text: str) -> Span:
        src = self.spans[span_id]
        if src.rewrite_generation >= self.MAX_GENERATION:
            raise ContextConservationError(
                f"span {span_id} at generation {src.rewrite_generation}; "
                f"re-summarization would compound drift—re-derive from tool log"
            )
        src_atoms = extract_atoms(src.text)
        new_atoms = extract_atoms(new_text)
        dropped = src_atoms - new_atoms
        if dropped:
            raise ContextConservationError(
                f"rewrite of span {span_id} drops claim atoms {sorted(dropped)}; "
                f"source={src.text!r} rewrite={new_text!r}"
            )
        return Span(span_id=span_id, text=new_text,
                    rewrite_generation=src.rewrite_generation + 1)

    def commit_rewrite_and_prune(self, span_id: int, new_text: str) -> None:
        # Fuse-ban: rewrite and prune in one op is unsound; must be separate.
        staged = self.stage_rewrite(span_id, new_text)
        # Verification edge: source and rewrite coexist here; only now prune.
        self.spans[span_id] = staged
        self.spans[span_id].pruned = True


def apply_edit(store: ContextStore, span_id: int, new_text: str) -> None:
    if span_id not in store.spans:
        raise ContextConservationError(f"unknown span {span_id}")
    store.commit_rewrite_and_prune(span_id, new_text)
