# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-its-own-pruning-decision-as-a-state-mutation-requiring-re-derivation-of-every-downstream-reference.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-its-own-pruning-decision-as-a-state-mutation-requiring-re-derivation-of-every-downstream-reference.warrant.json
# Markdown SHA-256:   b7563e8fe8f7a3b68f357ac73a805b4f7179cfc038122fd73e978b136d9e3004
# Code AST SHA-256:   c3773f711934b1ef600d77146e1464a96eada1304a4b8d1cdc32d2a7e2955804
# Verified Classes:   DanglingReferentError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class DanglingReferentError(RuntimeError):
    """Raised when a self-rewrite removes a referent still cited by a surviving token."""
    pass


def commit_self_rewrite(pre_buffer: dict, post_buffer: dict, protected_regions: list[str]) -> dict:
    """
    pre_buffer / post_buffer: {"tokens": list[str], "citations": dict[token_index, set[str]]}
    protected_regions: names of regions whose citations must remain resolvable.

    Invariant: every identifier cited by a surviving token must still appear
    verbatim somewhere in the post-rewrite buffer.
    """
    surviving_text = " ".join(post_buffer["tokens"])

    # Collect identifiers cited by tokens that survived the rewrite.
    live_citations: set[str] = set()
    for idx, refs in pre_buffer["citations"].items():
        if idx < len(post_buffer["tokens"]) and pre_buffer["tokens"][idx] == post_buffer["tokens"][idx]:
            live_citations |= refs  # token survived unchanged; its citations are still live

    dangling = {ref for ref in live_citations if ref not in surviving_text}

    if dangling:
        # Out-of-bounds mutation: referent elided, citation retained.
        raise DanglingReferentError(
            f"Self-rewrite would orphan live referents {sorted(dangling)}. "
            f"Retain these spans verbatim or re-derive their citations atomically."
        )

    return post_buffer
