# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-self-edited-context-policy-the-prompt-rewrite-self-verification-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-self-edited-context-policy-the-prompt-rewrite-self-verification-gap.warrant.json
# Markdown SHA-256:   e6b37a5bba28bca6fec0bc00bce3fcfbcdaed2f66f26b7f624925ebe5562f95d
# Code AST SHA-256:   a27f3d2fde2a3462837b64ff2cfcf1bf2064882126dec81e8338a8fc2fcb82db
# Verified Classes:   SelfEditCommitRefused
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SelfEditCommitRefused(RuntimeError):
    """Raised when a self-edited context policy cannot be proven to preserve invariants."""
    pass


INVARIANT_TAGS = {"verify_before_write", "no_scope_escape", "audit_log_required"}


def preserves_invariant(old_policy: dict, new_policy: dict, tag: str) -> bool:
    # Executable check: the invariant must remain bound to an invocable step,
    # not merely re-described. Compares binding, not wording.
    old_binding = old_policy.get("invariants", {}).get(tag)
    new_binding = new_policy.get("invariants", {}).get(tag)
    if old_binding is None:
        return True
    if new_binding is None:
        return False
    return new_binding.get("invocable_step") == old_binding.get("invocable_step")


def commit_self_edit(old_policy: dict,
                     new_policy: dict,
                     verifier: str,
                     trigger: str) -> dict:
    touched = {
        tag for tag in INVARIANT_TAGS
        if old_policy.get("invariants", {}).get(tag)
        != new_policy.get("invariants", {}).get(tag)
    }

    if touched and verifier == "self_critique":
        raise SelfEditCommitRefused(
            f"invariant region {sorted(touched)} edited under verifier='self_critique'; "
            f"self-verification gap open, escalate for external diff review"
        )

    if touched and trigger == "token_budget_pressure":
        raise SelfEditCommitRefused(
            f"invariant edit motivated by budget pressure ({trigger}); "
            f"route to scratchpad compaction, not constraint mutation"
        )

    for tag in touched:
        if not preserves_invariant(old_policy, new_policy, tag):
            raise SelfEditCommitRefused(
                f"invariant '{tag}' lost its executable binding in rewrite; "
                f"paraphrase is a constraint mutation"
            )

    return {"committed": True, "new_policy": new_policy, "touched": sorted(touched)}
