# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reject-a-valid-a2a-task-update-after-the-remote-agent-card-s-push-notification-binding-silently-downgrades-taskid-correlation-to.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reject-a-valid-a2a-task-update-after-the-remote-agent-card-s-push-notification-binding-silently-downgrades-taskid-correlation-to.warrant.json
# Markdown SHA-256:   67fad6118fbef37739dc3e0752f2bd7b1813fa22c21b2ed08f3bedc9974b7e20
# Code AST SHA-256:   b08a8a2b3638e0c7cd1a99b0e974117d2dd8f9e9c7faa17e8466d06193b712a4
# Verified Classes:   PushCorrelationMismatch, TaskCorrelator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PushCorrelationMismatch(RuntimeError):
    """Raised when a push event cannot be correlated to an in-flight task
    via the composite (taskId, contextId) key, and reconciliation is required."""
    pass


class TaskCorrelator:
    def __init__(self, agent_card: dict):
        binding = agent_card.get("pushNotifications") or {}
        # The card advertises capability, not envelope shape. We must record
        # that the shape is unverified and force reconciliation on first miss.
        self.envelope_shape_verified = False
        self.pending = {}  # (task_id, context_id) -> state

    def register(self, task_id: str, context_id: str) -> None:
        self.pending[(task_id, context_id)] = "submitted"

    def on_push_event(self, event: dict) -> str:
        payload = event.get("payload", {})
        task_id = payload.get("taskId") or payload.get("id")
        context_id = payload.get("contextId")
        if not task_id or not context_id:
            # Cannot correlate. Do NOT drop. Escalate to reconciliation.
            raise PushCorrelationMismatch(
                f"push event missing composite key: taskId={task_id!r} "
                f"contextId={context_id!r}; must reconcile via tasks/get"
            )
        key = (task_id, context_id)
        if key not in self.pending:
            raise PushCorrelationMismatch(
                f"push event for unknown composite key {key}; "
                f"possible taskId reuse across context or stale event"
            )
        new_state = payload.get("state")
        if new_state not in {"working", "completed", "failed", "canceled", "input-required"}:
            raise PushCorrelationMismatch(
                f"unrecognized state {new_state!r} for {key}; "
                f"envelope shape may have rotated since discovery"
            )
        self.pending[key] = new_state
        return new_state
