# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-self-editing-context-policies-against-pruning-the-instruction-that-authorizes-the-next-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-self-editing-context-policies-against-pruning-the-instruction-that-authorizes-the-next-rewrite.warrant.json
# Markdown SHA-256:   64f9d8d38d71202ad0818cb6f93caaf2d2d017fccf5a5c702b681201717aa5d9
# Code AST SHA-256:   7d96660ab07094bf87aa63349d0113a8b5f82c3dde23dea44b785c63846e2ef3
# Verified Classes:   SelfAuthorizingPruneError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SelfAuthorizingPruneError(RuntimeError):
    """Raised when a context rewrite would remove or weaken the policy that authorizes rewriting."""
    pass


PROTECTED_POLICY_ID = "rewrite_policy"


def policy_is_evaluable(buffer: dict[str, str], policy_id: str = PROTECTED_POLICY_ID) -> bool:
    # Policy must exist AND sit in a region the pruner is forbidden to touch.
    block = buffer.get(policy_id)
    if block is None:
        return False
    return buffer.get(f"{policy_id}__region") == "protected"


def apply_rewrite(buffer: dict[str, str], candidate: dict[str, str]) -> dict[str, str]:
    """Commit a pruning/compaction rewrite only if the authorization predicate survives it."""
    if not policy_is_evaluable(buffer):
        raise SelfAuthorizingPruneError(
            "pre-state already lacks an evaluable rewrite policy; refusing to edit"
        )
    if not policy_is_evaluable(candidate):
        # Candidate deleted, relocated, or demoted the policy into a prunable region.
        raise SelfAuthorizingPruneError(
            "candidate rewrite would make the authorization predicate unevaluable; "
            "rejecting and retaining pre-rewrite buffer"
        )
    return candidate


def prune_round(buffer: dict[str, str], pruner) -> dict[str, str]:
    candidate = pruner(buffer)
    try:
        return apply_rewrite(buffer, candidate)
    except SelfAuthorizingPruneError:
        # Fall back to the last known-good buffer; skip compression this round.
        return buffer
