# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-recover-from-a2a-v1-0-artifact-version-regressions-during-mid-task-delegation-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-recover-from-a2a-v1-0-artifact-version-regressions-during-mid-task-delegation-handoff.warrant.json
# Markdown SHA-256:   5dcfd2b7aac84b1373a39ee003d543ec8f9f16c2fc42ec1946840a1e1fea4bb4
# Code AST SHA-256:   b69ffd07d2f3fe9f7c693efa640b993b127c7fc0a6acb3804c97f95ac9c8f814
# Verified Classes:   ArtifactVersionRegression, CachedArtifact, ResumeReconciler
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class ArtifactVersionRegression(RuntimeError):
    """Raised when a cached artifact's content hash does not match the
    fresh fetch after a task resume, indicating a silent in-place mutation
    by the callee under a stable artifactId (A2A v1.0 permits this)."""


@dataclass
class CachedArtifact:
    artifact_id: str
    content_hash: str
    parts: list[dict[str, Any]]


@dataclass
class ResumeReconciler:
    cache: dict[str, CachedArtifact] = field(default_factory=dict)

    @staticmethod
    def _hash_parts(parts: list[dict[str, Any]]) -> str:
        canonical = json.dumps(parts, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()

    def cache_at_pause(self, artifact: dict[str, Any]) -> None:
        aid = artifact["artifactId"]
        parts = artifact.get("parts", [])
        self.cache[aid] = CachedArtifact(
            artifact_id=aid,
            content_hash=self._hash_parts(parts),
            parts=parts,
        )

    def reconcile_on_resume(self, fresh_task: dict[str, Any]) -> dict[str, list[dict[str, Any]]]:
        """Return authoritative artifact parts keyed by artifactId.

        Raises ArtifactVersionRegression if any cached artifact's content
        changed under a stable artifactId. The caller must treat this as a
        terminal delegation fault, not a retryable error.
        """
        authoritative: dict[str, list[dict[str, Any]]] = {}
        for artifact in fresh_task.get("artifacts", []):
            aid = artifact["artifactId"]
            parts = artifact.get("parts", [])
            fresh_hash = self._hash_parts(parts)

            cached = self.cache.get(aid)
            if cached is not None and cached.content_hash != fresh_hash:
                raise ArtifactVersionRegression(
                    f"artifact {aid} mutated in place across resume: "
                    f"cached_hash={cached.content_hash[:12]} "
                    f"fresh_hash={fresh_hash[:12]} "
                    f"cached_parts={len(cached.parts)} fresh_parts={len(parts)}"
                )
            authoritative[aid] = parts
        return authoritative
