# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-window-and-evicts-the-evidence-it-still-needs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-window-and-evicts-the-evidence-it-still-needs.warrant.json
# Markdown SHA-256:   e9fa90484be42bf24908285f070fcfe39a4b3a440ce5988740efe5ea6cf47a32
# Code AST SHA-256:   2f8ee47a62503e28ea4683f67b73e6f2f12ea1f228db0b13f78722c0e0d51e1e
# Verified Classes:   ContextRewriteViolation, Span, Tombstone, Window
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ContextRewriteViolation(RuntimeError):
    """Raised when a self-edit evicts a constraint span without a supersession tombstone."""
    pass


@dataclass
class Span:
    key: str
    text: str
    is_constraint: bool
    verbatim_params: tuple[str, ...] = ()  # numbers, identities, negations that must survive

    def digest(self) -> str:
        return hashlib.sha256(self.text.encode()).hexdigest()[:16]


@dataclass
class Tombstone:
    span_digest: str
    reason: str
    superseded_by: str | None  # key of the span that explicitly overrides it


@dataclass
class Window:
    spans: dict[str, Span] = field(default_factory=dict)
    tombstones: dict[str, Tombstone] = field(default_factory=dict)


def commit_rewrite(old: Window, new_spans: dict[str, Span],
                   new_tombstones: dict[str, Tombstone]) -> Window:
    """
    Fail-closed rewrite: every constraint span in `old` must either survive
    verbatim in `new_spans`, or carry a tombstone naming an explicit supersession.
    Relevance score is deliberately NOT consulted here.
    """
    for key, span in old.spans.items():
        if not span.is_constraint:
            continue

        survivor = new_spans.get(key)
        if survivor is not None:
            if survivor.digest() != span.digest():
                # Paraphrase of a constraint is treated as loss of operative params.
                lost = [p for p in span.verbatim_params if p not in survivor.text]
                if lost:
                    raise ContextRewriteViolation(
                        f"constraint '{key}' paraphrased; operative params lost: {lost}"
                    )
            continue

        tomb = new_tombstones.get(key)
        if tomb is None:
            raise ContextRewriteViolation(
                f"constraint '{key}' evicted with no tombstone "
                f"(digest {span.digest()}); rewrite is not auditable"
            )
        if tomb.superseded_by is None or tomb.superseded_by not in new_spans:
            raise ContextRewriteViolation(
                f"constraint '{key}' tombstoned but supersession target missing"
            )

    return Window(spans=dict(new_spans), tombstones=dict(new_tombstones))
