a2a-rs 0.6.0

Rust implementation of the Agent-to-Agent (A2A) Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
//! Integration tests for SQLx storage implementation

#[cfg(feature = "sqlx-storage")]
mod sqlx_tests {
    use a2a_rs::adapter::storage::{DatabaseConfig, SqlxTaskStorage};
    use a2a_rs::domain::TaskState;
    use a2a_rs::port::{
        AsyncConversationStore, AsyncNotificationManager, AsyncStreamingHandler,
        AsyncTaskLifecycle, AsyncTaskQuery, AsyncTaskVersioning,
    };
    use a2a_rs::{A2AError, TaskPushNotificationConfig};
    use std::sync::Arc;
    use uuid::Uuid;

    fn tid(s: &str) -> a2a_rs::domain::TaskId {
        s.parse().unwrap()
    }
    fn cid(s: &str) -> a2a_rs::domain::ContextId {
        s.parse().unwrap()
    }

    async fn create_test_storage() -> Result<SqlxTaskStorage, A2AError> {
        // Use SQLite in-memory for tests
        let config = DatabaseConfig::builder()
            .url("sqlite::memory:".to_string())
            .max_connections(1)
            .build();

        SqlxTaskStorage::new(&config.url).await
    }

    /// Everything the conversation tests need to say something.
    fn said(text: &str) -> a2a_rs::domain::Message {
        use a2a_rs::domain::{Message, Part, Role};
        Message::builder()
            .role(Role::User)
            .parts(vec![Part::text(text.to_string())])
            .message_id(Uuid::new_v4().to_string())
            .build()
    }

    fn texts(conversation: &a2a_rs::domain::Conversation) -> Vec<String> {
        use a2a_rs::domain::part;
        conversation
            .tail
            .iter()
            .flat_map(|entry| {
                entry.message.parts.iter().filter_map(|p| match &p.content {
                    Some(part::Content::Text(text)) => Some(text.clone()),
                    _ => None,
                })
            })
            .collect()
    }

    /// The messages of every task in a context, in the order they were written.
    /// This is the read `mode = "context"` makes on every turn, and it goes
    /// through the denormalized `task_history.context_id` added by migration 004
    /// rather than joining `tasks`.
    #[tokio::test]
    async fn a_context_reads_back_as_one_ordered_conversation()
    -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        storage.create(&tid("t1"), &cid("c1")).await?;
        storage
            .update_status(&tid("t1"), TaskState::Working, Some(said("what is it")))
            .await?;
        storage
            .update_status(&tid("t1"), TaskState::Completed, Some(said("Oslo")))
            .await?;

        // A second task in the same context: one turn per task is the shape a
        // real conversation has.
        storage.create(&tid("t2"), &cid("c1")).await?;
        storage
            .update_status(
                &tid("t2"),
                TaskState::Completed,
                Some(said("and the population")),
            )
            .await?;

