# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-token-budget-starvation-is-imminent-in-context-orchestration.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-token-budget-starvation-is-imminent-in-context-orchestration.warrant.json
# Markdown SHA-256:   044c54376d1d0781eb2429238063339cf94ec72c4fc749bb6a1826b8904c866d
# Code AST SHA-256:   fc15ee8cc1e28097d58ff90645d4d373a790a56c49245b1b5745335b15619353
# Verified Classes:   ContextStarvationError, ContextBudget
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ContextStarvationError(RuntimeError):
    """Raised when the mandatory context floor leaves no reserve for the next append."""
    pass


@dataclass
class ContextBudget:
    window: int
    system_tokens: int
    tool_schema_tokens: int
    min_working_set_tokens: int
    reserve_fraction: float = 0.15

    @property
    def mandatory_floor(self) -> int:
        return self.system_tokens + self.tool_schema_tokens + self.min_working_set_tokens

    @property
    def reserve(self) -> int:
        return int(self.window * self.reserve_fraction)


def assert_headroom(budget: ContextBudget, expected_next_append: int) -> None:
    """Validate that the next mandatory append fits with reserve intact.

    Must be called BEFORE any trimming loop. Trimming cannot fix starvation.
    """
    projected = budget.mandatory_floor + expected_next_append
    ceiling = budget.window - budget.reserve
    if budget.mandatory_floor >= ceiling:
        raise ContextStarvationError(
            f"Mandatory floor {budget.mandatory_floor} >= ceiling {ceiling} "
            f"(window={budget.window}, reserve={budget.reserve}). "
            f"Trimming is unsafe; take a structural action."
        )
    if projected >= ceiling:
        raise ContextStarvationError(
            f"Projected {projected} >= ceiling {ceiling} after next append "
            f"of {expected_next_append}. Compress memory to floor before proceeding."
        )
