# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-apply-a-self-authored-system-prompt-rewrite-when-the-rewrite-s-justification-depends-on-memory-it-is.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-apply-a-self-authored-system-prompt-rewrite-when-the-rewrite-s-justification-depends-on-memory-it-is.warrant.json
# Markdown SHA-256:   20690fc3580a464771702c6b78e807b07afa48d95a55f0b4642d1452d0a0dacc
# Code AST SHA-256:   3d669f87011454d0c405ff297f46f96ad2d7ffbbc8dfb19e3ff8a2cf062ae82f
# Verified Classes:   WarrantEvictionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class WarrantEvictionError(RuntimeError):
    """Raised when a self-authored rewrite would evict the supporting span
    for a constraint the rewrite itself retains. The rewrite is unsound:
    a fresh instance could not reconstruct why the retained rule is hard."""
    pass


def commit_rewrite(
    retained_constraints: dict[str, str],   # constraint_id -> text asserted in new prompt
    supporting_spans: dict[str, set[str]],  # constraint_id -> span ids that warrant it
    evicted_span_ids: set[str],
    hardness: dict[str, str],               # constraint_id -> "hard" | "soft"
) -> None:
    """Pre-commit gate. MUST run against the pre-rewrite context, before the
    eviction is applied, because after commit the evidence is gone."""
    for cid, text in retained_constraints.items():
        if hardness.get(cid) != "hard":
            continue
        lost = supporting_spans.get(cid, set()) & evicted_span_ids
        if lost:
            raise WarrantEvictionError(
                f"Rewrite retains hard constraint {cid!r} ({text!r}) but evicts "
                f"its warrant spans {sorted(lost)}. Synthesize a compressed warrant "
                f"(rule + hardness + consequence + source pointer) before evicting, "
                f"or drop the rewrite."
            )
    # Only reached when every retained hard constraint keeps its warrant.
