# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-self-revise-its-prompt-into-a-budget-infeasible-state-and-lose-the-ability-to-revert.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-self-revise-its-prompt-into-a-budget-infeasible-state-and-lose-the-ability-to-revert.warrant.json
# Markdown SHA-256:   bf44ae3af1360ffc4bf7d95a394e90156e029ada554d2794385edfcfe67ac05b
# Code AST SHA-256:   138113fc26889da23c1c8366fd005b6a85d80a8e9e38825f1630d498cb20599c
# Verified Classes:   BudgetInfeasibleRevision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class BudgetInfeasibleRevision(RuntimeError):
    """Raised when an in-place prompt revision would commit a post-state that
    cannot fit the window, or cannot be reverted because no shadow copy exists."""
    pass


def commit_self_edit(prior_text, proposed_delta, window, reserve, shadow_store, slot_key):
    """Gate an in-place prompt revision against the committed-artifact invariant.

    prior_text   : current contents of the mutable slot (str)
    proposed_delta: the model's proposed new text for the slot (str), NOT a diff
    window       : total token budget of the context window (int)
    reserve      : protected tail budget for the final answer (int)
    shadow_store : dict mapping slot_key -> prior_text, out-of-band
    """
    def toks(s):
        # tokenizer approximation; replace with real counter
        return len(s.split())

    prior_size = toks(prior_text)
    committed_size = toks(proposed_delta)
    slack = window - prior_size - reserve

    # Invariant 1: committed artifact must fit with reserve intact.
    if committed_size + reserve > window:
        raise BudgetInfeasibleRevision(
            f"committed post-state {committed_size} + reserve {reserve} "
            f"exceeds window {window}; edit must be emitted as a minimal diff, "
            f"not a full rewrite"
        )

    # Invariant 2: monotonic growth bounded by genuine slack.
    if committed_size > prior_size + slack:
        raise BudgetInfeasibleRevision(
            f"revision grows slot by {committed_size - prior_size} tokens "
            f"but only {slack} slack available; policy creep detected"
        )

    # Invariant 3: revert must be feasible without consuming window budget.
    if slot_key not in shadow_store:
        if slack < prior_size:
            raise BudgetInfeasibleRevision(
                f"no shadow copy of prior ({prior_size} tok) and slack "
                f"({slack} tok) insufficient to reconstruct it; revert would "
                f"be infeasible after commit"
            )
        shadow_store[slot_key] = prior_text

    # Commit only after all invariants pass.
    shadow_store[slot_key] = prior_text
    return proposed_delta
