# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-agent-card-capability-claims-against-observed-task-state-transitions-when-an-a2a-v1-0-peer-advertises-input-required.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-agent-card-capability-claims-against-observed-task-state-transitions-when-an-a2a-v1-0-peer-advertises-input-required.warrant.json
# Markdown SHA-256:   d0341ba5a1664af6747d91ff9c74f4f4e6378e0422badc335e754ece1fcbf2d9
# Code AST SHA-256:   82d616b1f80b72a906e978316eacc3683dd072fad5182c42fc869df0fe245e1e
# Verified Classes:   A2ATransitionConformanceError, TaskStatusEvent, TaskHandle
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class A2ATransitionConformanceError(RuntimeError):
    """Raised when a peer violates its advertised state-transition contract."""


@dataclass
class TaskStatusEvent:
    state: str                 # submitted | working | input-required | completed | failed | canceled
    final: bool
    status_message: str
    history_len: int
    progress_token: Optional[str] = None


@dataclass
class TaskHandle:
    task_id: str
    peer: str
    declared_state_history: bool
    max_identical_resumes: int = 2
    _seen: list = field(default_factory=list)

    def _fingerprint(self, ev: TaskStatusEvent) -> str:
        h = hashlib.sha256(
            f"{ev.state}|{ev.status_message}|{ev.progress_token}".encode()
        ).hexdigest()[:16]
        return h

    def observe(self, ev: TaskStatusEvent) -> str:
        """Record an event and decide whether the peer is stalled (non-conformant)."""
        self._seen.append(ev)

        # Terminal states close the loop cleanly.
        if ev.final or ev.state in ("completed", "failed", "canceled"):
            return "terminal"

        if ev.state != "input-required":
            return "progressing"

        # Count consecutive input-required events with identical fingerprint
        # AND non-growing history. History growth => legitimate re-elicitation.
        identical = 0
        prev_hist = None
        for past in reversed(self._seen):
            if past.state != "input-required":
                break
            if prev_hist is None:
                prev_hist = past.history_len
            if self._fingerprint(past) == self._fingerprint(ev):
                identical += 1
            else:
                break

        history_grew = self._history_grew()

        if history_grew:
            # Peer is genuinely eliciting more info; reset the stall counter.
            return "progressing"

        if identical >= self.max_identical_resumes:
            if self.declared_state_history:
                raise A2ATransitionConformanceError(
                    f"peer={self.peer} task={self.task_id} claims "
                    f"stateTransitionHistory=true but history_len stayed at "
                    f"{ev.history_len} across {identical} identical "
                    f"input-required events (fingerprint={self._fingerprint(ev)}). "
                    f"Resumption edge is non-conformant; aborting rather than "
                    f"silently failing a live remote task."
                )
            # Peer never claimed history support: we cannot discriminate,
            # so we must escalate rather than guess.
            raise A2ATransitionConformanceError(
                f"peer={self.peer} task={self.task_id} repeated input-required "
                f"x{identical} with no progress token and no history signal; "
                f"cannot distinguish stall from elicitation. Escalate."
            )

        return "awaiting-input"

    def _history_grew(self) -> bool:
        lens = [e.history_len for e in self._seen if e.state == "input-required"]
        return len(lens) >= 2 and lens[-1] > lens[-2]
