# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-silently-corrupting-their-own-rewrite-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-silently-corrupting-their-own-rewrite-budget.warrant.json
# Markdown SHA-256:   ecbb2ef02a1fbd1d1aec5b29911a7e608e13b061456e3225be5f3f24bbdea814
# Code AST SHA-256:   6490c146259ba0b04233480e635b2d603d7510583933990ddedec032c0e4c24f
# Verified Classes:   RewriteBudgetViolation, RewritePlan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RewriteBudgetViolation(RuntimeError):
    """Raised when a self-editing context rewrite cannot prove a non-negative net token delta.

    This is a pre-commit gate, not a post-hoc check. If the conservation
    identity cannot be proven from attributed deltas, the rewrite must be
    rejected rather than committed on an estimate.
    """
    pass


class RewritePlan:
    def __init__(self, tokens_freed: int, rewrite_cost: int, measurement_cost: int,
                 touched_own_substrate: bool):
        self.tokens_freed = tokens_freed
        self.rewrite_cost = rewrite_cost
        self.measurement_cost = measurement_cost
        self.touched_own_substrate = touched_own_substrate


def commit_rewrite(plan: RewritePlan, budget_slack: int) -> int:
    """Return net tokens freed, or raise if the rewrite is unsound.

    Preconditions enforced here:
      1. The plan must not have edited its own decision substrate this turn.
      2. The conservation identity must be provable from attributed deltas.
      3. Net delta must be strictly positive (a zero-net rewrite is churn).
    """
    if plan.touched_own_substrate:
        raise RewriteBudgetViolation(
            "plan edited its own rationale/plan artifacts; self-reference loop reachable"
        )

    net = plan.tokens_freed - plan.rewrite_cost - plan.measurement_cost

    if plan.tokens_freed < 0 or plan.rewrite_cost < 0 or plan.measurement_cost < 0:
        raise RewriteBudgetViolation(
            f"unattributed cost component in plan: {plan.__dict__}"
        )

    if net <= 0:
        raise RewriteBudgetViolation(
            f"rewrite does not conserve budget: freed={plan.tokens_freed} "
            f"rewrite_cost={plan.rewrite_cost} measurement_cost={plan.measurement_cost} "
            f"net={net} slack={budget_slack}"
        )

    return net


# Example: a plan that "saves" 400 but costs 380 to plan and 90 to measure.
try:
    commit_rewrite(
        RewritePlan(tokens_freed=400, rewrite_cost=380, measurement_cost=90,
                    touched_own_substrate=False),
        budget_slack=50,
    )
except RewriteBudgetViolation as e:
    # Correct outcome: reject and degrade to no-op / escalate out-of-band.
    print(f"rejected: {e}")
