# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-a2a-task-resumption-from-silently-re-executing-a-signed-artifact-after-card-re-discovery.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-a2a-task-resumption-from-silently-re-executing-a-signed-artifact-after-card-re-discovery.warrant.json
# Markdown SHA-256:   effb10d412df5438af3d2c736d8ef2cbb5dd8e64f5453f87982643f3a7940164
# Code AST SHA-256:   e3760e5529f785d492e0da0e8824f8ba84229be2a00c2e59f7959adeaf20d423
# Verified Classes:   ArtifactKeyDriftError, TaskEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, List, Tuple


class ArtifactKeyDriftError(RuntimeError):
    """Raised when an in-flight A2A task receives an artifact signed under a
    key that was not part of the task's originally negotiated key set.

    This is the guardrail against silent re-execution after Agent Card
    re-discovery (e.g. remote signing-key rotation mid-task). The card may be
    authentic; the artifact is still unauthorized for *this* task.
    """


@dataclass
class TaskEnvelope:
    task_id: str
    epoch: int
    negotiated_kids: FrozenSet[str]
    artifact_ledger: List[Tuple[str, str, str]] = field(default_factory=list)

    def accept_artifact(self, artifact_id: str, kid: str, state: str) -> None:
        if kid not in self.negotiated_kids:
            raise ArtifactKeyDriftError(
                f"task {self.task_id!r} epoch {self.epoch}: artifact "
                f"{artifact_id!r} signed under kid {kid!r} which is not in "
                f"negotiated set {sorted(self.negotiated_kids)!r}. "
                f"Card re-discovery does not extend in-flight authorization; "
                f"call renegotiate() to open a new epoch."
            )
        if any(a == artifact_id for a, _, _ in self.artifact_ledger):
            raise ArtifactKeyDriftError(
                f"task {self.task_id!r}: artifact {artifact_id!r} already "
                f"recorded in ledger; duplicate delivery indicates remote "
                f"re-executed the task after card rotation."
            )
        self.artifact_ledger.append((artifact_id, kid, state))

    def renegotiate(self, new_kids: FrozenSet[str], new_epoch: int) -> "TaskEnvelope":
        # Explicit, logged transition — never inferred from card re-discovery.
        if new_epoch <= self.epoch:
            raise ArtifactKeyDriftError(
                f"task {self.task_id!r}: renegotiation must advance epoch "
                f"(current {self.epoch}, requested {new_epoch})."
            )
        return TaskEnvelope(
            task_id=self.task_id,
            epoch=new_epoch,
            negotiated_kids=new_kids,
            artifact_ledger=list(self.artifact_ledger),
        )


def handle_artifact_receipt(
    envelope: TaskEnvelope, artifact_id: str, kid: str, state: str
) -> TaskEnvelope:
    envelope.accept_artifact(artifact_id, kid, state)
    return envelope
