# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-semantic-collapse-in-self-editing-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-semantic-collapse-in-self-editing-context-windows.warrant.json
# Markdown SHA-256:   d76d6c67ff18d3b5218e31a2074bd26049795f3954dbd922c2d76ef4795eed8f
# Code AST SHA-256:   0cc4182494d67c633533291991e56bb79ad7e762fc403f85bdb7dbcd1ed9a351
# Verified Classes:   CommitmentLossError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CommitmentLossError(RuntimeError):
    """Raised when a model-driven rewrite would drop or alter a commitment
    that has no durable external record. This is a hard stop: the rewrite
    must be refused and the window spilled to a keyed store instead."""


def apply_rewrite(
    pre_commitments: dict[str, str],
    rewritten_text: str,
    rewritten_commitment_ids: set[str],
    durable_store: dict[str, str],
) -> str:
    """Validate a self-edit before committing it.

    pre_commitments maps commitment id -> canonical statement.
    rewritten_commitment_ids is what the rewriter *claims* it preserved.
    A commitment may be dropped from the window only if it exists in
    durable_store; otherwise the rewrite is refused.
    """
    for cid, statement in pre_commitments.items():
        preserved_in_window = cid in rewritten_commitment_ids
        preserved_durably = cid in durable_store
        if not preserved_in_window and not preserved_durably:
            raise CommitmentLossError(
                f"rewrite would drop commitment {cid!r} ({statement!r}) "
                f"with no durable record; refusing rewrite and requiring spill"
            )
        if preserved_in_window and durable_store.get(cid, statement) != statement:
            raise CommitmentLossError(
                f"rewrite altered commitment {cid!r} from {statement!r} "
                f"to {durable_store[cid]!r}; rewrites may weaken, not strengthen"
            )
    return rewritten_text
