# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-priority-inheritance-when-nested-sub-agents-re-budget-a-shared-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-priority-inheritance-when-nested-sub-agents-re-budget-a-shared-context-window.warrant.json
# Markdown SHA-256:   51972dde0381e4aedc755560d08d7bc7f48400e42445467863b9a554e9c6ed3c
# Code AST SHA-256:   1b2c27e12dc3852f95a92d294d9dd8b8782ed04abbbe7e4fdb7761c6804140cd
# Verified Classes:   PriorityInheritanceViolation, InheritedItem, DelegationEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class PriorityInheritanceViolation(RuntimeError):
    """Raised when a sub-agent's budget allocation would evict an inherited
    priority-0 item below its reserved floor, or when the residual scratch
    budget after pre-allocating inherited floors is negative."""
    pass


@dataclass(frozen=True)
class InheritedItem:
    name: str
    priority: int          # 0 = highest
    reserved_floor: int    # tokens that must survive at every descendant


@dataclass
class DelegationEnvelope:
    total_budget: int
    inherited: list[InheritedItem] = field(default_factory=list)
    min_viable_scratch: int = 512


def plan_child_budget(env: DelegationEnvelope, child_local_slices: dict[str, int]) -> dict[str, int]:
    """Pre-allocate inherited floors, then draw child slices from the residual.
    Fails closed if the residual cannot cover the child's declared slices."""
    inherited_total = sum(i.reserved_floor for i in env.inherited)
    residual = env.total_budget - inherited_total

    if residual < env.min_viable_scratch:
        raise PriorityInheritanceViolation(
            f"infeasible spawn: inherited floors={inherited_total} leave "
            f"residual={residual} < min_viable_scratch={env.min_viable_scratch}; "
            f"refusing to delegate (would evict {[i.name for i in env.inherited if i.priority == 0]})"
        )

    requested = sum(child_local_slices.values())
    if requested > residual:
        raise PriorityInheritanceViolation(
            f"child slices request {requested} tokens but only {residual} residual "
            f"available after inherited floors; child must not draw from inherited budget"
        )

    allocation = {i.name: i.reserved_floor for i in env.inherited}
    allocation.update(child_local_slices)
    return allocation


def verify_return_ledger(env: DelegationEnvelope, child_reported_survivors: set[str]) -> None:
    """Structural check: every inherited item the parent sent must appear in the
    child's reported survivors. Trust the set comparison, not the child's prose."""
    required = {i.name for i in env.inherited}
    missing = required - child_reported_survivors
    if missing:
        raise PriorityInheritanceViolation(
            f"return ledger reports inherited items evicted at depth: {sorted(missing)}; "
            f"child result is untrustworthy for constrained output"
        )
