# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-artifact-lineage-when-a2a-v1-0-task-negotiation-re-binds-taskid-across-a-resumed-input-required-state.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-artifact-lineage-when-a2a-v1-0-task-negotiation-re-binds-taskid-across-a-resumed-input-required-state.warrant.json
# Markdown SHA-256:   09f1ee0ef5b9a2d8f87e8a53abcf03bae35f3ab3cf9e01ddf252fbee67b543f0
# Code AST SHA-256:   200daa75add76deac45f232f6ebf17475f75a7d55fe959e9f90efd728aff323a
# Verified Classes:   ArtifactLineageError, Artifact, TaskStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ArtifactLineageError(RuntimeError):
    """Raised when an artifact's append reference does not resolve within its task lineage."""
    pass

@dataclass
class Artifact:
    artifact_id: str
    task_id: str
    context_id: str
    append: bool
    ref: Optional[str] = None

@dataclass
class TaskStore:
    by_context: dict = field(default_factory=dict)   # contextId -> taskId
    artifacts: dict = field(default_factory=dict)    # artifactId -> Artifact

    def rehydrate_task_id(self, context_id: str) -> str:
        # Continuity key: derived ONLY from the task store, never from the Agent Card.
        if context_id not in self.by_context:
            raise ArtifactLineageError(
                f"no persisted taskId for contextId={context_id}; "
                f"refusing to re-derive from discovery"
            )
        return self.by_context[context_id]

    def accept_artifact(self, art: Artifact) -> None:
        if art.append and art.ref is not None:
            target = self.artifacts.get(art.ref)
            if target is None:
                raise ArtifactLineageError(
                    f"append target {art.ref} unknown for artifact {art.artifact_id}"
                )
            if target.task_id != art.task_id:
                # The exact failure mode: server resumed by contextId, minted a new
                # taskId, and emitted an append pointing across the lineage boundary.
                raise ArtifactLineageError(
                    f"lineage split: {art.artifact_id} (task={art.task_id}) "
                    f"appends to {art.ref} (task={target.task_id}) under "
                    f"context={art.context_id}; reconcile before storing"
                )
        self.artifacts[art.artifact_id] = art

def resume_turn(store: TaskStore, context_id: str, incoming: Artifact) -> None:
    expected = store.rehydrate_task_id(context_id)
    if incoming.task_id != expected:
        raise ArtifactLineageError(
            f"taskId drift on resume: expected {expected}, got {incoming.task_id}"
        )
    store.accept_artifact(incoming)

# Repro of the observed failure:
store = TaskStore()
store.by_context["ctx_7f"] = "tsk_01H"
store.accept_artifact(Artifact("art_a", "tsk_01H", "ctx_7f", append=False))
# Server minted tsk_01J after a card-version cache miss on the client:
resume_turn(store, "ctx_7f", Artifact("art_b", "tsk_01J", "ctx_7f", append=True, ref="art_a"))
# -> ArtifactLineageError: taskId drift on resume: expected tsk_01H, got tsk_01J
