# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-arbitrate-a-shared-context-window-when-priority-inheritance-inverts-under-sub-agent-starvation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-arbitrate-a-shared-context-window-when-priority-inheritance-inverts-under-sub-agent-starvation.warrant.json
# Markdown SHA-256:   ed3444bf48b2849e15958e85753bf0b31731b7c920db19c99a6930618b76aea3
# Code AST SHA-256:   14ac9b239639c2b56c1e516b2f9c49b0c07968d9613dd1bdd3ce59415a01c35e
# Verified Classes:   BudgetArbitrationError, InheritanceMode, SubAgent, SharedWindow
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class BudgetArbitrationError(RuntimeError):
    """Raised when priority inheritance would grow a holder's context."""


class InheritanceMode(Enum):
    COMPUTE_DIRECTED = "compute_directed"   # forbidden: raises quantum
    COMPACTION_DIRECTED = "compaction_directed"  # required: sets deadline


@dataclass
class SubAgent:
    name: str
    priority: int
    working_set_tokens: int
    effective_priority: int = field(init=False)

    def __post_init__(self) -> None:
        self.effective_priority = self.priority


@dataclass
class SharedWindow:
    soft_cap: int
    emergency_reserve: int

    def headroom(self, holder: SubAgent) -> int:
        return self.soft_cap - holder.working_set_tokens


def arbitrate(
    waiter: SubAgent,
    holder: SubAgent,
    request_tokens: int,
    window: SharedWindow,
    mode: InheritanceMode,
) -> str:
    """Grant the waiter's request or direct the holder to compact.

    Enforces the invariant: inheritance must never increase holder capacity.
    """
    if waiter.priority <= holder.priority:
        raise BudgetArbitrationError(
            f"waiter {waiter.name} priority {waiter.priority} not above "
            f"holder {holder.name} priority {holder.priority}; no inheritance needed"
        )

    pre_inheritance_size = holder.working_set_tokens

    if mode is InheritanceMode.COMPUTE_DIRECTED:
        # Simulate the forbidden path: donation raises quantum, holder grows.
        holder.effective_priority = waiter.priority
        projected_growth = request_tokens // 2  # empirical: hot holders expand
        holder.working_set_tokens += projected_growth
        if holder.working_set_tokens > pre_inheritance_size:
            raise BudgetArbitrationError(
                f"invariant violated: inheritance grew holder {holder.name} "
                f"from {pre_inheritance_size} to {holder.working_set_tokens} tokens; "
                f"waiter {waiter.name} starved"
            )

    # COMPACTION_DIRECTED: transfer urgency, not capacity.
    target = window.soft_cap - request_tokens - window.emergency_reserve
    if target < 0:
        raise BudgetArbitrationError(
            f"request {request_tokens} exceeds achievable target {target}; "
            f"waiter {waiter.name} must degrade allocation"
        )
    holder.effective_priority = waiter.priority  # urgency only
    holder.working_set_tokens = min(holder.working_set_tokens, target)
    if holder.working_set_tokens > pre_inheritance_size:
        raise BudgetArbitrationError(
            f"compaction raised holder size; scheduler bug in {holder.name}"
        )
    return f"compacted {holder.name} to {holder.working_set_tokens} tokens; waiter unblocked"
