# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-rewriting-before-the-rewrite-loop-consumes-the-task-budget-it-was-meant-to-protect.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-rewriting-before-the-rewrite-loop-consumes-the-task-budget-it-was-meant-to-protect.warrant.json
# Markdown SHA-256:   fd7a98dc74ef2597b95ae71774d51d1b68b09eee985388171474ba2235ca246c
# Code AST SHA-256:   62179fc0da958ad98eb47fe4f4ded1348a01b5b96e2d7e2c8b3adf2f0fd19eeb
# Verified Classes:   RewriteBudgetViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RewriteBudgetViolation(RuntimeError):
    """Raised when a model-driven context rewrite would violate the headroom invariant."""
    pass


def authorize_rewrite(
    span_tokens: int,
    rewrite_overhead: int,
    tokens_now: int,
    context_limit: int,
    reserve_tokens: int,
    rewrite_count: int,
    max_rewrites: int,
    already_rewritten: bool,
) -> str:
    if already_rewritten:
        raise RewriteBudgetViolation(
            f"span already rewritten (terminal); re-selection would loop"
        )
    if rewrite_count >= max_rewrites:
        raise RewriteBudgetViolation(
            f"rewrite cap {max_rewrites} reached; escalate to hard truncation"
        )
    if span_tokens <= rewrite_overhead:
        # Net-negative rewrite: must evict, not rewrite.
        return "evict"

    cost = span_tokens + rewrite_overhead
    headroom = context_limit - tokens_now
    if headroom < cost + reserve_tokens:
        raise RewriteBudgetViolation(
            f"headroom {headroom} < cost {cost} + reserve {reserve_tokens}; "
            f"rewrite would consume the task budget it protects"
        )
    return "rewrite"
