# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-when-the-pruner-s-own-rationale-is-evicted-mid-pass.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-when-the-pruner-s-own-rationale-is-evicted-mid-pass.warrant.json
# Markdown SHA-256:   c7a8d8bcc9fff471bd06096fe581d58ae2c99fb4295b4cc92c1b26dfff9a020d
# Code AST SHA-256:   f4a83d4b3241646d007a7433092b5a67bdc18fe5f20b9ab9b071e64f451ed558
# Verified Classes:   UnauditableRewriteError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnauditableRewriteError(RuntimeError):
    """Raised when a self-edit cannot be checked against its input."""


def apply_self_edit(buffer: list[str], selection_log: dict | None,
                    pinned_region: list[str]) -> list[str]:
    # Invariant: a rewrite is only admissible if it is auditable
    # (selection_log present) OR obligations are structurally out of reach
    # (pinned_region non-empty and pruner cannot touch it).
    if selection_log is None and not pinned_region:
        raise UnauditableRewriteError(
            "self-edit refused: no selection log and no pinned region; "
            "rewrite would evict its own rationale (Trace B) undetectably"
        )

    # Co-location check: every retained claim must carry a scope qualifier
    # in the same atomic unit. Orphaned qualifiers are Trace A precursors.
    for unit in buffer:
        if unit.startswith("claim:") and "scope=" not in unit:
            raise UnauditableRewriteError(
                f"retained claim lacks scope qualifier: {unit!r}; "
                "pruning this unit would over-generalize the fact"
            )

    # Obligations must never enter the editable buffer.
    for unit in buffer:
        if unit.startswith("obligation:"):
            raise UnauditableRewriteError(
                f"obligation present in editable buffer: {unit!r}; "
                "move to pinned_region before rewriting"
            )

    survivors = [u for u in buffer if not u.startswith("drop:")]
    if selection_log is not None:
        selection_log["kept"] = len(survivors)
        selection_log["dropped"] = len(buffer) - len(survivors)
    return survivors + list(pinned_region)
