# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-anchor-task-ownership-when-an-a2a-v1-0-push-notification-webhook-delivers-a-continuation-turn-to-an-agent-that-has-already-c.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-anchor-task-ownership-when-an-a2a-v1-0-push-notification-webhook-delivers-a-continuation-turn-to-an-agent-that-has-already-c.warrant.json
# Markdown SHA-256:   6a9dab691bcc83cb127699402215d5310749dd7b1f153b81aa17d54194f6b415
# Code AST SHA-256:   b6050afc95bbf5df4351cbf80929ba28f4496b22ae99af3ac96b89b45acd48a3
# Verified Classes:   ContinuationAnchorError, FrameAnchor, PushEvent, ContinuationArbiter
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional
from datetime import datetime


class ContinuationAnchorError(RuntimeError):
    """Raised when a push-bound continuation cannot be causally re-anchored."""
    pass


@dataclass
class FrameAnchor:
    task_id: str
    context_id: str
    original_intent: str
    disambiguation_axes: list[str]
    tool_ledger: list[dict]
    pending_goals: list[str]
    last_sent_turn_hash: str
    pinned: bool = True


@dataclass
class PushEvent:
    task_id: str
    context_id: str
    state: str            # "working" | "input-required" | "completed" | "failed"
    timestamp: datetime
    predecessor_turn_hash: str
    message_text: str
    final: bool = False


NON_TERMINAL = {"working", "input-required"}


class ContinuationArbiter:
    def __init__(self, anchor_store: dict[str, FrameAnchor]):
        self.anchor_store = anchor_store

    def is_evictable(self, task_id: str, state: str) -> bool:
        # Pin rule: non-terminal push-bound tasks may never be evicted.
        return state not in NON_TERMINAL

    def handle_push(self, event: PushEvent) -> str:
        if event.final or event.state not in NON_TERMINAL:
            return "terminal-ack"

        anchor: Optional[FrameAnchor] = self.anchor_store.get(event.task_id)

        if anchor is None:
            # Do NOT answer from a reconstructed summary. Fail loudly.
            raise ContinuationAnchorError(
                f"no pinned frame for task {event.task_id}; "
                f"refusing to resume from summary (would fork intent)"
            )

        if anchor.context_id != event.context_id:
            raise ContinuationAnchorError(
                f"contextId mismatch for {event.task_id}: "
                f"anchor={anchor.context_id} event={event.context_id}"
            )

        if anchor.last_sent_turn_hash != event.predecessor_turn_hash:
            raise ContinuationAnchorError(
                f"causal binding broken for {event.task_id}: "
                f"expected predecessor {anchor.last_sent_turn_hash}, "
                f"got {event.predecessor_turn_hash} (possible replay/fork)"
            )

        # Safe to resume: rehydrate full frame, not summary.
        return self._resume(anchor, event)

    def _resume(self, anchor: FrameAnchor, event: PushEvent) -> str:
        # Continuation must reference the preserved disambiguation axes.
        if not anchor.disambiguation_axes:
            raise ContinuationAnchorError(
                f"frame for {anchor.task_id} lost disambiguation axes; "
                f"cannot safely interpret continuation '{event.message_text}'"
            )
        return f"resumed:{anchor.task_id}:axes={anchor.disambiguation_axes}"
