# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-peer-s-taskstate-before-accepting-an-a2a-v1-0-completed-artifact-the-input-required-re-entry-window-and-the-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-peer-s-taskstate-before-accepting-an-a2a-v1-0-completed-artifact-the-input-required-re-entry-window-and-the-artifact.warrant.json
# Markdown SHA-256:   fcca20735968b21796d468997cf803ba80ef4b86c97fb9ac596e1c1b34b8a348
# Code AST SHA-256:   2b2bbadea2888f47242280401d5108ac0828a870fd2f9b2fe933cc823b18dc61
# Verified Classes:   TaskState, ArtifactEpochMismatch, Artifact, TaskLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


class ArtifactEpochMismatch(RuntimeError):
    """Raised when a completed task's artifact set cannot be proven to belong
    to the final working epoch, or when a resumed task lacks the epoch
    provenance needed to make that proof."""


@dataclass
class Artifact:
    artifact_id: str
    epoch: int
    content_hash: str


@dataclass
class TaskLedger:
    task_id: str
    epoch: int = 0
    state: TaskState = TaskState.SUBMITTED
    artifacts: List[Artifact] = field(default_factory=list)
    streamed_since_checkpoint: bool = False

    def on_state(self, new_state: TaskState) -> None:
        if new_state == TaskState.WORKING and self.state != TaskState.WORKING:
            self.epoch += 1
        self.state = new_state

    def on_artifact(self, artifact_id: str, content_hash: str) -> None:
        # Artifacts are tagged with the epoch that produced them, not the
        # epoch observed at acceptance time.
        self.artifacts.append(
            Artifact(artifact_id=artifact_id, epoch=self.epoch, content_hash=content_hash)
        )


def accept_completed_artifacts(ledger: TaskLedger) -> List[Artifact]:
    if ledger.state != TaskState.COMPLETED:
        raise ArtifactEpochMismatch(
            f"task {ledger.task_id} not completed; state={ledger.state}"
        )
    if ledger.epoch > 1 and not ledger.streamed_since_checkpoint:
        # Multi-epoch task resumed without stream provenance: we cannot
        # distinguish final-epoch artifacts from input-required residue.
        raise ArtifactEpochMismatch(
            f"task {ledger.task_id} has {ledger.epoch} working epochs but no "
            f"stream provenance since checkpoint; artifact epoch unprovable"
        )
    final_epoch = ledger.epoch
    accepted = [a for a in ledger.artifacts if a.epoch == final_epoch]
    if not accepted:
        raise ArtifactEpochMismatch(
            f"task {ledger.task_id} completed with no artifacts in final epoch "
            f"{final_epoch}; only residue from earlier epochs present"
        )
    return accepted
