# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-learned-relevance-scorer-s-budget-allocation-across-sub-agents-when-score-provenance-is-stale.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-learned-relevance-scorer-s-budget-allocation-across-sub-agents-when-score-provenance-is-stale.warrant.json
# Markdown SHA-256:   3cd0e35e8c80f95c1597960d971c27a18d83143b439cf96dcc17ad0dd3e73f5c
# Code AST SHA-256:   e6a9dd5f16effe2202ea75acd17be9b3d4a3c125441eeb89f9b9b88b70db861d
# Verified Classes:   BudgetInvariantError, AgentState, ScoredAgent, AgentSlot
# Defensive Guards:   10 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class BudgetInvariantError(RuntimeError):
    """Raised when a proportional budget split would violate score provenance
    or evict context from a running sub-agent."""
    pass


class AgentState(Enum):
    PENDING = "pending"
    RUNNING = "running"
    DONE = "done"


@dataclass(frozen=True)
class ScoredAgent:
    agent_id: str
    score: float
    descriptor_hash: str      # hash of the task descriptor the score was computed against
    scorer_version: str
    batch_id: str
    step_index: int           # planner step at which the score was computed


@dataclass
class AgentSlot:
    agent_id: str
    state: AgentState = AgentState.PENDING
    current_budget: int = 0
    descriptor_hash: str = ""


def _h(descriptor: str) -> str:
    return hashlib.sha256(descriptor.encode()).hexdigest()[:16]


def allocate(
    total_budget: int,
    scores: list[ScoredAgent],
    slots: dict[str, AgentSlot],
    current_step: int,
    staleness_horizon: int = 0,
) -> dict[str, int]:
    """Proportional allocation with provenance and mid-execution guards.

    Returns a mapping agent_id -> new budget. Running agents are never
    reduced below their current_budget.
    """
    if not scores:
        raise BudgetInvariantError("empty score vector; cannot normalize")

    # Guard 1: common scorer version across the normalizing sum.
    versions = {s.scorer_version for s in scores}
    if len(versions) > 1:
        raise BudgetInvariantError(
            f"mixed scorer versions in normalization: {sorted(versions)}; "
            f"cross-version scores are not summable"
        )

    # Guard 2: descriptor provenance — every score must match the slot's
    # current descriptor binding.
    for s in scores:
        slot = slots.get(s.agent_id)
        if slot is None:
            raise BudgetInvariantError(f"score for unknown agent {s.agent_id}")
        if s.descriptor_hash != slot.descriptor_hash:
            raise BudgetInvariantError(
                f"stale score for {s.agent_id}: scored against "
                f"{s.descriptor_hash}, slot bound to {slot.descriptor_hash}"
            )

    # Guard 3: staleness horizon — scores must be from the current step
    # (or within the declared horizon).
    for s in scores:
        if current_step - s.step_index > staleness_horizon:
            raise BudgetInvariantError(
                f"score for {s.agent_id} is {current_step - s.step_index} steps "
                f"stale, horizon is {staleness_horizon}"
            )

    # Guard 4: running agents are committed; only the residual pool is
    # divisible. This is the guard whose absence caused the S1 eviction.
    committed = {
        aid: slot.current_budget
        for aid, slot in slots.items()
        if slot.state is AgentState.RUNNING
    }
    committed_total = sum(committed.values())
    if committed_total > total_budget:
        raise BudgetInvariantError(
            f"committed budgets ({committed_total}) exceed total ({total_budget}); "
            f"cannot honor running agents without eviction"
        )

    residual = total_budget - committed_total
    pending = [s for s in scores if s.agent_id not in committed]
    if not pending:
        return dict(committed)

    total_score = sum(s.score for s in pending)
    if total_score <= 0:
        raise BudgetInvariantError("non-positive score mass in residual pool")

    result = dict(committed)
    for s in pending:
        share = int(residual * (s.score / total_score))
        # Running agents (none here) would be floored; pending agents get share.
        prev = slots[s.agent_id].current_budget
        if slots[s.agent_id].state is AgentState.RUNNING and share < prev:
            raise BudgetInvariantError(
                f"allocation would evict {prev - share} tokens from running "
                f"agent {s.agent_id}; mid-execution subtraction is prohibited"
            )
        result[s.agent_id] = share
    return result


def apply_reallocation(
    total_budget: int,
    scores: list[ScoredAgent],
    slots: dict[str, AgentSlot],
    current_step: int,
) -> dict[str, int]:
    """Entry point used by the orchestrator on every planner edit."""
    try:
        new_budgets = allocate(total_budget, scores, slots, current_step)
    except BudgetInvariantError as e:
        # Fallback: freeze running agents, re-score only pending, allocate
        # residual pool. Never re-normalize the full mixed vector.
        raise BudgetInvariantError(
            f"proportional reallocation refused: {e}. "
            f"Fall back to reserved-pool allocation for pending agents only."
        ) from e

    # Commit and detect any reduction against a running agent.
    for aid, slot in slots.items():
        if slot.state is AgentState.RUNNING and new_budgets.get(aid, 0) < slot.current_budget:
            raise BudgetInvariantError(
                f"post-hoc reduction of running agent {aid}: "
                f"{slot.current_budget} -> {new_budgets.get(aid, 0)}"
            )
    for aid, b in new_budgets.items():
        slots[aid].current_budget = b
    return new_budgets
