# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-eviction-debt-when-a-parent-agent-reallocates-its-context-budget-mid-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-eviction-debt-when-a-parent-agent-reallocates-its-context-budget-mid-delegation.warrant.json
# Markdown SHA-256:   dcda72c21ae8bf8e60f31f859becd5b87063df76f2f1b8c47f3632870206d737
# Code AST SHA-256:   c18e8fae23f9ea90cb6cfb2ebd1105ae82fb1884575fda7fc4f26f480bfc9f6a
# Verified Classes:   EvictionDebtError, ChildState, ChildContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class EvictionDebtError(RuntimeError):
    """Raised when a forced eviction would truncate a suspended child's reasoning spine."""


class ChildState(Enum):
    RUNNING = "running"
    AWAITING_TOOL = "awaiting_tool"
    COMMITTED = "committed"


@dataclass
class ChildContext:
    child_id: str
    state: ChildState
    total_tokens: int
    spine_tokens: int          # dependency-reachable from resume anchor
    spine_floor: int           # minimum spine that must survive
    resume_anchor: str | None = None
    eviction_receipts: list = field(default_factory=list)

    @property
    def evictable_slack(self) -> int:
        return self.total_tokens - self.spine_tokens


def reclaim(parent_children: dict[str, ChildContext], target_tokens: int) -> dict[str, int]:
    """Evict only unreachable slack; refuse to touch spine of suspended children."""
    reclaimed: dict[str, int] = {}
    remaining = target_tokens

    # Only committed children expose their full spine as evictable slack.
    for cid, ctx in parent_children.items():
        if remaining <= 0:
            break
        if ctx.state is ChildState.AWAITING_TOOL:
            # Suspended: spine is untouchable until the pending call reconciles.
            continue
        take = min(ctx.evictable_slack, remaining)
        if take > 0:
            ctx.total_tokens -= take
            remaining -= take
            reclaimed[cid] = take

    if remaining > 0:
        # Do not reach into suspended spines to close the gap.
        suspended = [c for c in parent_children.values() if c.state is ChildState.AWAITING_TOOL]
        raise EvictionDebtError(
            f"reclaim short by {remaining} tokens; {len(suspended)} child(ren) suspended "
            f"with uncommitted spine. Defer or respawn, do not truncate: "
            f"{[c.child_id for c in suspended]}"
        )
    return reclaimed


def evict_suspended(child: ChildContext, drop_tokens: int) -> None:
    """Explicitly attempt to evict a suspended child's spine — always a bug."""
    if child.state is ChildState.AWAITING_TOOL and drop_tokens > child.evictable_slack:
        raise EvictionDebtError(
            f"child {child.child_id} is AWAITING_TOOL; requested drop of {drop_tokens} "
            f"exceeds slack {child.evictable_slack} and would truncate spine "
            f"(floor {child.spine_floor}). Respawn from checkpoint instead."
        )
    child.total_tokens -= drop_tokens
    child.eviction_receipts.append(f"dropped {drop_tokens} slack tokens")