        let conversation = storage.load(&cid("c1"), None, None).await?;
        assert_eq!(
            texts(&conversation),
            vec!["what is it", "Oslo", "and the population"]
        );
        Ok(())
    }

    /// Ordering is by the history table's autoincrement id, not its timestamp.
    /// `datetime('now')` is second-resolution, so rows written inside one second
    /// used to come back in an arbitrary order — invisible while history was
    /// read for display, and wrong turns in a prompt once it is not.
    #[tokio::test]
    async fn messages_written_in_the_same_second_keep_their_order()
    -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        storage.create(&tid("t1"), &cid("c1")).await?;
        let written: Vec<String> = (0..20).map(|i| format!("message {i}")).collect();
        for text in &written {
            storage
                .update_status(&tid("t1"), TaskState::Working, Some(said(text)))
                .await?;
        }

        assert_eq!(texts(&storage.load(&cid("c1"), None, None).await?), written);
        Ok(())
    }

    #[tokio::test]
    async fn conversations_do_not_leak_between_contexts() -> Result<(), Box<dyn std::error::Error>>
    {
        let storage = create_test_storage().await?;
        storage.create(&tid("t1"), &cid("c1")).await?;
        storage.create(&tid("t2"), &cid("c2")).await?;
        storage
            .update_status(&tid("t1"), TaskState::Completed, Some(said("in one")))
            .await?;
        storage
            .update_status(&tid("t2"), TaskState::Completed, Some(said("in two")))
            .await?;

        assert_eq!(
            texts(&storage.load(&cid("c1"), None, None).await?),
            vec!["in one"]
        );
        Ok(())
    }

    /// A digest hides everything at or below its watermark. Re-loading the
    /// summarized part would double the tokens compaction exists to save.
    #[tokio::test]
    async fn a_digest_replaces_the_messages_it_covers() -> Result<(), Box<dyn std::error::Error>> {
        use a2a_rs::domain::Digest;

        let storage = create_test_storage().await?;
        storage.create(&tid("t1"), &cid("c1")).await?;
        for text in ["one", "two", "three"] {
            storage
                .update_status(&tid("t1"), TaskState::Working, Some(said(text)))
                .await?;
        }

        let before = storage.load(&cid("c1"), None, None).await?;
        storage
            .compact(
                &cid("c1"),
                None,
                Digest {
                    covers_through: before.tail[1].seq,
                    summary: "they said one and two".to_string(),
                    replaced_messages: 2,
                    model: "test".to_string(),
                },
            )
            .await?;

        let after = storage.load(&cid("c1"), None, None).await?;
        assert_eq!(after.summary(), Some("they said one and two"));
        assert_eq!(texts(&after), vec!["three"]);
        Ok(())
    }

    /// Two turns of one conversation can compact at once. Both rows land, and
    /// the digest covering more wins — which is why `load` picks by watermark
    /// rather than by the newest row.
    #[tokio::test]
    async fn concurrent_compaction_keeps_the_widest_digest()
    -> Result<(), Box<dyn std::error::Error>> {
        use a2a_rs::domain::Digest;

        let storage = create_test_storage().await?;
        storage.create(&tid("t1"), &cid("c1")).await?;
        for text in ["one", "two", "three"] {
            storage
                .update_status(&tid("t1"), TaskState::Working, Some(said(text)))
                .await?;
        }
        let loaded = storage.load(&cid("c1"), None, None).await?;

        // Widest written first, so "newest row wins" would pick the narrow one
        // and re-feed a message the summary already covers.
        for (seq, summary) in [
            (loaded.tail[2].seq, "covers all three"),
            (loaded.tail[0].seq, "covers only the first"),
        ] {
            storage
                .compact(
                    &cid("c1"),
                    None,
                    Digest {
                        covers_through: seq,
                        summary: summary.to_string(),
                        replaced_messages: 1,
                        model: "test".to_string(),
                    },
                )
                .await?;
        }

        let after = storage.load(&cid("c1"), None, None).await?;
        assert_eq!(after.summary(), Some("covers all three"));
        assert!(after.tail.is_empty(), "{:?}", texts(&after));
        Ok(())
    }

    /// Limiting keeps the newest: the older end is what a summary stands in for.
    #[tokio::test]
    async fn limiting_a_conversation_keeps_the_most_recent_messages()
    -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        storage.create(&tid("t1"), &cid("c1")).await?;
        for text in ["one", "two", "three", "four"] {
            storage
                .update_status(&tid("t1"), TaskState::Working, Some(said(text)))
                .await?;
        }

        assert_eq!(
            texts(&storage.load(&cid("c1"), None, Some(2)).await?),
            vec!["three", "four"]
        );
        Ok(())
    }

    /// Handing a conversation back makes `context_id` a capability: whoever
    /// holds one would otherwise read what was said in it. The first read
    /// claims the context; a different principal is refused.
    #[tokio::test]
    async fn a_context_belongs_to_whoever_started_it() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        storage.create(&tid("t1"), &cid("c1")).await?;
        storage
            .update_status(&tid("t1"), TaskState::Completed, Some(said("private")))
            .await?;

        storage.load(&cid("c1"), Some("alice"), None).await?;
        assert_eq!(
            texts(&storage.load(&cid("c1"), Some("alice"), None).await?),
            vec!["private"]
        );

        let err = storage
            .load(&cid("c1"), Some("mallory"), None)
            .await
            .expect_err("another principal must be refused");
        assert!(
            matches!(err, A2AError::ContextAccessDenied { .. }),
            "{err:?}"
        );
        Ok(())
    }

    /// An agent with no authenticator has no principal to claim with, and its
    /// conversations stay readable. Refusing here would break every
    /// unauthenticated deployment.
    #[tokio::test]
    async fn an_unowned_context_stays_open() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        storage.create(&tid("t1"), &cid("c1")).await?;
        storage
            .update_status(&tid("t1"), TaskState::Completed, Some(said("open")))
            .await?;

        storage.load(&cid("c1"), None, None).await?;
        assert_eq!(
            texts(&storage.load(&cid("c1"), Some("anyone"), None).await?),
            vec!["open"]
        );
        Ok(())
    }

    /// The first turn of a conversation asks for history that does not exist.
    #[tokio::test]
    async fn an_unknown_context_is_empty_rather_than_an_error()
    -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        assert!(
            storage
                .load(&cid("never-seen"), None, None)
                .await?
                .is_empty()
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_task_lifecycle() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        let task_id = Uuid::new_v4().to_string();
        let context_id = "test-context";

        // Test task creation
        let task = storage.create(&tid(&task_id), &cid(context_id)).await?;
        assert_eq!(task.id, task_id);
        assert_eq!(task.context_id, context_id);
        assert_eq!(task.status.state, TaskState::Submitted);

        // Test task existence
        assert!(storage.exists(&tid(&task_id)).await?);
        assert!(!storage.exists(&tid("non-existent")).await?);

        // Test status updates
        let working_task = storage
            .update_status(&tid(&task_id), TaskState::Working, None)
            .await?;
        assert_eq!(working_task.status.state, TaskState::Working);

        let completed_task = storage
            .update_status(&tid(&task_id), TaskState::Completed, None)
            .await?;
        assert_eq!(completed_task.status.state, TaskState::Completed);

        // Test task retrieval with history
        let retrieved_task = storage.get(&tid(&task_id), Some(10)).await?;
        assert_eq!(retrieved_task.id, task_id);
        assert_eq!(retrieved_task.status.state, TaskState::Completed);
        // Should have history: Submitted -> Working -> Completed
        // Note: We're not loading full history in the current implementation
        // assert_eq!(retrieved_task.history.len(), 3);

        Ok(())
    }

    #[tokio::test]
    async fn test_task_cancellation() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        let task_id = Uuid::new_v4().to_string();

        // Create and start working on task
        storage.create(&tid(&task_id), &cid("test-context")).await?;
        storage
            .update_status(&tid(&task_id), TaskState::Working, None)
            .await?;

        // Cancel the working task
        let canceled_task = storage.cancel(&tid(&task_id)).await?;
        assert_eq!(canceled_task.status.state, TaskState::Canceled);

        // Verify cancellation was successful
        let task_with_history = storage.get(&tid(&task_id), None).await?;
        assert_eq!(task_with_history.status.state, TaskState::Canceled);
        // Note: We're not fully implementing history loading in this version
        // In a full implementation, you'd verify the cancellation message was added

        Ok(())
    }

    /// A queued task is the clearest case, and the one the storage used to
    /// refuse: nothing has started, and a client that changed its mind has no
    /// other way to stop it. Same rule as the in-memory adapter — the two
    /// consult `TaskState::is_cancelable` rather than each carrying their own
    /// copy of it.
    #[tokio::test]
    async fn a_submitted_task_can_be_canceled() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        let task_id = Uuid::new_v4().to_string();
        storage.create(&tid(&task_id), &cid("test-context")).await?;

        let canceled = storage.cancel(&tid(&task_id)).await?;
        assert_eq!(canceled.status.state, TaskState::Canceled);
        assert_eq!(
            storage.get(&tid(&task_id), None).await?.status.state,
            TaskState::Canceled,
            "the cancellation has to reach the database, not just the response"
        );
        Ok(())
    }

    /// The agent is waiting on the caller; cancelling is how the caller says
    /// "never mind" instead of being obliged to answer.
    #[tokio::test]
    async fn an_interrupted_task_can_be_canceled() -> Result<(), Box<dyn std::error::Error>> {
        for state in [TaskState::InputRequired, TaskState::AuthRequired] {
            let storage = create_test_storage().await?;
            let task_id = Uuid::new_v4().to_string();
            storage.create(&tid(&task_id), &cid("test-context")).await?;
            storage.update_status(&tid(&task_id), state, None).await?;

            let canceled = storage.cancel(&tid(&task_id)).await?;
            assert_eq!(
                canceled.status.state,
                TaskState::Canceled,
                "cancelling from {state:?} should work"
            );
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_cannot_cancel_completed_task() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        let task_id = Uuid::new_v4().to_string();

        // Create, work on, and complete task
        storage.create(&tid(&task_id), &cid("test-context")).await?;
        storage
            .update_status(&tid(&task_id), TaskState::Working, None)
            .await?;
        storage
            .update_status(&tid(&task_id), TaskState::Completed, None)
            .await?;

        // Try to cancel completed task - should fail
        let result = storage.cancel(&tid(&task_id)).await;
        assert!(result.is_err());

        if let Err(A2AError::TaskNotCancelable(_)) = result {
            // Expected error type
        } else {
            panic!("Expected TaskNotCancelable error, got: {:?}", result);
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_duplicate_task_creation() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        let task_id = Uuid::new_v4().to_string();

        // Create first task
        storage.create(&tid(&task_id), &cid("test-context")).await?;

        // Try to create duplicate - should fail
        let result = storage.create(&tid(&task_id), &cid("test-context")).await;
        assert!(result.is_err());

        if let Err(A2AError::TaskNotFound(_)) = result {
            // Expected error type (reused for "already exists")
        } else {
            panic!(
                "Expected TaskNotFound error for duplicate, got: {:?}",
                result
            );
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_task_history_limit() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        let task_id = Uuid::new_v4().to_string();

        // Create task and make several status changes
        storage.create(&tid(&task_id), &cid("test-context")).await?;
        storage
            .update_status(&tid(&task_id), TaskState::Working, None)
            .await?;
        storage
            .update_status(&tid(&task_id), TaskState::InputRequired, None)
            .await?;
        storage
            .update_status(&tid(&task_id), TaskState::Working, None)
            .await?;
        storage
            .update_status(&tid(&task_id), TaskState::Completed, None)
            .await?;

        // Note: We're not fully implementing history loading in this version
        // In a full implementation, you'd test history limits here
        let _task_limited = storage.get(&tid(&task_id), Some(3)).await?;
        let _task_full = storage.get(&tid(&task_id), None).await?;

        Ok(())
    }

    #[tokio::test]
    async fn test_push_notifications() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        let task_id = Uuid::new_v4().to_string();

        // Create task first
        storage.create(&tid(&task_id), &cid("test-context")).await?;

        // Set push notification config
        let config = TaskPushNotificationConfig {
            tenant: String::new(),
            task_id: task_id.clone(),
            id: String::new(),
            url: "https://example.com/webhook".to_string(),
            token: String::new(),
            authentication: None.into(),
            ..Default::default()
        };

        let set_config = storage.set_config(&config).await?;
        assert_eq!(set_config.task_id, task_id);
        assert_eq!(set_config.url, "https://example.com/webhook");

        // Get push notification config
        let retrieved_config = storage
            .get_config(&a2a_rs::domain::GetTaskPushNotificationConfigParams {
                id: task_id.clone(),
                push_notification_config_id: None,
                metadata: None,
            })
            .await?;
        assert_eq!(retrieved_config.task_id, task_id);
        assert_eq!(retrieved_config.url, "https://example.com/webhook");

        // Remove push notification config
        storage
            .delete_config(&a2a_rs::domain::DeleteTaskPushNotificationConfigParams {
                id: task_id.clone(),
                push_notification_config_id: String::new(),
                metadata: None,
            })
            .await?;

        // Verify it's removed
        let result = storage
            .get_config(&a2a_rs::domain::GetTaskPushNotificationConfigParams {
                id: task_id.clone(),
                push_notification_config_id: None,
                metadata: None,
            })
            .await;
        assert!(result.is_err());

        Ok(())
    }

    #[tokio::test]
    async fn test_database_config() -> Result<(), Box<dyn std::error::Error>> {
        // Test config validation
        let valid_config = DatabaseConfig::builder()
            .url("sqlite:test.db".to_string())
            .max_connections(5)
            .timeout_seconds(10)
            .build();
        assert!(valid_config.validate().is_ok());

        // Test invalid config
        let invalid_config = DatabaseConfig::builder().url("".to_string()).build();
        assert!(invalid_config.validate().is_err());

        // Test database type detection
        use a2a_rs::adapter::storage::DatabaseType;
        assert_eq!(valid_config.database_type(), Some(DatabaseType::Sqlite));

        let postgres_config = DatabaseConfig::builder()
            .url("postgres://localhost/test".to_string())
            .build();
        assert_eq!(
            postgres_config.database_type(),
            Some(DatabaseType::Postgres)
        );

        Ok(())
    }

    /// Subscriber management is not a storage responsibility: it lives in
    /// `InMemoryStreamingHandler`. This pins the registry semantics on that
    /// adapter.
    #[tokio::test]
    async fn test_streaming_subscribers() -> Result<(), Box<dyn std::error::Error>> {
        use a2a_rs::InMemoryStreamingHandler;

        let streaming = InMemoryStreamingHandler::new();
        let task_id = Uuid::new_v4().to_string();

        // No subscribers registered for an unknown task.
        let count = streaming.get_subscriber_count(&task_id).await?;
        assert_eq!(count, 0);

        // Removing subscribers for a task with none is a no-op.
        streaming.remove_task_subscribers(&task_id).await?;

        // Removal by subscription ID is unsupported by the in-memory handler.
        let result = streaming.remove_subscription("fake-id").await;
        assert!(matches!(result, Err(A2AError::UnsupportedOperation(_))));

        Ok(())
    }

    #[tokio::test]
    async fn test_concurrent_operations() -> Result<(), Box<dyn std::error::Error>> {
        let storage = Arc::new(create_test_storage().await?);
        let mut handles = Vec::new();

        // Create multiple tasks concurrently
        for i in 0..10 {
            let storage_clone = storage.clone();
            let handle = tokio::spawn(async move {
                let task_id = format!("concurrent-task-{}", i);
                let task = storage_clone
                    .create(&tid(&task_id), &cid("concurrent-context"))
                    .await?;
                storage_clone
                    .update_status(&tid(&task_id), TaskState::Working, None)
                    .await?;
                storage_clone
                    .update_status(&tid(&task_id), TaskState::Completed, None)
                    .await?;
                Ok::<_, A2AError>(task)
            });
            handles.push(handle);
        }

        // Wait for all operations to complete
        for handle in handles {
            let result = handle.await??;
            assert_eq!(result.status.state, TaskState::Submitted); // Initial state
        }

        // Verify all tasks exist
        for i in 0..10 {
            let task_id = format!("concurrent-task-{}", i);
            assert!(storage.exists(&tid(&task_id)).await?);
            let task = storage.get(&tid(&task_id), None).await?;
            assert_eq!(task.status.state, TaskState::Completed);
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_database_migrations() -> Result<(), Box<dyn std::error::Error>> {
        // Test that migrations run successfully on a fresh database
        let config = DatabaseConfig::builder()
            .url("sqlite::memory:".to_string())
            .build();

        // This should run migrations internally
        let _storage = SqlxTaskStorage::new(&config.url).await?;

        // Create another instance with the same URL - should not fail
        let _storage2 = SqlxTaskStorage::new(&config.url).await?;

        Ok(())
    }

    // ===== v1.0.0 Tests =====

    #[tokio::test]
    async fn test_list_tasks_v3_basic() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;

        // Create some tasks
        for i in 0..5 {
            let task_id = format!("task-{}", i);
            storage.create(&tid(&task_id), &cid("test-context")).await?;
        }

        // List all tasks
        let params = a2a_rs::domain::ListTasksParams::default();
        let result = storage.list(&params).await?;

        assert_eq!(result.total_size, 5, "Should have 5 tasks");
        assert_eq!(result.tasks.len(), 5, "Should return 5 tasks");
        assert_eq!(result.page_size, 50, "Default page size should be 50");

        Ok(())
    }

    #[tokio::test]
    async fn test_list_tasks_v3_filtering() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;

        // Create tasks in different contexts and states
        storage.create(&tid("task-a-1"), &cid("context-a")).await?;
        storage.create(&tid("task-a-2"), &cid("context-a")).await?;
        storage.create(&tid("task-b-1"), &cid("context-b")).await?;

        storage
            .update_status(&tid("task-a-1"), TaskState::Working, None)
            .await?;
        storage
            .update_status(&tid("task-a-2"), TaskState::Completed, None)
            .await?;

        // Filter by context
        let params = a2a_rs::domain::ListTasksParams {
            context_id: Some("context-a".to_string()),
            ..Default::default()
        };
        let result = storage.list(&params).await?;
        assert_eq!(result.total_size, 2, "Should have 2 tasks in context-a");

        // Filter by status
        let params = a2a_rs::domain::ListTasksParams {
            status: Some(TaskState::Working),
            ..Default::default()
        };
        let result = storage.list(&params).await?;
        assert_eq!(result.total_size, 1, "Should have 1 working task");

        Ok(())
    }

    #[tokio::test]
    async fn test_list_tasks_v3_pagination() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;

        // Create 10 tasks
        for i in 0..10 {
            storage
                .create(&tid(&format!("task-{}", i)), &cid("test-context"))
                .await?;
        }

        // Get first page
        let params = a2a_rs::domain::ListTasksParams {
            page_size: Some(3),
            ..Default::default()
        };
        let page1 = storage.list(&params).await?;
        assert_eq!(page1.tasks.len(), 3, "Should return 3 tasks");
        assert!(
            !page1.next_page_token.is_empty(),
            "Should have next page token"
        );

        // Get second page
        let params = a2a_rs::domain::ListTasksParams {
            page_size: Some(3),
            page_token: Some(page1.next_page_token.clone()),
            ..Default::default()
        };
        let page2 = storage.list(&params).await?;
        assert_eq!(page2.tasks.len(), 3, "Should return 3 tasks");

        Ok(())
    }

    #[tokio::test]
    async fn test_push_notification_config_v3_crud() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        let task_id = Uuid::new_v4().to_string();

        // Create task first
        storage.create(&tid(&task_id), &cid("test-context")).await?;

        // Set push notification config
        let config = TaskPushNotificationConfig {
            tenant: String::new(),
            task_id: task_id.clone(),
            id: "config-1".to_string(),
            url: "https://example.com/webhook".to_string(),
            token: "test-token".to_string(),
            authentication: None.into(),
            ..Default::default()
        };
        storage.set_config(&config).await?;

        // Get specific config
        let get_params = a2a_rs::domain::GetTaskPushNotificationConfigParams {
            id: task_id.clone(),
            push_notification_config_id: Some("config-1".to_string()),
            metadata: None,
        };
        let retrieved = storage.get_config(&get_params).await?;
        assert_eq!(retrieved.url, "https://example.com/webhook");
        assert_eq!(retrieved.token, "test-token");

        // List configs
        let list_params = a2a_rs::domain::ListTaskPushNotificationConfigsParams {
            id: task_id.clone(),
            metadata: None,
        };
        let configs = storage.list_configs(&list_params).await?;
        assert_eq!(configs.len(), 1, "Should have 1 config");

        // Delete config
        let delete_params = a2a_rs::domain::DeleteTaskPushNotificationConfigParams {
            id: task_id.clone(),
            push_notification_config_id: "config-1".to_string(),
            metadata: None,
        };
        storage.delete_config(&delete_params).await?;

        // Verify deleted
        let configs = storage.list_configs(&list_params).await?;
        assert_eq!(configs.len(), 0, "Config should be deleted");

        Ok(())
    }

    #[tokio::test]
    async fn test_push_notification_config_v3_multiple() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        let task_id = Uuid::new_v4().to_string();

        // Create task
        storage.create(&tid(&task_id), &cid("test-context")).await?;

        // Set multiple configs
        let config1 = TaskPushNotificationConfig {
            tenant: String::new(),
            task_id: task_id.clone(),
            id: "config-1".to_string(),
            url: "https://example.com/webhook1".to_string(),
            token: String::new(),
            authentication: None.into(),
            ..Default::default()
        };
        let config2 = TaskPushNotificationConfig {
            tenant: String::new(),
            task_id: task_id.clone(),
            id: "config-2".to_string(),
            url: "https://example.com/webhook2".to_string(),
            token: "token-2".to_string(),
            authentication: None.into(),
            ..Default::default()
        };

        storage.set_config(&config1).await?;
        storage.set_config(&config2).await?;

        // List should return both
        let list_params = a2a_rs::domain::ListTaskPushNotificationConfigsParams {
            id: task_id.clone(),
            metadata: None,
        };
        let configs = storage.list_configs(&list_params).await?;
        assert_eq!(configs.len(), 2, "Should have 2 configs");

        Ok(())
    }

    #[tokio::test]
    async fn test_optimistic_concurrency_versioning() -> Result<(), Box<dyn std::error::Error>> {
        let storage = create_test_storage().await?;
        let task_id = Uuid::new_v4().to_string();

        // A freshly created task starts at version 1.
        storage.create(&tid(&task_id), &cid("ctx")).await?;
        assert_eq!(storage.version(&tid(&task_id)).await?, 1);

        // Every unversioned mutation bumps the version too.
        storage
            .update_status(&tid(&task_id), TaskState::Working, None)
            .await?;
        let snapshot = storage.get_versioned(&tid(&task_id), None).await?;
        assert_eq!(snapshot.version, 2);
        assert_eq!(snapshot.task.status.state, TaskState::Working);

        // A conditional update with the stale version is rejected, untouched.
        let stale = storage
            .update_status_checked(&tid(&task_id), 1, TaskState::Completed, None)
            .await;
        match stale {
            Err(A2AError::VersionConflict {
                expected, actual, ..
            }) => {
                assert_eq!(expected, 1);
                assert_eq!(actual, 2);
            }
            other => panic!("expected VersionConflict, got {other:?}"),
        }
        // State is unchanged after the rejected update.
        assert_eq!(
            storage.get(&tid(&task_id), None).await?.status.state,
            TaskState::Working
        );

        // A conditional update with the current version succeeds and bumps.
        let updated = storage
            .update_status_checked(&tid(&task_id), 2, TaskState::Completed, None)
            .await?;
        assert_eq!(updated.version, 3);
        assert_eq!(updated.task.status.state, TaskState::Completed);

        // Versioning ops on a missing task report TaskNotFound.
        assert!(matches!(
            storage.version(&tid("ghost")).await,
            Err(A2AError::TaskNotFound(_))
        ));

        Ok(())
    }
}

#[cfg(not(feature = "sqlx-storage"))]
#[tokio::test]
async fn test_sqlx_not_available() {
    // This test just verifies the feature flag works correctly
    println!("SQLx storage tests skipped - feature not enabled");
}