# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-self-editing-context-window-from-losing-the-causal-lineage-of-the-token-it-rewrites-in-place.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-self-editing-context-window-from-losing-the-causal-lineage-of-the-token-it-rewrites-in-place.warrant.json
# Markdown SHA-256:   5374d0e29cd24c4cd51de499b92573adda3142daee9e5cdfcddb9d9f29529969
# Code AST SHA-256:   1a6661ed9721a57f8ac18bda4f3f944e3f0b4ddeb89c9363718c086bec10243e
# Verified Classes:   LineageBreakError, Constraint
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal

Polarity = Literal["affirm", "negate"]
Ordering = Literal["before", "after", "only", "none"]


class LineageBreakError(RuntimeError):
    """Raised when an in-place rewrite destroys a load-bearing constraint."""


@dataclass(frozen=True)
class Constraint:
    subject: str
    polarity: Polarity
    ordering: Ordering
    span_id: str


def extract_constraints(span: str, span_id: str) -> list[Constraint]:
    # Toy extractor: real systems use a constrained-decoding pass.
    # It must surface negations and orderings explicitly.
    out: list[Constraint] = []
    lowered = span.lower()
    if "not " in lowered or "must not" in lowered:
        out.append(Constraint("target", "negate", "none", span_id))
    if "before" in lowered:
        out.append(Constraint("migration", "affirm", "before", span_id))
    elif "after" in lowered:
        out.append(Constraint("migration", "affirm", "after", span_id))
    return out


def gate_rewrite(
    pre_span: str,
    post_span: str,
    span_id: str,
    ledger: dict[str, list[Constraint]],
) -> None:
    """Invariant: post_span must entail every pre_span constraint with
    identical polarity and ordering. Ledger retains pre-rewrite lineage."""
    pre = ledger.get(span_id) or extract_constraints(pre_span, span_id)
    ledger[span_id] = pre  # retain lineage before any commit
    post = extract_constraints(post_span, span_id)

    pre_key = {(c.subject, c.polarity, c.ordering) for c in pre}
    post_key = {(c.subject, c.polarity, c.ordering) for c in post}

    dropped = pre_key - post_key
    if dropped:
        raise LineageBreakError(
            f"rewrite of span {span_id} dropped load-bearing constraints: "
            f"{sorted(dropped)}; pre={pre_span!r} post={post_span!r}"
        )


def commit_rewrite(
    buffer: list[str],
    span_id: str,
    pre_span: str,
    post_span: str,
    ledger: dict[str, list[Constraint]],
) -> list[str]:
    gate_rewrite(pre_span, post_span, span_id, ledger)
    idx = buffer.index(pre_span)
    return buffer[:idx] + [post_span] + buffer[idx + 1:]


# Demonstration of the observed failure being caught at the gate.
ledger: dict[str, list[Constraint]] = {}
pre = "deploy target must NOT use staging; migration must run BEFORE schema drop"
post = "Deploy to prod-east; migration and schema drop are sequenced"
try:
    commit_rewrite([pre], "span-41", pre, post, ledger)
except LineageBreakError as e:
    print(f"blocked: {e}")
