# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-s-capability-attestation-as-a-lease-not-a-fact-during-a2a-v1-0-task-lifecycle-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-s-capability-attestation-as-a-lease-not-a-fact-during-a2a-v1-0-task-lifecycle-negotiation.warrant.json
# Markdown SHA-256:   c1d6b33ae0d0ab87f8b9c478b0b1ef41edb98aaea77d83406f9b178beadcd4af
# Code AST SHA-256:   686bbf54fe912e79173fe04366a48bacc2c18b26b8569c47ff258a2934745460
# Verified Classes:   CapabilityAttestationError, TaskState, AgentCard, Task
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum


class CapabilityAttestationError(RuntimeError):
    """Raised when a peer's capability attestation cannot bound a task result."""
    pass


class TaskState(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    COMPLETED = "completed"
    FAILED = "failed"
    UNVERIFIED = "unverified"


@dataclass
class AgentCard:
    peer_id: str
    skills: frozenset
    issuer_vendor: str
    fetched_at: datetime
    ttl: timedelta


@dataclass
class Task:
    task_id: str
    peer_id: str
    dispatched_skill: str
    caller_vendor: str
    card_snapshot: AgentCard
    state: TaskState = TaskState.SUBMITTED


def commit_result(
    task: Task,
    refreshed_card: AgentCard | None,
    now: datetime,
) -> TaskState:
    """Enforce lifecycle-scoped attestation at the completed transition.

    The capability that authorized dispatch must still be valid when the
    peer commits output, or the result is unverifiable.
    """
    if task.state is not TaskState.WORKING:
        raise CapabilityAttestationError(
            f"task {task.task_id} not in WORKING; cannot commit from {task.state}"
        )

    cross_vendor = task.card_snapshot.issuer_vendor != task.caller_vendor
    age = now - task.card_snapshot.fetched_at
    lease_expired = age > task.card_snapshot.ttl

    needs_recheck = cross_vendor and lease_expired

    if not needs_recheck:
        task.state = TaskState.COMPLETED
        return task.state

    if refreshed_card is None:
        # Peer unreachable at commit: do not silently accept.
        task.state = TaskState.UNVERIFIED
        return task.state

    if refreshed_card.issuer_vendor != task.card_snapshot.issuer_vendor:
        raise CapabilityAttestationError(
            f"issuer vendor changed for peer {task.peer_id}: "
            f"{task.card_snapshot.issuer_vendor} -> {refreshed_card.issuer_vendor}"
        )

    if task.dispatched_skill not in refreshed_card.skills:
        # Capability revoked mid-flight; preserve artifact for reconciliation.
        task.state = TaskState.FAILED
        return task.state

    task.state = TaskState.COMPLETED
    return task.state
