# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-spends-its-context-rewriting-budget-on-a-self-referential-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-spends-its-context-rewriting-budget-on-a-self-referential-rewrite.warrant.json
# Markdown SHA-256:   80b966f396f8a413a4e61762ac2158f4fcc5783dbf7cde5e17835dab50d89a59
# Code AST SHA-256:   7e977081b35f1f3e917d5cb6ef075dd645ffc6a2771f3573ea53edc4f8658682
# Verified Classes:   SelfAuthoredBudgetError, BudgetLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re

LEDGER_RE = re.compile(r"budget_remaining\s*:\s*(\d+)", re.IGNORECASE)


class SelfAuthoredBudgetError(RuntimeError):
    """Raised when a rewrite op attempts to author its own budget ledger
    inside the rewritable region, or when the authored ledger disagrees
    with the authoritative external counter post-commit."""
    pass


class BudgetLedger:
    def __init__(self, remaining: int):
        self.remaining = remaining

    def decrement(self, n: int = 1) -> None:
        self.remaining -= n


def commit_rewrite(op_text: str, ledger: BudgetLedger) -> str:
    """Apply a model-authored rewrite op against the authoritative ledger.

    The op may not contain a ledger line: authorization must come from the
    external counter, never from text the op can edit. The runtime rewrites
    the in-context ledger itself after commit.
    """
    authored = LEDGER_RE.findall(op_text)
    if authored:
        raise SelfAuthoredBudgetError(
            "rewrite op contains a self-authored budget ledger line "
            f"({authored!r}); the ledger is pinned outside the rewritable "
            "region and must not be authored by the op. Remove the ledger "
            "line and retry; the runtime will render the correct value."
        )

    if ledger.remaining <= 0:
        raise SelfAuthoredBudgetError(
            "rewrite budget exhausted; no ops may commit. The ledger has "
            "been corrected in-context to budget_remaining: 0."
        )

    ledger.decrement(1)
    # Runtime owns the ledger rendering after commit.
    return f"{op_text}\n\n[ledger] budget_remaining: {ledger.remaining}"
