# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-compressed-handoff-lossy-summarization-contracts-and-the-provenance-floor-in-hierarchical-context-arbitration.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-compressed-handoff-lossy-summarization-contracts-and-the-provenance-floor-in-hierarchical-context-arbitration.warrant.json
# Markdown SHA-256:   bd3de15026c518c60d1f1588f87e4d2e3e4f718413874db450e4fc5284fc204b
# Code AST SHA-256:   9433a18a06b4834d7e48345065d17447d845fa71c4fda75606518725ce618c86
# Verified Classes:   HandoffRefused, Verdict, Handoff
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class HandoffRefused(RuntimeError):
    """Raised when a compressed handoff cannot be safely accepted by the child."""


class Verdict(Enum):
    ACCEPT = "accept"
    RE_EXPAND = "re_expand"
    REFUSE = "refuse"


@dataclass(frozen=True)
class Handoff:
    payload_tokens: int
    budget_tokens: int
    provenance_tag: str            # parent context version this summary was cut from
    parent_context_version: str    # current live version at the parent
    dropped_classes: FrozenSet[str]
    reexpansion_available: bool


# Classes of span that are load-bearing for a write-class task.
CRITICAL_CLASSES: FrozenSet[str] = frozenset({
    "identity_binding",     # tenant / principal the action is scoped to
    "negative_constraint",  # explicit "do not ..." guards
    "schema_discriminator", # disambiguates near-identical tool schemas
    "budget_warrant",       # spend/authority token carried across the seam
})


def arbitrate(handoff: Handoff, task_class: str) -> Verdict:
    if handoff.payload_tokens > handoff.budget_tokens:
        # A payload over budget is a compressor bug, not a child decision.
        raise HandoffRefused(
            f"payload {handoff.payload_tokens} exceeds budget "
            f"{handoff.budget_tokens}; compressor violated contract"
        )

    if task_class != "write":
        # Read-only tasks tolerate lossy summaries; gate is advisory only.
        return Verdict.ACCEPT

    if handoff.provenance_tag != handoff.parent_context_version:
        # Summary may describe a superseded state; re-expansion would be stale.
        raise HandoffRefused(
            f"provenance tag {handoff.provenance_tag!r} != live parent "
            f"version {handoff.parent_context_version!r}; summary is stale"
        )

    elided_critical = handoff.dropped_classes & CRITICAL_CLASSES
    if not elided_critical:
        return Verdict.ACCEPT

    if handoff.reexpansion_available:
        return Verdict.RE_EXPAND

    raise HandoffRefused(
        "critical classes elided with no re-expansion channel: "
        f"{sorted(elided_critical)}; refusing rather than betting on summary"
    )
