# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-context-budget-starvation-in-shared-memory-subagent-arbitration.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-context-budget-starvation-in-shared-memory-subagent-arbitration.warrant.json
# Markdown SHA-256:   bc0ed46007e0f85107f5ab0c648d2a6d2a177843c4eb1e18e38924373e28d42d
# Code AST SHA-256:   cfc01a69dd3e9bc170302e880a11327d87c1e5db1318666bba81e68df56bcbad
# Verified Classes:   ContextStarvationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ContextStarvationError(RuntimeError):
    """Raised when a subagent's allocation falls despite stable demand."""


def arbitrate(epoch_report: dict, substrate_frozen: bool) -> dict:
    """
    epoch_report: {
        'agent': {'demand': int, 'allocated': int, 'reads': int, 'writes': int,
                  'reuse_ratio': float}
    }
    Returns per-agent allocation, or raises if starvation is structurally indicated.
    """
    for agent, m in epoch_report.items():
        read_write = m['reads'] / max(m['writes'], 1)
        demand_stable = m['demand'] == m.get('prev_demand', m['demand'])
        allocation_fell = m['allocated'] < m.get('prev_allocated', m['allocated'])

        if demand_stable and allocation_fell and read_write < 0.1 and m['reuse_ratio'] > 0.7:
            if not substrate_frozen:
                raise ContextStarvationError(
                    f"{agent}: stable demand but falling allocation "
                    f"(r/w={read_write:.2f}, reuse={m['reuse_ratio']:.2f}); "
                    f"run freeze test before adding capacity"
                )
            # Substrate frozen and still starved -> genuine exhaustion, not starvation.
    return {a: m['allocated'] for a, m in epoch_report.items()}
