# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-arbitrates-context-budget-across-subagents-that-share-a-single-working-memory-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-arbitrates-context-budget-across-subagents-that-share-a-single-working-memory-window.warrant.json
# Markdown SHA-256:   af650fdda457eaa97b3c96a64eed36d3c7f4b804e07976a689272b8f244b0fed
# Code AST SHA-256:   ba90d088490dc58075e92bae1b0fb0fb7364b7e2decdd7e50d2a8022ffa652be
# Verified Classes:   ArbitrationDeficitError, Subagent, SharedWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ArbitrationDeficitError(RuntimeError):
    """Raised when an arbitration pass would consume the state it arbitrates."""
    pass


@dataclass
class Subagent:
    name: str
    live_tokens: int
    checkpoint_handle: str | None = None


@dataclass
class SharedWindow:
    capacity: int
    subagents: dict[str, Subagent] = field(default_factory=dict)
    # Ledger is runtime-owned and excluded from the evictable pool.
    _arbitration_reserve: int = 0

    def headroom(self) -> int:
        return self.capacity - sum(s.live_tokens for s in self.subagents.values())

    def arbitrate(self, demands: dict[str, int], arbitration_cost: int) -> dict[str, int]:
        # Invariant 1: arbitration must be self-funding; never measure inside the deficit.
        h = self.headroom()
        if arbitration_cost >= h:
            raise ArbitrationDeficitError(
                f"arbitration_cost={arbitration_cost} >= headroom={h}; "
                f"refusing lossy self-measurement, shed load instead"
            )

        # Invariant 2: atomic batched check, not sequential grants.
        total_demand = sum(demands.values())
        if total_demand > h - arbitration_cost:
            raise ArbitrationDeficitError(
                f"aggregate demand {total_demand} exceeds usable headroom "
                f"{h - arbitration_cost}; overcommit would trigger silent eviction"
            )

        # Invariant 3: checkpoint before any state is moved/evicted.
        grants: dict[str, int] = {}
        for name, want in demands.items():
            sa = self.subagents[name]
            if want < sa.live_tokens and sa.checkpoint_handle is None:
                raise ArbitrationDeficitError(
                    f"subagent {name!r} would be evicted without a durable checkpoint; "
                    f"flush to storage before shrinking its budget"
                )
            grants[name] = want
        return grants
