# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a2a-v1-0-task-state-divergence-when-an-artifact-s-parts-array-is-reordered-across-a-push-notification-replay-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a2a-v1-0-task-state-divergence-when-an-artifact-s-parts-array-is-reordered-across-a-push-notification-replay-boundary.warrant.json
# Markdown SHA-256:   29d02f9db77fd77f9dd7b6c67debe1218ef2ee93e62dbd4b87168aa4fe4643f4
# Code AST SHA-256:   929e6de6e80811039a390638838543e9d543e9f593b4e67623166a5ce55734d1
# Verified Classes:   ArtifactSequenceViolation, ArtifactUpdate, ArtifactState, ArtifactLogReconstructor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class ArtifactSequenceViolation(RuntimeError):
    """Raised when a TaskArtifactUpdateEvent violates per-artifact log ordering."""
    pass


@dataclass
class ArtifactUpdate:
    task_id: str
    artifact_id: str
    event_id: str
    sequence: int          # monotonic per (task_id, artifact_id); peer-supplied or derived
    append: bool
    parts: List[str]


@dataclass
class ArtifactState:
    high_water: int = -1
    parts: List[str] = field(default_factory=list)


class ArtifactLogReconstructor:
    """Reconstructs A2A v1.0 artifacts with sequence-based idempotency.

    De-duplication keys on (task_id, artifact_id, sequence), never on content
    hash, so a re-serialized duplicate is still suppressed. Gaps and
    out-of-order appends are rejected rather than applied.
    """

    def __init__(self) -> None:
        self._state: Dict[tuple, ArtifactState] = {}

    def apply(self, upd: ArtifactUpdate) -> ArtifactState:
        key = (upd.task_id, upd.artifact_id)
        st = self._state.setdefault(key, ArtifactState())

        # Replay of an already-applied position: idempotent no-op.
        if upd.sequence <= st.high_water:
            return st

        # Gap or out-of-order: cannot safely apply an append.
        if upd.sequence != st.high_water + 1:
            raise ArtifactSequenceViolation(
                f"artifact {upd.artifact_id} expected sequence "
                f"{st.high_water + 1}, got {upd.sequence} (event {upd.event_id}); "
                f"reconcile via tasks/get before applying"
            )

        if upd.append:
            st.parts.extend(upd.parts)
        else:
            st.parts = list(upd.parts)

        st.high_water = upd.sequence
        return st

    def digest(self, task_id: str, artifact_id: str) -> str:
        st = self._state[(task_id, artifact_id)]
        return hashlib.sha256(
            json.dumps(st.parts, sort_keys=True).encode()
        ).hexdigest()


def reconcile_with_authoritative_task(
    reconstructed: List[str], authoritative_parts: List[str]
) -> None:
    """Post-condition: reconstructed artifact must equal the peer's Task."""
    if reconstructed != authoritative_parts:
        raise ArtifactSequenceViolation(
            "reconstructed artifact diverges from tasks/get authoritative content; "
            "duplicate append likely applied"
        )
