# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-rewriting-before-a-self-editing-policy-corrupts-its-own-evidence-base.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-rewriting-before-a-self-editing-policy-corrupts-its-own-evidence-base.warrant.json
# Markdown SHA-256:   8ff396580b9aaf82433bac3586373c35f58d3f0f9929d22f697ff43de4300e72
# Code AST SHA-256:   b191fa412a6f1368789daed9767f90fa1da90d709c3d846ce6cf9046582a42a9
# Verified Classes:   ProtectedInvariantLoss
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProtectedInvariantLoss(RuntimeError):
    """Raised when a model-driven context rewrite removes or discharges the last
    live reference to a protected, re-checkable invariant."""
    pass


def apply_context_rewrite(
    pre_buffer: dict,
    proposed_buffer: dict,
    protected_store: dict,
) -> dict:
    """
    pre_buffer / proposed_buffer: {entry_id: {"text": str, "status": "live"|"discharged"}}
    protected_store: {entry_id: {"constraint": str}} -- editor has read-only access.

    Returns the buffer to commit. Raises if the edit would strand a protected
    invariant with no live, re-checkable reference.
    """
    for entry_id, spec in protected_store.items():
        pre = pre_buffer.get(entry_id)
        post = proposed_buffer.get(entry_id)

        pre_live = pre is not None and pre.get("status") == "live"
        if not pre_live:
            continue  # invariant was not live before this edit; nothing to strand

        post_present = post is not None
        post_live = post_present and post.get("status") == "live"

        if not post_present:
            raise ProtectedInvariantLoss(
                f"rewrite dropped protected invariant {entry_id!r} "
                f"({spec['constraint']!r}); last live reference removed"
            )
        if not post_live:
            raise ProtectedInvariantLoss(
                f"rewrite downgraded protected invariant {entry_id!r} from "
                f"'live' to {post.get('status')!r} without external validator "
                f"verdict; summarizer may not discharge re-checkable constraints"
            )

    return proposed_buffer
