# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-a2a-task-state-resumption-as-a-two-phase-commit-against-its-own-checkpoint-rather-than-trusting-the-peer-s-taskstatusupda.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-a2a-task-state-resumption-as-a-two-phase-commit-against-its-own-checkpoint-rather-than-trusting-the-peer-s-taskstatusupda.warrant.json
# Markdown SHA-256:   23bed1fe9cf6d127e1ad2cc66e86f536459c6ffd8c2d24a2dd0051128cd9513c
# Code AST SHA-256:   59f61b360aeea2fdac712687b669875fda778e347a3b9ddc722ddec328f08406
# Verified Classes:   A2ACommitViolation, LocalCommitState, TaskRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class A2ACommitViolation(RuntimeError):
    """Raised when a terminal remote event is used as the sole authority for local commit."""
    pass


class LocalCommitState(Enum):
    PENDING = "pending"
    COMMITTED = "committed"


@dataclass
class TaskRecord:
    remote_task_id: str
    remote_state: str = "working"
    local_commit_state: LocalCommitState = LocalCommitState.PENDING
    committed_steps: set = field(default_factory=set)
    seen_event_ids: set = field(default_factory=set)


def make_event_id(remote_task_id: str, state: str, seq: int) -> str:
    return hashlib.sha256(f"{remote_task_id}:{state}:{seq}".encode()).hexdigest()


def handle_terminal_event(
    record: TaskRecord,
    event_id: str,
    remote_state: str,
    pipeline_steps: list,
    execute_step,
) -> TaskRecord:
    """
    Two-phase handling of a terminal TaskStatusUpdateEvent.

    Prepare: record the remote terminality and the event ID, but do NOT
    advance local_commit_state. Re-enter the pipeline at the first
    uncommitted step. Commit only after every step has durably committed.
    """
    if remote_state != "completed":
        record.remote_state = remote_state
        return record

    # Idempotent redelivery: a duplicate terminal event is a no-op.
    if event_id in record.seen_event_ids:
        return record
    record.seen_event_ids.add(event_id)
    record.remote_state = "completed"

    # GUARDRAIL: refuse to mark committed on the basis of remote_state alone.
    if record.local_commit_state is LocalCommitState.COMMITTED:
        # Already committed locally; nothing to do. This is the only safe
        # path to a committed state on a terminal event.
        return record

    # Prepare phase: resume the local pipeline from the first uncommitted step.
    for step in pipeline_steps:
        if step.name in record.committed_steps:
            continue
        execute_step(step)  # must be idempotent under replay via step key
        record.committed_steps.add(step.name)

    # Commit phase: only now may local state advance.
    if len(record.committed_steps) != len(pipeline_steps):
        raise A2ACommitViolation(
            f"remote task {record.remote_task_id} reported completed but "
            f"local pipeline has {len(pipeline_steps) - len(record.committed_steps)} "
            f"uncommitted steps; refusing to advance local_commit_state"
        )
    record.local_commit_state = LocalCommitState.COMMITTED
    return record
