# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewinds-a-delegated-a2a-task-to-working-after-the-peer-has-already-published-a-terminal-artifact-chunk.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewinds-a-delegated-a2a-task-to-working-after-the-peer-has-already-published-a-terminal-artifact-chunk.warrant.json
# Markdown SHA-256:   613b4a0bd7ec711d33e9491ec94c903afff6f143414824480b2d6c87bfc1afe5
# Code AST SHA-256:   43424c2db11fc0878af6e859daca81aa2210426917e32d95d1bcfab84e43e445
# Verified Classes:   A2AArtifactSeamError, TaskState, ArtifactAccumulator, A2ATaskView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class A2AArtifactSeamError(RuntimeError):
    """Raised when an artifact stream is truncated, forked, or sealed
    inconsistently with the A2A v1.0 task lifecycle."""


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


TERMINAL_STATES = {TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED}


@dataclass
class ArtifactAccumulator:
    """Per-artifactId accumulator. Reset is driven ONLY by append=False.
    status.state is never consulted here -- that is the invariant."""

    artifact_id: str
    buffer: list[str] = field(default_factory=list)
    sealed: bool = False
    saw_first_chunk: bool = False

    def apply_chunk(self, *, append: bool, last_chunk: bool, text: str) -> None:
        if self.sealed:
            raise A2AArtifactSeamError(
                f"artifact {self.artifact_id!r}: chunk arrived after seal"
            )
        if append is False:
            # The ONLY legal reset trigger.
            self.buffer.clear()
            self.saw_first_chunk = True
        else:
            if not self.saw_first_chunk:
                # append=True before any append=False means the peer's
                # cursor is ahead of ours -- we already lost the prefix.
                raise A2AArtifactSeamError(
                    f"artifact {self.artifact_id!r}: append=True before "
                    f"first chunk; stream forked (peer cursor ahead of "
                    f"local accumulator). Recovery requires a NEW taskId."
                )
        self.buffer.append(text)
        if last_chunk:
            self.sealed = True

    def seal_on_terminal(self) -> str:
        if not self.sealed:
            raise A2AArtifactSeamError(
                f"artifact {self.artifact_id!r}: task reached terminal state "
                f"without lastChunk=True; refusing to emit truncated artifact"
            )
        return "".join(self.buffer)


class A2ATaskView:
    """Parent-side view of one delegated task. Keeps control plane
    (status.state) and data plane (artifacts) strictly separate."""

    def __init__(self, task_id: str) -> None:
        self.task_id = task_id
        self.state: TaskState = TaskState.SUBMITTED
        self._artifacts: dict[str, ArtifactAccumulator] = {}

    def _acc(self, artifact_id: str) -> ArtifactAccumulator:
        if artifact_id not in self._artifacts:
            self._artifacts[artifact_id] = ArtifactAccumulator(artifact_id)
        return self._artifacts[artifact_id]

    # --- data plane ---
    def on_artifact_update(
        self, *, artifact_id: str, append: bool, last_chunk: bool, text: str
    ) -> None:
        self._acc(artifact_id).apply_chunk(
            append=append, last_chunk=last_chunk, text=text
        )

    # --- control plane ---
    def on_status_update(self, state: TaskState) -> None:
        # NOTE: deliberately does NOT touch any accumulator.
        self.state = state
        if state in TERMINAL_STATES:
            self._seal_all_on_terminal()

    def _seal_all_on_terminal(self) -> None:
        if self.state != TaskState.COMPLETED:
            # failed/canceled: discard unsealed, do not emit partials
            for acc in self._artifacts.values():
                if not acc.sealed:
                    acc.buffer.clear()
            return
        for acc in self._artifacts.values():
            acc.seal_on_terminal()  # raises if truncated

    def on_resubscribe(self) -> None:
        # Resubscribe is a resume-from-cursor, NOT a rewind.
        # Resetting accumulators here is the bug this article documents.
        return

    def finalize(self, artifact_id: str) -> str:
        acc = self._artifacts.get(artifact_id)
        if acc is None:
            raise A2AArtifactSeamError(f"unknown artifact {artifact_id!r}")
        return acc.seal_on_terminal()


def replay_heartbeat_seam() -> None:
    """Reproduces the documented failure: a working heartbeat must not
    reset the accumulator, and a resubscribe must not rewind it."""
    view = A2ATaskView(task_id="T")
    view.on_status_update(TaskState.WORKING)
    view.on_artifact_update(
        artifact_id="report", append=False, last_chunk=False, text="<8KB>"
    )
    # heartbeat interleaved with stream -- must be a no-op for data plane
    view.on_status_update(TaskState.WORKING)
    view.on_resubscribe()
    # peer resumes from its own cursor: next chunk is append=True
    view.on_artifact_update(
        artifact_id="report", append=True, last_chunk=True, text="<32KB>"
    )
    view.on_status_update(TaskState.COMPLETED)
    out = view.finalize("report")
    if not out.startswith("<8KB>"):
        raise A2AArtifactSeamError(
            "artifact prefix lost: accumulator was reset by a status "
            "heartbeat or resubscribe; stream forked from peer cursor"
        )


if __name__ == "__main__":
    replay_heartbeat_seam()
