a2a-cli 0.2.1

Standalone A2A CLI client
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
// Copyright AGNTCY Contributors (https://github.com/agntcy)
// SPDX-License-Identifier: Apache-2.0
use std::collections::BTreeMap;
use std::process::Command as StdCommand;
use std::sync::{Arc, Mutex};

use a2a::event::{StreamResponse, TaskStatusUpdateEvent};
use a2a::*;
use a2a_server::jsonrpc::jsonrpc_router;
use a2a_server::rest::rest_router;
use a2a_server::{RequestHandler, ServiceParams, WELL_KNOWN_AGENT_CARD_PATH};
use assert_cmd::Command as AssertCommand;
use assert_cmd::assert::OutputAssertExt;
use assert_cmd::cargo::CommandCargoExt;
use async_trait::async_trait;
use axum::http::{HeaderMap, StatusCode, header};
use axum::routing::get;
use axum::{Json, Router};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use futures::stream::{self, BoxStream};
use serde_json::Value;
use tokio::net::TcpListener;

/// (Authorization, x-test, x-api-key) recorded per card fetch.
type CardHeaders = (Option<String>, Option<String>, Option<String>);

/// (Authorization, x-api-key, x-trace-id, A2A-Version) recorded per call to
/// the *agent*. The version is recorded as every value joined by `,`, so a
/// test can tell one explicit version from two appended ones.
/// Kept separate from [`CardHeaders`] because the card fetch and the agent
/// call go out over different clients: a credential reaching one is no
/// evidence it reaches the other.
type AgentHeaders = (
    Option<String>,
    Option<String>,
    Option<String>,
    Option<String>,
);

/// Every value sent for `name`, joined by `,` — distinguishes a header set
/// once from one appended to twice.
fn joined_header_values(headers: &HeaderMap, name: &str) -> Option<String> {
    let values: Vec<String> = headers
        .get_all(name)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .map(ToOwned::to_owned)
        .collect();
    (!values.is_empty()).then(|| values.join(","))
}

fn header_value(headers: &HeaderMap, name: &str) -> Option<String> {
    headers
        .get(name)
        .and_then(|value| value.to_str().ok())
        .map(ToOwned::to_owned)
}

#[derive(Default)]
struct ServerState {
    tasks: Mutex<BTreeMap<String, Task>>,
    push_configs: Mutex<BTreeMap<(String, String), TaskPushNotificationConfig>>,
    card_headers: Mutex<Vec<CardHeaders>>,
    agent_headers: Mutex<Vec<AgentHeaders>>,
    /// Number of times `get_task` has been called for each of the
    /// poll-until-settled fixture task ids below.
    poll_counts: Mutex<BTreeMap<String, u32>>,
    /// The `tenant` field of each `send_message` request received, in
    /// order — for TX_003's "selected interface's own tenant, absent an
    /// explicit --tenant" fallback.
    received_send_tenants: Mutex<Vec<Option<String>>>,
}

/// Fixture task ids that settle to `COMPLETED` only after this many
/// `get_task` calls, so tests can exercise the blocking-wait/poll loop
/// instead of a task that is already settled on the first read.
const POLLS_UNTIL_SETTLED: u32 = 3;
/// Fixture task id that never settles, for exercising `--timeout`.
const STUCK_TASK_ID: &str = "task-stuck";

struct TestHandler {
    state: Arc<ServerState>,
    extended_card: AgentCard,
}

struct TestServer {
    base_url: String,
    state: Arc<ServerState>,
    handle: tokio::task::JoinHandle<()>,
}

impl Drop for TestServer {
    fn drop(&mut self) {
        self.handle.abort();
    }
}

impl TestServer {
    async fn spawn() -> Self {
        Self::spawn_with_card_tenant(None).await
    }

    /// Like [`Self::spawn`], but the public card's JSON-RPC interface
    /// declares the given routing `tenant` (A2A §8.3.2), for exercising
    /// TX_003's "use the selected interface's own tenant absent an explicit
    /// --tenant" fallback.
    async fn spawn_with_card_tenant(tenant: Option<&str>) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base_url = format!("http://{}", listener.local_addr().unwrap());
        let state = Arc::new(ServerState::default());

        {
            let mut tasks = state.tasks.lock().unwrap();
            tasks.insert(
                "task-1".to_string(),
                make_task("task-1", "ctx-1", TaskState::Completed, "seeded result"),
            );
            tasks.insert(
                "task-failed".to_string(),
                make_task("task-failed", "ctx-failed", TaskState::Failed, "it broke"),
            );
            tasks.insert(
                "task-rejected".to_string(),
                make_task(
                    "task-rejected",
                    "ctx-rejected",
                    TaskState::Rejected,
                    "not allowed",
                ),
            );
            tasks.insert(
                "task-needs-input".to_string(),
                make_task(
                    "task-needs-input",
                    "ctx-needs-input",
                    TaskState::InputRequired,
                    "what's the destination city?",
                ),
            );
        }

        let mut public_card = make_agent_card(&base_url, "Fixture Agent");
        if let Some(tenant) = tenant {
            public_card.supported_interfaces[0].tenant = Some(tenant.to_string());
        }
        let extended_card = make_agent_card(&base_url, "Fixture Agent (extended)");
        let handler = Arc::new(TestHandler {
            state: state.clone(),
            extended_card,
        });

        let card_state = state.clone();
        let card = public_card.clone();
        let custom_path_card = public_card.clone();

        // Record the headers of every call that reaches the agent's own
        // endpoints, so a test can tell "the credential was attached to the
        // card fetch" apart from "the credential was attached to the RPC".
        let agent_state = state.clone();
        let record_agent_headers = axum::middleware::from_fn(
            move |headers: HeaderMap,
                  request: axum::extract::Request,
                  next: axum::middleware::Next| {
                let state = agent_state.clone();
                async move {
                    state.agent_headers.lock().unwrap().push((
                        header_value(&headers, header::AUTHORIZATION.as_str()),
                        header_value(&headers, "x-api-key"),
                        header_value(&headers, "x-trace-id"),
                        joined_header_values(&headers, "a2a-version"),
                    ));
                    next.run(request).await
                }
            },
        );

        let app = Router::new()
            .route(
                WELL_KNOWN_AGENT_CARD_PATH,
                get(move |headers: HeaderMap| {
                    let state = card_state.clone();
                    let card = card.clone();
                    async move {
                        state.card_headers.lock().unwrap().push((
                            header_value(&headers, header::AUTHORIZATION.as_str()),
                            header_value(&headers, "x-test"),
                            header_value(&headers, "x-api-key"),
                        ));
                        (StatusCode::OK, Json(card))
                    }
                }),
            )
            // The same card at a path that is *not* the well-known one, so a
            // test can prove a full card URL is used as-is rather than
            // having the well-known path appended to it.
            .route(
                "/custom/card.json",
                get({
                    let card = custom_path_card.clone();
                    move || {
                        let card = card.clone();
                        async move { (StatusCode::OK, Json(card)) }
                    }
                }),
            )
            .nest(
                "/jsonrpc",
                jsonrpc_router(handler.clone()).layer(record_agent_headers.clone()),
            )
            .nest("/rest", rest_router(handler).layer(record_agent_headers));

        let handle = tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        TestServer {
            base_url,
            state,
            handle,
        }
    }
}

#[async_trait]
impl RequestHandler for TestHandler {
    async fn send_message(
        &self,
        _params: &ServiceParams,
        req: SendMessageRequest,
    ) -> Result<SendMessageResponse, A2AError> {
        self.state
            .received_send_tenants
            .lock()
            .unwrap()
            .push(req.tenant.clone());

        let text = req.message.text().unwrap_or_default();
        if text == "send-error" {
            return Err(A2AError::invalid_request("send failed"));
        }

        // A2A §3.4.3: an explicit --task-id must reference an existing
        // task, and a --context-id given alongside it must match that
        // task's actual context — the server rejects a mismatch rather
        // than reconciling it (SPEC.md §8.1, INTERACT_002).
        if let Some(requested_task_id) = &req.message.task_id {
            let tasks = self.state.tasks.lock().unwrap();
            match tasks.get(requested_task_id) {
                None => return Err(A2AError::task_not_found(requested_task_id)),
                Some(existing) => {
                    if let Some(requested_context_id) = &req.message.context_id {
                        if requested_context_id != &existing.context_id {
                            return Err(A2AError::invalid_params(format!(
                                "task {requested_task_id} belongs to context {}, not {requested_context_id}",
                                existing.context_id
                            )));
                        }
                    }
                }
            }
        }

        let task_id = req
            .message
            .task_id
            .clone()
            .unwrap_or_else(|| "task-send".to_string());
        let context_id = req
            .message
            .context_id
            .clone()
            .unwrap_or_else(|| "ctx-send".to_string());
        if text == "reply-only" {
            // No task created: a direct Message reply (SEND_003 — the tool
            // must exit cleanly with it rather than waiting on a task that
            // doesn't exist).
            return Ok(SendMessageResponse::Message(Message {
                message_id: "msg-reply-only".to_string(),
                context_id: Some(context_id),
                task_id: None,
                role: Role::Agent,
                parts: vec![Part::text(format!("Echo: {text}"))],
                metadata: None,
                extensions: None,
                reference_task_ids: None,
            }));
        }
        if text == "start-pending" {
            // A task that starts WORKING and only settles after
            // POLLS_UNTIL_SETTLED calls to get_task, so tests can observe
            // send's blocking-by-default wait actually polling.
            let task = make_task(
                "task-pending-send",
                "ctx-pending-send",
                TaskState::Working,
                "pending",
            );
            self.state
                .tasks
                .lock()
                .unwrap()
                .insert("task-pending-send".to_string(), task.clone());
            return Ok(SendMessageResponse::Task(task));
        }

        // Multi-part messages are echoed back verbatim so tests can assert
        // on the exact parts (and their order/media types) the CLI sent;
        // a single-part message keeps the simpler "Echo: {text}" form so
        // existing single-part assertions are unaffected.
        let response_parts = if req.message.parts.len() > 1 {
            req.message.parts.clone()
        } else {
            vec![Part::text(format!("Echo: {text}"))]
        };
        // A task that lands FAILED on the first reply, so `send`'s own
        // reporting path can be observed naming a non-success outcome
        // (EXIT_002) rather than only `task get`'s.
        let state = if text == "send-failing" {
            TaskState::Failed
        } else {
            TaskState::Completed
        };
        let task = make_task_with_parts(&task_id, &context_id, state, response_parts);
        self.state
            .tasks
            .lock()
            .unwrap()
            .insert(task_id.clone(), task.clone());
        Ok(SendMessageResponse::Task(task))
    }

    async fn send_streaming_message(
        &self,
        _params: &ServiceParams,
        req: SendMessageRequest,
    ) -> Result<BoxStream<'static, Result<StreamResponse, A2AError>>, A2AError> {
        let task_id = req
            .message
            .task_id
            .clone()
            .unwrap_or_else(|| "task-stream".to_string());
        let context_id = req
            .message
            .context_id
            .clone()
            .unwrap_or_else(|| "ctx-stream".to_string());
        let text = req.message.text().unwrap_or_default();
        if text == "stream-error" {
            return Ok(Box::pin(stream::once(async {
                Err(A2AError::internal("stream failed"))
            })));
        }
        if text == "stream-open-error" {
            // Unlike "stream-error" (a stream that opens, then yields an
            // error item), this fails *opening* the stream at all — the
            // case send's fallback-to-polling path (TASK_POLL_004) exists
            // for. UNSUPPORTED_OPERATION specifically, since that's the
            // only code the fallback should trigger on.
            return Err(A2AError::unsupported_operation("streaming not available"));
        }
        if text == "stream-open-real-error" {
            // A genuine failure opening the stream that is *not*
            // "streaming unsupported" — this must propagate as an error,
            // not be silently retried as a one-shot send.
            return Err(A2AError::internal("transport exploded"));
        }

        let task = make_task(
            &task_id,
            &context_id,
            TaskState::Completed,
            &format!("Echo: {text}"),
        );
        self.state
            .tasks
            .lock()
            .unwrap()
            .insert(task_id.clone(), task.clone());

        Ok(Box::pin(stream::iter(vec![
            Ok(StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
                task_id,
                context_id,
                status: TaskStatus {
                    state: TaskState::Working,
                    message: None,
                    timestamp: None,
                },
                metadata: None,
            })),
            Ok(StreamResponse::Task(task)),
        ])))
    }

    async fn get_task(
        &self,
        _params: &ServiceParams,
        req: GetTaskRequest,
    ) -> Result<Task, A2AError> {
        if req.id == STUCK_TASK_ID {
            return Ok(make_task(&req.id, "ctx-stuck", TaskState::Working, "stuck"));
        }

        if req.id == "task-pending" || req.id == "task-pending-send" {
            let mut counts = self.state.poll_counts.lock().unwrap();
            let count = counts.entry(req.id.clone()).or_insert(0);
            *count += 1;
            let state = if *count >= POLLS_UNTIL_SETTLED {
                TaskState::Completed
            } else {
                TaskState::Working
            };
            let context_id = if req.id == "task-pending" {
                "ctx-pending"
            } else {
                "ctx-pending-send"
            };
            return Ok(make_task(&req.id, context_id, state, "settled"));
        }

        self.state
            .tasks
            .lock()
            .unwrap()
            .get(&req.id)
            .cloned()
            .ok_or_else(|| A2AError::task_not_found(&req.id))
    }

    async fn list_tasks(
        &self,
        _params: &ServiceParams,
        req: ListTasksRequest,
    ) -> Result<ListTasksResponse, A2AError> {
        if req.context_id.as_deref() == Some("error") {
            return Err(A2AError::invalid_params("list failed"));
        }

        let tasks: Vec<Task> = self
            .state
            .tasks
            .lock()
            .unwrap()
            .values()
            .filter(|task| {
                req.context_id
                    .as_ref()
                    .is_none_or(|context_id| &task.context_id == context_id)
            })
            .filter(|task| {
                req.status
                    .as_ref()
                    .is_none_or(|status| &task.status.state == status)
            })
            .cloned()
            .collect();

        Ok(ListTasksResponse {
            total_size: tasks.len() as i32,
            page_size: req.page_size.unwrap_or(tasks.len() as i32),
            next_page_token: String::new(),
            tasks,
        })
    }

    async fn cancel_task(
        &self,
        _params: &ServiceParams,
        req: CancelTaskRequest,
    ) -> Result<Task, A2AError> {
        let mut tasks = self.state.tasks.lock().unwrap();
        let task = tasks
            .get(&req.id)
            .cloned()
            .ok_or_else(|| A2AError::task_not_found(&req.id))?;
        let canceled = make_task(&task.id, &task.context_id, TaskState::Canceled, "canceled");
        tasks.insert(req.id, canceled.clone());
        Ok(canceled)
    }

    async fn subscribe_to_task(
        &self,
        _params: &ServiceParams,
        req: SubscribeToTaskRequest,
    ) -> Result<BoxStream<'static, Result<StreamResponse, A2AError>>, A2AError> {
        if req.id == "stream-error" {
            return Ok(Box::pin(stream::once(async {
                Err(A2AError::internal("stream failed"))
            })));
        }

        let task = self
            .state
            .tasks
            .lock()
            .unwrap()
            .get(&req.id)
            .cloned()
            .ok_or_else(|| A2AError::task_not_found(&req.id))?;

        Ok(Box::pin(stream::iter(vec![
            Ok(StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
                task_id: req.id.clone(),
                context_id: task.context_id.clone(),
                status: TaskStatus {
                    state: TaskState::Working,
                    message: None,
                    timestamp: None,
                },
                metadata: None,
            })),
            Ok(StreamResponse::Task(task)),
        ])))
    }

    async fn create_push_config(
        &self,
        _params: &ServiceParams,
        req: TaskPushNotificationConfig,
    ) -> Result<TaskPushNotificationConfig, A2AError> {
        if !self.state.tasks.lock().unwrap().contains_key(&req.task_id) {
            return Err(A2AError::task_not_found(&req.task_id));
        }

        let mut config = req;
        let config_id = config
            .id
            .clone()
            .unwrap_or_else(|| "cfg-generated".to_string());
        config.id = Some(config_id.clone());
        self.state
            .push_configs
            .lock()
            .unwrap()
            .insert((config.task_id.clone(), config_id), config.clone());
        Ok(config)
    }

    async fn get_push_config(
        &self,
        _params: &ServiceParams,
        req: GetTaskPushNotificationConfigRequest,
    ) -> Result<TaskPushNotificationConfig, A2AError> {
        self.state
            .push_configs
            .lock()
            .unwrap()
            .get(&(req.task_id.clone(), req.id.clone()))
            .cloned()
            .ok_or_else(|| A2AError::task_not_found(&req.task_id))
    }

    async fn list_push_configs(
        &self,
        _params: &ServiceParams,
        req: ListTaskPushNotificationConfigsRequest,
    ) -> Result<ListTaskPushNotificationConfigsResponse, A2AError> {
        if req.task_id == "missing" {
            return Err(A2AError::task_not_found(&req.task_id));
        }

        let configs = self
            .state
            .push_configs
            .lock()
            .unwrap()
            .values()
            .filter(|config| config.task_id == req.task_id)
            .cloned()
            .collect();
        Ok(ListTaskPushNotificationConfigsResponse {
            configs,
            next_page_token: None,
        })
    }

    async fn delete_push_config(
        &self,
        _params: &ServiceParams,
        req: DeleteTaskPushNotificationConfigRequest,
    ) -> Result<(), A2AError> {
        let deleted = self
            .state
            .push_configs
            .lock()
            .unwrap()
            .remove(&(req.task_id.clone(), req.id.clone()));
        if deleted.is_none() {
            return Err(A2AError::task_not_found(&req.task_id));
        }
        Ok(())
    }

    async fn get_extended_agent_card(
        &self,
        _params: &ServiceParams,
        req: GetExtendedAgentCardRequest,
    ) -> Result<AgentCard, A2AError> {
        if req.tenant.as_deref() == Some("error") {
            return Err(A2AError::unsupported_operation("extended card denied"));
        }

        Ok(self.extended_card.clone())
    }
}

fn make_agent_card(base_url: &str, name: &str) -> AgentCard {
    AgentCard {
        name: name.to_string(),
        description: "CLI integration fixture".to_string(),
        version: VERSION.to_string(),
        supported_interfaces: vec![
            AgentInterface::new(format!("{base_url}/jsonrpc"), TRANSPORT_PROTOCOL_JSONRPC),
            AgentInterface::new(format!("{base_url}/rest"), TRANSPORT_PROTOCOL_HTTP_JSON),
        ],
        capabilities: AgentCapabilities {
            streaming: Some(true),
            push_notifications: Some(true),
            extensions: None,
            extended_agent_card: Some(true),
        },
        default_input_modes: vec!["text/plain".to_string()],
        default_output_modes: vec!["text/plain".to_string()],
        skills: vec![],
        provider: None,
        documentation_url: None,
        icon_url: None,
        security_schemes: None,
        security_requirements: None,
        signatures: None,
    }
}

fn make_task(task_id: &str, context_id: &str, state: TaskState, text: &str) -> Task {
    make_task_with_parts(task_id, context_id, state, vec![Part::text(text)])
}

fn make_task_with_parts(
    task_id: &str,
    context_id: &str,
    state: TaskState,
    parts: Vec<Part>,
) -> Task {
    Task {
        id: task_id.to_string(),
        context_id: context_id.to_string(),
        status: TaskStatus {
            state,
            message: Some(Message {
                message_id: format!("msg-{task_id}"),
                context_id: Some(context_id.to_string()),
                task_id: Some(task_id.to_string()),
                role: Role::Agent,
                parts,
                metadata: None,
                extensions: None,
                reference_task_ids: None,
            }),
            timestamp: None,
        },
        artifacts: None,
        history: None,
        metadata: None,
    }
}

/// Most of this suite asserts on the exact protocol JSON shape the CLI
/// received/produced, so these helpers default to `-o json` — the same way
/// the pre-#168 CLI always behaved. Tests that specifically exercise the new
/// `text` default or the error envelope build their own `StdCommand`
/// instead of going through these.
fn run_cli_success(server: &TestServer, args: &[&str]) -> String {
    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    command.args(["--agent-card", server.base_url.as_str(), "--output", "json"]);
    command.args(args);
    let output = command.assert().success().get_output().stdout.clone();
    String::from_utf8(output).unwrap()
}

fn run_cli_failure(server: &TestServer, args: &[&str]) -> (String, String) {
    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    command.args(["--agent-card", server.base_url.as_str(), "--output", "json"]);
    command.args(args);
    let output = command.assert().failure().get_output().clone();
    (
        String::from_utf8(output.stdout).unwrap(),
        String::from_utf8(output.stderr).unwrap(),
    )
}

/// Like [`run_cli_failure`], but also returns the process exit code, for the
/// handful of tests that check §11.6's exit-code contract explicitly.
fn run_cli_failure_status(server: &TestServer, args: &[&str]) -> (String, String, i32) {
    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    command.args(["--agent-card", server.base_url.as_str(), "--output", "json"]);
    command.args(args);
    let output = command.assert().failure().get_output().clone();
    (
        String::from_utf8(output.stdout).unwrap(),
        String::from_utf8(output.stderr).unwrap(),
        output.status.code().unwrap(),
    )
}

/// Parse the Appendix B error envelope a failing command printed to stderr.
fn parse_error_envelope(stderr: &str) -> Value {
    serde_json::from_str(stderr.trim()).unwrap()
}

fn parse_json_lines(output: &str) -> Vec<Value> {
    output
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| serde_json::from_str(line).unwrap())
        .collect()
}

async fn unused_base_url() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    drop(listener);
    format!("http://{addr}")
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn card_and_extended_card_commands_work() {
    let server = TestServer::spawn().await;

    let stdout = run_cli_success(
        &server,
        &[
            "--bearer",
            "secret",
            "--svc-param",
            "X-Test: abc",
            "card",
            "get",
        ],
    );
    let card: Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(card["name"], "Fixture Agent");

    let headers = server.state.card_headers.lock().unwrap().clone();
    assert_eq!(headers.len(), 1);
    assert_eq!(headers[0].0.as_deref(), Some("Bearer secret"));
    assert_eq!(headers[0].1.as_deref(), Some("abc"));

    let compact = run_cli_success(
        &server,
        &[
            "--transport",
            "rest",
            "--compact",
            "card",
            "get",
            "--extended",
        ],
    );
    assert!(!compact.trim_end().contains('\n'));
    let card: Value = serde_json::from_str(compact.trim()).unwrap();
    assert_eq!(card["name"], "Fixture Agent (extended)");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_task_list_and_cancel_commands_work() {
    let server = TestServer::spawn().await;

    // No --task-id/--context-id: this starts a *new* task (the server
    // assigns "task-send"/"ctx-send" per the fixture's defaults). A2A
    // §4.1 forbids a client from inventing a taskId for a new task, so
    // an explicit --task-id here would have to name an *existing* task
    // (see the INTERACT_002 rejection tests below).
    let send = run_cli_success(
        &server,
        &[
            "--bearer",
            "secret",
            "--svc-param",
            "X-Trace: 123",
            "send",
            "hello from cli",
            "--accept-output",
            "text/plain",
            "--return-immediately",
        ],
    );
    let send_json: Value = serde_json::from_str(&send).unwrap();
    assert_eq!(send_json["task"]["id"], "task-send");
    assert_eq!(
        send_json["task"]["status"]["message"]["parts"][0]["text"],
        "Echo: hello from cli"
    );

    let get_task = run_cli_success(
        &server,
        &["task", "get", "task-send", "--history-length", "1"],
    );
    let task_json: Value = serde_json::from_str(&get_task).unwrap();
    assert_eq!(task_json["id"], "task-send");

    let list = run_cli_success(
        &server,
        &[
            "--compact",
            "task",
            "list",
            "--context-id",
            "ctx-send",
            "--status",
            "completed",
        ],
    );
    let list_json: Value = serde_json::from_str(list.trim()).unwrap();
    assert_eq!(list_json["tasks"].as_array().unwrap().len(), 1);

    let cancel = run_cli_success(&server, &["task", "cancel", "task-send"]);
    let cancel_json: Value = serde_json::from_str(&cancel).unwrap();
    assert_eq!(cancel_json["status"]["state"], "TASK_STATE_CANCELED");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn stream_and_subscribe_commands_work() {
    let server = TestServer::spawn().await;

    let stream_output = run_cli_success(
        &server,
        &[
            "--compact",
            "send",
            "streaming request",
            "--stream",
            "--task-id",
            "task-stream",
            "--context-id",
            "ctx-stream",
        ],
    );
    let stream_events = parse_json_lines(&stream_output);
    assert_eq!(stream_events.len(), 2);
    assert_eq!(
        stream_events[0]["statusUpdate"]["status"]["state"],
        "TASK_STATE_WORKING"
    );
    assert_eq!(stream_events[1]["task"]["id"], "task-stream");

    let subscribe_output =
        run_cli_success(&server, &["--compact", "task", "subscribe", "task-stream"]);
    let subscribe_events = parse_json_lines(&subscribe_output);
    assert_eq!(subscribe_events.len(), 2);
    assert_eq!(subscribe_events[1]["task"]["id"], "task-stream");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn push_config_crud_commands_work() {
    let server = TestServer::spawn().await;

    let create = run_cli_success(
        &server,
        &[
            "--compact",
            "--tenant",
            "tenant-1",
            "task",
            "push-config",
            "create",
            "task-1",
            "https://example.com/callback",
            "--config-id",
            "cfg-1",
            "--token",
            "tok-1",
            "--auth-scheme",
            "Bearer",
            "--auth-credentials",
            "secret",
        ],
    );
    let create_json: Value = serde_json::from_str(create.trim()).unwrap();
    assert_eq!(create_json["taskId"], "task-1");
    assert_eq!(create_json["id"], "cfg-1");
    assert_eq!(create_json["tenant"], "tenant-1");

    let get = run_cli_success(
        &server,
        &["--compact", "task", "push-config", "get", "task-1", "cfg-1"],
    );
    let get_json: Value = serde_json::from_str(get.trim()).unwrap();
    assert_eq!(get_json["authentication"]["scheme"], "Bearer");

    let list = run_cli_success(
        &server,
        &[
            "--compact",
            "task",
            "push-config",
            "list",
            "task-1",
            "--page-size",
            "10",
        ],
    );
    let list_json: Value = serde_json::from_str(list.trim()).unwrap();
    assert_eq!(list_json["configs"].as_array().unwrap().len(), 1);

    let delete = run_cli_success(
        &server,
        &[
            "--compact",
            "task",
            "push-config",
            "delete",
            "task-1",
            "cfg-1",
        ],
    );
    let delete_json: Value = serde_json::from_str(delete.trim()).unwrap();
    assert_eq!(delete_json["deleted"], true);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn binary_reports_a2a_and_non_a2a_errors() {
    let server = TestServer::spawn().await;

    // Unreachable agent: A2ACLI_ERR_UNREACHABLE, exit 3 (Appendix D).
    let base_url = unused_base_url().await;
    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--agent-card",
            base_url.as_str(),
            "--output",
            "json",
            "card",
            "get",
        ])
        .assert()
        .failure()
        .get_output()
        .clone();
    let stderr = String::from_utf8(output.stderr).unwrap();
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "A2ACLI_ERR_UNREACHABLE");
    assert_eq!(output.status.code().unwrap(), 3);

    // A protocol failure carries the A2A error name and its numeric code
    // unchanged (§11.4), and exits 1 — the CLI did its job of conducting
    // and reporting the call.
    let (_stdout, stderr, code) =
        run_cli_failure_status(&server, &["card", "get", "--extended", "--tenant", "error"]);
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "UNSUPPORTED_OPERATION");
    assert_eq!(envelope["error"]["message"], "extended card denied");
    assert_eq!(envelope["error"]["a2aCode"], -32004);
    assert_eq!(code, 1);

    let (_stdout, stderr) = run_cli_failure(&server, &["send", "send-error"]);
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "INVALID_REQUEST");
    assert_eq!(envelope["error"]["a2aCode"], -32600);

    let (_stdout, stderr) = run_cli_failure(&server, &["task", "list", "--context-id", "error"]);
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "INVALID_PARAMS");
    assert_eq!(envelope["error"]["a2aCode"], -32602);

    let (_stdout, stderr) = run_cli_failure(&server, &["task", "get", "missing"]);
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "TASK_NOT_FOUND");
    assert_eq!(envelope["error"]["message"], "task not found: missing");
    assert_eq!(envelope["error"]["a2aCode"], -32001);

    let (_stdout, stderr) = run_cli_failure(&server, &["task", "cancel", "missing"]);
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "TASK_NOT_FOUND");

    let (_stdout, stderr) = run_cli_failure(&server, &["task", "subscribe", "stream-error"]);
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "INTERNAL_ERROR");
    assert_eq!(envelope["error"]["a2aCode"], -32603);

    let (_stdout, stderr) =
        run_cli_failure(&server, &["--compact", "send", "stream-error", "--stream"]);
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "INTERNAL_ERROR");

    let (_stdout, stderr) = run_cli_failure(
        &server,
        &[
            "task",
            "push-config",
            "create",
            "missing",
            "https://example.com/callback",
            "--config-id",
            "cfg-missing",
        ],
    );
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "TASK_NOT_FOUND");

    let (_stdout, stderr) = run_cli_failure(
        &server,
        &["task", "push-config", "get", "task-1", "missing"],
    );
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "TASK_NOT_FOUND");

    let (_stdout, stderr) = run_cli_failure(&server, &["task", "push-config", "list", "missing"]);
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "TASK_NOT_FOUND");

    let (_stdout, stderr) = run_cli_failure(
        &server,
        &["task", "push-config", "delete", "task-1", "missing"],
    );
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "TASK_NOT_FOUND");

    // A CLI-local usage failure: A2ACLI_ERR_USAGE, exit 2, no a2aCode.
    let (_stdout, stderr, code) = run_cli_failure_status(
        &server,
        &[
            "task",
            "push-config",
            "create",
            "task-1",
            "https://example.com/callback",
            "--auth-credentials",
            "secret",
        ],
    );
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "A2ACLI_ERR_USAGE");
    assert!(
        envelope["error"]["message"]
            .as_str()
            .unwrap()
            .contains("--auth-credentials requires --auth-scheme")
    );
    assert!(envelope["error"]["a2aCode"].is_null());
    assert_eq!(code, 2);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_blocks_by_default_until_task_settles() {
    let server = TestServer::spawn().await;

    let output = run_cli_success(
        &server,
        &[
            "--compact",
            "--poll-interval",
            "10ms",
            "--timeout",
            "5s",
            "send",
            "start-pending",
        ],
    );
    let response: Value = serde_json::from_str(output.trim()).unwrap();
    assert_eq!(response["task"]["id"], "task-pending-send");
    assert_eq!(response["task"]["status"]["state"], "TASK_STATE_COMPLETED");

    // The blocking wait must have actually polled get_task rather than
    // returning the initial WORKING response.
    let count = *server
        .state
        .poll_counts
        .lock()
        .unwrap()
        .get("task-pending-send")
        .unwrap_or(&0);
    assert!(count >= POLLS_UNTIL_SETTLED);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_async_returns_immediately_without_waiting() {
    let server = TestServer::spawn().await;

    let output = run_cli_success(&server, &["--compact", "--async", "send", "start-pending"]);
    let response: Value = serde_json::from_str(output.trim()).unwrap();
    assert_eq!(response["task"]["id"], "task-pending-send");
    assert_eq!(response["task"]["status"]["state"], "TASK_STATE_WORKING");

    // --async must skip polling entirely.
    let count = *server
        .state
        .poll_counts
        .lock()
        .unwrap()
        .get("task-pending-send")
        .unwrap_or(&0);
    assert_eq!(count, 0);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn task_get_wait_polls_until_settled() {
    let server = TestServer::spawn().await;

    let output = run_cli_success(
        &server,
        &[
            "--compact",
            "--wait",
            "--poll-interval",
            "10ms",
            "--timeout",
            "5s",
            "task",
            "get",
            "task-pending",
        ],
    );
    let task: Value = serde_json::from_str(output.trim()).unwrap();
    assert_eq!(task["status"]["state"], "TASK_STATE_COMPLETED");

    let count = *server
        .state
        .poll_counts
        .lock()
        .unwrap()
        .get("task-pending")
        .unwrap_or(&0);
    assert!(count >= POLLS_UNTIL_SETTLED);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn task_get_without_wait_does_not_poll() {
    let server = TestServer::spawn().await;

    let output = run_cli_success(&server, &["--compact", "task", "get", "task-pending"]);
    let task: Value = serde_json::from_str(output.trim()).unwrap();
    // Still WORKING: a one-shot read must not have polled to settlement.
    assert_eq!(task["status"]["state"], "TASK_STATE_WORKING");

    let count = *server
        .state
        .poll_counts
        .lock()
        .unwrap()
        .get("task-pending")
        .unwrap_or(&0);
    assert_eq!(count, 1);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn task_get_wait_times_out() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr) = run_cli_failure(
        &server,
        &[
            "--wait",
            "--poll-interval",
            "10ms",
            "--timeout",
            "50ms",
            "task",
            "get",
            STUCK_TASK_ID,
        ],
    );
    assert!(stderr.contains("timed out"));
    assert!(stderr.contains(STUCK_TASK_ID));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_with_ordered_message_parts_and_media_type() {
    let server = TestServer::spawn().await;

    let output = run_cli_success(
        &server,
        &[
            "--compact",
            "send",
            "--text-part",
            "hello",
            "--file-part",
            "https://example.com/doc.pdf",
            "--media-type",
            "application/pdf",
            "--data-part",
            r#"{"priority":"high"}"#,
        ],
    );
    let response: Value = serde_json::from_str(output.trim()).unwrap();
    let parts = response["task"]["status"]["message"]["parts"]
        .as_array()
        .unwrap();

    assert_eq!(parts.len(), 3);
    assert_eq!(parts[0]["text"], "hello");
    assert_eq!(parts[1]["url"], "https://example.com/doc.pdf");
    assert_eq!(parts[1]["mediaType"], "application/pdf");
    assert!(parts[1].get("text").is_none());
    assert_eq!(parts[2]["data"]["priority"], "high");
    assert!(parts[2].get("mediaType").is_none());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_reads_local_file_part_and_stdin_data_part() {
    let server = TestServer::spawn().await;

    let mut file_path = std::env::temp_dir();
    file_path.push(format!("a2acli-test-file-part-{}.bin", std::process::id()));
    std::fs::write(&file_path, b"binary payload").unwrap();

    let output = AssertCommand::cargo_bin("a2acli")
        .unwrap()
        .args([
            "--agent-card",
            server.base_url.as_str(),
            "--output",
            "json",
            "--compact",
            "send",
            "--text-part",
            "hello",
            "--file-part",
            file_path.to_str().unwrap(),
            "--data-part",
            "-",
        ])
        .write_stdin(r#"{"ok":true}"#)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    std::fs::remove_file(&file_path).unwrap();

    let response: Value = serde_json::from_str(String::from_utf8(output).unwrap().trim()).unwrap();
    let parts = response["task"]["status"]["message"]["parts"]
        .as_array()
        .unwrap();

    assert_eq!(parts.len(), 3);
    assert_eq!(
        parts[1]["filename"],
        file_path.file_name().unwrap().to_str().unwrap()
    );
    let decoded = BASE64.decode(parts[1]["raw"].as_str().unwrap()).unwrap();
    assert_eq!(decoded, b"binary payload");
    assert_eq!(parts[2]["data"]["ok"], true);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_rejects_media_type_without_preceding_part() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr) = run_cli_failure(
        &server,
        &[
            "send",
            "--media-type",
            "application/pdf",
            "--text-part",
            "hello",
        ],
    );
    assert!(stderr.contains("--media-type must immediately follow"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_rejects_positional_text_combined_with_part_flags() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr) = run_cli_failure(&server, &["send", "hello", "--text-part", "world"]);
    assert!(stderr.contains("cannot be combined"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_falls_back_to_polling_when_the_stream_fails_to_open() {
    let server = TestServer::spawn().await;

    // "stream-open-error" fails send_streaming_message itself (not a
    // stream item), which must trigger the one-shot-send-plus-poll
    // fallback rather than propagating the error or hanging.
    let stdout = run_cli_success(
        &server,
        &["--compact", "send", "stream-open-error", "--stream"],
    );
    let response: Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(response["task"]["status"]["state"], "TASK_STATE_COMPLETED");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_exits_cleanly_on_a_message_only_reply() {
    let server = TestServer::spawn().await;

    let stdout = run_cli_success(&server, &["--compact", "send", "reply-only"]);
    let response: Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(response["message"]["messageId"], "msg-reply-only");
    assert!(response.get("task").is_none());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_part_reports_a_usage_error_for_a_missing_local_path() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr) = run_cli_failure(
        &server,
        &["send", "--file-part", "/no/such/file-part-path.bin"],
    );
    assert!(stderr.contains("failed to read"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn data_part_reads_json_from_a_local_file() {
    let server = TestServer::spawn().await;

    let mut file_path = std::env::temp_dir();
    file_path.push(format!("a2acli-test-data-part-{}.json", std::process::id()));
    std::fs::write(&file_path, r#"{"from":"file"}"#).unwrap();

    let stdout = run_cli_success(
        &server,
        &[
            "--compact",
            "send",
            "--text-part",
            "hello",
            "--data-part",
            file_path.to_str().unwrap(),
        ],
    );
    std::fs::remove_file(&file_path).unwrap();

    let response: Value = serde_json::from_str(stdout.trim()).unwrap();
    let parts = response["task"]["status"]["message"]["parts"]
        .as_array()
        .unwrap();
    assert_eq!(parts[1]["data"]["from"], "file");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn data_part_rejects_a_value_that_is_neither_a_file_nor_valid_json() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr) = run_cli_failure(
        &server,
        &["send", "--data-part", "not json and no such file"],
    );
    assert!(stderr.contains("--data-part must be a file path"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn data_part_reports_a_usage_error_when_stdin_is_not_utf8() {
    let server = TestServer::spawn().await;

    let output = AssertCommand::cargo_bin("a2acli")
        .unwrap()
        .args([
            "--agent-card",
            server.base_url.as_str(),
            "send",
            "--data-part",
            "-",
        ])
        // Invalid UTF-8: read_to_string fails with an io::Error, exercising
        // --data-part -'s ReadFile error path (distinct from malformed-but-
        // valid-UTF-8 JSON, covered by the "neither a file nor valid JSON"
        // case above).
        .write_stdin(vec![0xFF, 0xFE, 0xFD])
        .assert()
        .failure()
        .get_output()
        .clone();
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("failed to read <stdin>"));
}

// Review fixes (a2aproject/a2a-rs#172 review from msardara).

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_stream_propagates_a_non_unsupported_error_instead_of_falling_back() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr) =
        run_cli_failure(&server, &["send", "stream-open-real-error", "--stream"]);
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "INTERNAL_ERROR");
    assert_eq!(envelope["error"]["message"], "transport exploded");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_rejects_a_message_with_no_content_at_all() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr) = run_cli_failure(&server, &["send"]);
    assert!(stderr.contains("message must have at least one part"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn media_type_alone_with_no_other_part_flag_is_rejected() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr) = run_cli_failure(&server, &["send", "--media-type", "application/json"]);
    assert!(stderr.contains("--media-type must immediately follow"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn data_part_reports_the_real_error_for_an_unreadable_existing_path() {
    let server = TestServer::spawn().await;

    // A directory exists but can never be read as file content — read_to_string
    // fails with something other than NotFound, which must be reported as a
    // ReadFile error rather than silently retried as inline JSON.
    let mut dir_path = std::env::temp_dir();
    dir_path.push(format!("a2acli-test-data-part-dir-{}", std::process::id()));
    std::fs::create_dir_all(&dir_path).unwrap();

    let (_stdout, stderr) = run_cli_failure(
        &server,
        &["send", "--data-part", dir_path.to_str().unwrap()],
    );

    std::fs::remove_dir_all(&dir_path).unwrap();

    assert!(stderr.contains("failed to read"));
    assert!(!stderr.contains("must be a file path"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn text_is_the_default_output_format() {
    let server = TestServer::spawn().await;

    // No -o/--output flag at all: this is the §6.5 default, not an opt-in.
    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--agent-card",
            server.base_url.as_str(),
            "task",
            "get",
            "task-1",
        ])
        .assert()
        .success()
        .get_output()
        .clone();

    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(
        !stdout.trim_start().starts_with('{'),
        "expected text, got: {stdout}"
    );
    assert!(stdout.contains("Task ID: task-1"));
    assert!(stdout.contains("Context ID: ctx-1"));
    assert!(stdout.contains("State: COMPLETED"));
    assert!(stdout.contains("Text:"));
    assert!(stdout.contains("seeded result"));

    // §11.1: stderr carries no diagnostics on a successful run.
    assert!(String::from_utf8(output.stderr).unwrap().is_empty());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn text_output_prints_resume_hint_on_input_required() {
    let server = TestServer::spawn().await;

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--agent-card",
            server.base_url.as_str(),
            "task",
            "get",
            "task-needs-input",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(output).unwrap();

    assert!(stdout.contains("State: INPUT_REQUIRED"));
    assert!(stdout.contains("Resume with: a2acli send --task-id task-needs-input \"<reply>\""));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn json_output_is_still_available_via_output_flag() {
    let server = TestServer::spawn().await;

    let stdout = run_cli_success(&server, &["task", "get", "task-1"]);
    let task: Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(task["id"], "task-1");
    assert_eq!(task["status"]["state"], "TASK_STATE_COMPLETED");
}

// INTERACT_002: a rejected --task-id surfaces the protocol error, exits
// non-zero, and never falls back to silently starting a new task.

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_rejects_unknown_task_id_without_creating_one() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr, code) =
        run_cli_failure_status(&server, &["send", "hello", "--task-id", "no-such-task"]);
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "TASK_NOT_FOUND");
    assert_ne!(code, 0);

    // The rejected attempt must not have silently created "no-such-task".
    let (_stdout, stderr) = run_cli_failure(&server, &["task", "get", "no-such-task"]);
    assert_eq!(
        parse_error_envelope(&stderr)["error"]["code"],
        "TASK_NOT_FOUND"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_rejects_task_id_with_mismatched_context_id() {
    let server = TestServer::spawn().await;

    // task-1 actually belongs to ctx-1 (seeded by TestServer::spawn).
    let (_stdout, stderr, code) = run_cli_failure_status(
        &server,
        &[
            "send",
            "hello",
            "--task-id",
            "task-1",
            "--context-id",
            "ctx-wrong",
        ],
    );
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "INVALID_PARAMS");
    assert!(
        envelope["error"]["message"]
            .as_str()
            .unwrap()
            .contains("ctx-1")
    );
    assert_ne!(code, 0);

    // task-1 itself must be unchanged by the rejected attempt.
    let stdout = run_cli_success(&server, &["task", "get", "task-1"]);
    let task: Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(task["contextId"], "ctx-1");
    assert_eq!(task["status"]["state"], "TASK_STATE_COMPLETED");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_accepts_task_id_alone_without_requiring_context_id() {
    // §8.1: --task-id MAY be given without --context-id; the server
    // resolves the task's own context, so this must succeed.
    let server = TestServer::spawn().await;

    let stdout = run_cli_success(
        &server,
        &["--compact", "send", "hello", "--task-id", "task-1"],
    );
    let response: Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(response["task"]["id"], "task-1");
    assert_eq!(response["task"]["status"]["state"], "TASK_STATE_COMPLETED");
}

// INTERACT_005: the CLI is completely stateless — it never remembers a
// previous run's identifiers and replays them absent an explicit flag.

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn repeated_sends_without_explicit_ids_never_reuse_a_previous_task() {
    let server = TestServer::spawn().await;

    // Two independent `send` invocations, neither passing --task-id: if the
    // CLI remembered the first run's task id and replayed it, the second
    // call would be rejected as "continuing" a task that belongs to a
    // different, non-existent context. Since neither run passes any
    // identifier, the server's own defaults apply identically both times,
    // and both must succeed exactly the same way.
    let first = run_cli_success(&server, &["--compact", "send", "hello once"]);
    let second = run_cli_success(&server, &["--compact", "send", "hello twice"]);

    let first: Value = serde_json::from_str(first.trim()).unwrap();
    let second: Value = serde_json::from_str(second.trim()).unwrap();
    assert_eq!(first["task"]["id"], second["task"]["id"]);
    assert_eq!(
        second["task"]["status"]["message"]["parts"][0]["text"],
        "Echo: hello twice"
    );
}

// INTERACT_001/003: contextId is an opaque, server-assigned grouping value
// the CLI passes through unchanged — never fabricated, and never assumed to
// mean a "chat session" (e.g. reused across unrelated task ids).

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn context_id_is_passed_through_opaquely_to_a_new_task() {
    let server = TestServer::spawn().await;

    // A fresh --context-id with no --task-id starts a new task grouped
    // under that context; the CLI must forward it verbatim rather than
    // validating, transforming, or fabricating one of its own.
    let stdout = run_cli_success(
        &server,
        &[
            "--compact",
            "send",
            "hello",
            "--context-id",
            "ctx-custom-123",
        ],
    );
    let response: Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(response["task"]["contextId"], "ctx-custom-123");
}

// AUTH_001/AUTH_003/TX_003 (a2aproject/a2a-rs#169).

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn api_key_is_attached_as_a_header_to_the_card_fetch() {
    let server = TestServer::spawn().await;

    run_cli_success(&server, &["--api-key", "key-abc", "card", "get"]);

    let headers = server.state.card_headers.lock().unwrap().clone();
    assert_eq!(headers.last().unwrap().2.as_deref(), Some("key-abc"));
}

/// AUTH_003: the credential has to reach the *agent*, not only the card
/// fetch — those go out over separate clients, and `card get` never builds
/// the agent client at all, so it cannot witness this.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn credentials_and_service_params_reach_the_agent_not_only_the_card_fetch() {
    let server = TestServer::spawn().await;

    run_cli_success(
        &server,
        &[
            "--api-key",
            "key-xyz",
            "--bearer",
            "token-xyz",
            "--svc-param",
            "X-Trace-Id:trace-1",
            "task",
            "get",
            "task-1",
        ],
    );

    let headers = server.state.agent_headers.lock().unwrap().clone();
    let (authorization, api_key, trace_id, _version) = headers
        .last()
        .cloned()
        .expect("the agent call should have been recorded");
    assert_eq!(api_key.as_deref(), Some("key-xyz"));
    assert_eq!(authorization.as_deref(), Some("Bearer token-xyz"));
    // `--svc-param` is a general transport-level pair, not a credential, and
    // rides along on the same call.
    assert_eq!(trace_id.as_deref(), Some("trace-1"));
}

/// `--insecure` swaps in transports built on a client that skips
/// certificate verification; against a plain-HTTP fixture the call still has
/// to succeed and still carry the credential, so the escape hatch can't
/// quietly drop either.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn insecure_flag_still_builds_a_working_authenticated_client() {
    let server = TestServer::spawn().await;

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--agent-card",
            server.base_url.as_str(),
            "--output",
            "json",
            "--insecure",
            "--api-key",
            "key-insecure",
            "task",
            "get",
            "task-1",
        ])
        .assert()
        .success()
        .get_output()
        .clone();

    let task: Value =
        serde_json::from_str(String::from_utf8(output.stdout).unwrap().trim()).unwrap();
    assert_eq!(task["id"], "task-1");

    let headers = server.state.agent_headers.lock().unwrap().clone();
    assert_eq!(
        headers.last().unwrap().1.as_deref(),
        Some("key-insecure"),
        "--insecure must not drop the credential"
    );
    // §12.1/AUTH_003: never silent, even on a call that succeeded.
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("--insecure disables TLS certificate verification"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn insecure_flag_prints_a_warning_and_names_the_credential_risk() {
    let server = TestServer::spawn().await;

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--agent-card",
            server.base_url.as_str(),
            "--insecure",
            "--bearer",
            "secret",
            "card",
            "get",
        ])
        .assert()
        .success()
        .get_output()
        .clone();
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("--insecure disables TLS certificate verification"));
    assert!(stderr.contains("--bearer/--api-key"));

    // Without a credential, the warning is still printed but doesn't
    // mention sending one.
    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--agent-card",
            server.base_url.as_str(),
            "--insecure",
            "card",
            "get",
        ])
        .assert()
        .success()
        .get_output()
        .clone();
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("--insecure disables TLS certificate verification"));
    assert!(!stderr.contains("--bearer/--api-key"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn no_insecure_flag_means_no_warning() {
    let server = TestServer::spawn().await;

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args(["--agent-card", server.base_url.as_str(), "card", "get"])
        .assert()
        .success()
        .get_output()
        .clone();
    assert!(String::from_utf8(output.stderr).unwrap().is_empty());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn selected_interface_tenant_is_used_absent_an_explicit_tenant_flag() {
    let server = TestServer::spawn_with_card_tenant(Some("card-declared-tenant")).await;

    run_cli_success(&server, &["--compact", "send", "hello"]);

    let received = server.state.received_send_tenants.lock().unwrap().clone();
    assert_eq!(received, vec![Some("card-declared-tenant".to_string())]);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_declared_interface_tenant_is_not_displaced_by_the_tenant_flag() {
    let server = TestServer::spawn_with_card_tenant(Some("card-declared-tenant")).await;

    run_cli_success(
        &server,
        &["--compact", "--tenant", "explicit-tenant", "send", "hello"],
    );

    // A2A §8.3.2 rule 4 / SPEC.md §13.1: the tenant sent MUST be exactly
    // the value the selected interface declares. --tenant does not get to
    // substitute another one (#199).
    let received = server.state.received_send_tenants.lock().unwrap().clone();
    assert_eq!(received, vec![Some("card-declared-tenant".to_string())]);
}

/// Where the card declares no tenant there is nothing to preserve, so an
/// explicit --tenant is used as given.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_tenant_flag_applies_when_the_interface_declares_none() {
    let server = TestServer::spawn().await;

    run_cli_success(
        &server,
        &["--compact", "--tenant", "explicit-tenant", "send", "hello"],
    );

    let received = server.state.received_send_tenants.lock().unwrap().clone();
    assert_eq!(received, vec![Some("explicit-tenant".to_string())]);
}

// AUTH_004 (a2aproject/a2a-rs#169).

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn debug_flag_emits_diagnostics_without_leaking_the_bearer_token() {
    let server = TestServer::spawn().await;

    // --debug's diagnostics come from the client-call interceptor pipeline
    // (LoggingInterceptor), which only runs for actual A2A operations —
    // unlike a bare `card get`, `send` goes through resolve_client and so
    // exercises it.
    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--agent-card",
            server.base_url.as_str(),
            "--debug",
            "--bearer",
            "super-secret-token",
            "--async",
            "send",
            "hello",
        ])
        .assert()
        .success()
        .get_output()
        .clone();
    let stderr = String::from_utf8(output.stderr).unwrap();

    // --debug produces *some* diagnostic output...
    assert!(!stderr.is_empty());
    // ...but never the credential value, regardless of verbosity.
    assert!(!stderr.contains("super-secret-token"));
}

// CONFIG_001 (a2aproject/a2a-rs#170).

/// A scratch working directory with `HOME`/`XDG_CONFIG_HOME` also pointed at
/// it (so `~/.config/a2a-cli/.env` resolves somewhere empty and controlled)
/// — isolates `.env`-discovery tests from both the real developer machine
/// and from each other despite running in parallel.
struct ConfigScratchDir {
    path: std::path::PathBuf,
}

impl ConfigScratchDir {
    fn new(name: &str) -> Self {
        let mut path = std::env::temp_dir();
        path.push(format!("a2acli-test-{name}-{}", std::process::id()));
        std::fs::create_dir_all(&path).unwrap();
        Self { path }
    }

    fn write_local_env(&self, contents: &str) {
        std::fs::write(self.path.join(".env"), contents).unwrap();
    }

    /// Write the global `.env` at `<xdg>/a2a-cli/.env` inside this scratch
    /// dir, and return the `<xdg>` directory for the caller to export as
    /// `XDG_CONFIG_HOME`.
    fn write_xdg_env(&self, contents: &str) -> std::path::PathBuf {
        let xdg = self.path.join("xdg");
        let dir = xdg.join("a2a-cli");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join(".env"), contents).unwrap();
        xdg
    }

    fn command(&self, server: &TestServer) -> StdCommand {
        let mut command = StdCommand::cargo_bin("a2acli").unwrap();
        command
            .current_dir(&self.path)
            .env("HOME", &self.path)
            .env_remove("XDG_CONFIG_HOME")
            .env_remove("A2ACLI_TENANT")
            .env_remove("A2ACLI_BASE_URL")
            .env_remove("A2ACLI_AGENT_CARD")
            .env_remove("A2ACLI_ENDPOINT")
            .args(["--agent-card", server.base_url.as_str()]);
        command
    }
}

impl Drop for ConfigScratchDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn local_dotenv_file_sets_a_default_without_a_flag() {
    let server = TestServer::spawn().await;
    let scratch = ConfigScratchDir::new("local-dotenv");
    scratch.write_local_env("A2ACLI_TENANT=file-tenant\n");

    let output = scratch
        .command(&server)
        .args(["--output", "json", "--compact", "send", "hello"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let response: Value = serde_json::from_str(String::from_utf8(output).unwrap().trim()).unwrap();
    assert_eq!(response["task"]["id"], "task-send");

    let received = server.state.received_send_tenants.lock().unwrap().clone();
    assert_eq!(received.last().unwrap().as_deref(), Some("file-tenant"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn real_env_var_outranks_a_local_dotenv_file() {
    let server = TestServer::spawn().await;
    let scratch = ConfigScratchDir::new("env-outranks-file");
    scratch.write_local_env("A2ACLI_TENANT=file-tenant\n");

    let output = scratch
        .command(&server)
        .env("A2ACLI_TENANT", "real-env-tenant")
        .args(["--output", "json", "--compact", "send", "hello"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let response: Value = serde_json::from_str(String::from_utf8(output).unwrap().trim()).unwrap();
    assert_eq!(response["task"]["id"], "task-send");

    let received = server.state.received_send_tenants.lock().unwrap().clone();
    assert_eq!(received.last().unwrap().as_deref(), Some("real-env-tenant"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn explicit_config_flag_overrides_local_dotenv_discovery() {
    let server = TestServer::spawn().await;
    let scratch = ConfigScratchDir::new("explicit-config-flag");
    // The auto-discovered local .env says one thing...
    scratch.write_local_env("A2ACLI_TENANT=cwd-tenant\n");
    // ...but an explicit --config file says another, and must win.
    let explicit_path = scratch.path.join("prod.env");
    std::fs::write(&explicit_path, "A2ACLI_TENANT=explicit-tenant\n").unwrap();

    let output = scratch
        .command(&server)
        .args([
            "--config",
            explicit_path.to_str().unwrap(),
            "--output",
            "json",
            "--compact",
            "send",
            "hello",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let response: Value = serde_json::from_str(String::from_utf8(output).unwrap().trim()).unwrap();
    assert_eq!(response["task"]["id"], "task-send");

    let received = server.state.received_send_tenants.lock().unwrap().clone();
    assert_eq!(received.last().unwrap().as_deref(), Some("explicit-tenant"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn config_show_reports_effective_settings_and_sources() {
    let server = TestServer::spawn().await;
    let scratch = ConfigScratchDir::new("config-show");

    let output = scratch
        .command(&server)
        .args(["--bearer", "super-secret", "config", "show"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(output).unwrap();

    // A flag-supplied credential is redacted, and its source is "flag".
    assert!(stdout.contains("bearer: (set, redacted) (source: flag)"));
    assert!(!stdout.contains("super-secret"));
    // An untouched setting reports the built-in default and its source.
    assert!(stdout.contains("(source: built-in default)"));
    assert!(stdout.contains("output: text"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn config_show_reports_dotenv_file_as_the_source() {
    let server = TestServer::spawn().await;
    let scratch = ConfigScratchDir::new("config-show-dotenv");
    scratch.write_local_env("A2ACLI_TENANT=file-tenant\n");

    let output = scratch
        .command(&server)
        .args(["config", "show"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(output).unwrap();
    assert!(stdout.contains("tenant: file-tenant (source: local .env file)"));
}

/// The global `.env` lives at `~/.config/a2a-cli/.env`, but `$XDG_CONFIG_HOME`
/// relocates `~/.config` when it is set — so the lookup has to honor it
/// rather than hard-coding the home-relative path.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn global_dotenv_is_discovered_under_xdg_config_home() {
    let server = TestServer::spawn().await;
    let scratch = ConfigScratchDir::new("config-show-xdg");
    let xdg = scratch.write_xdg_env("A2ACLI_TENANT=xdg-tenant\n");

    let output = scratch
        .command(&server)
        .env("XDG_CONFIG_HOME", &xdg)
        .args(["config", "show"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(output).unwrap();
    assert!(
        stdout.contains("tenant: xdg-tenant (source: global .env file)"),
        "{stdout}"
    );
}

/// `config show` has to report an explicit `--transport` preference in the
/// order it will actually be applied — the point of the command is to settle
/// which transport wins without having to guess.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn config_show_reports_an_explicit_transport_preference_in_order() {
    let server = TestServer::spawn().await;
    let scratch = ConfigScratchDir::new("config-show-transport");

    let output = scratch
        .command(&server)
        .args([
            "--transport",
            "rest",
            "--transport",
            "jsonrpc",
            "config",
            "show",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(output).unwrap();
    assert!(
        stdout.contains("transport: rest,jsonrpc (source: flag)"),
        "{stdout}"
    );

    // Absent the flag, the card's own ordering is reported rather than a
    // fabricated default preference.
    let output = scratch
        .command(&server)
        .args(["config", "show"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(output).unwrap();
    assert!(
        stdout.contains("transport: (agent card's own order)"),
        "{stdout}"
    );
}

// CARD_GET_001 / §10.1 (a2aproject/a2a-rs#178): the Agent Card reference.

/// A bare host or origin gets the well-known path appended — the form every
/// other test in this file relies on, asserted here explicitly.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn agent_card_accepts_a_bare_origin() {
    let server = TestServer::spawn().await;

    let stdout = run_cli_success(&server, &["card", "get"]);
    let card: Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(card["name"], "Fixture Agent");
    // The card fetch did reach the well-known handler.
    assert_eq!(server.state.card_headers.lock().unwrap().len(), 1);
}

/// A reference that already carries a path is a full card URL and is used
/// as-is — the well-known path must not be appended to it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn agent_card_accepts_a_full_card_url_without_appending_the_well_known_path() {
    let server = TestServer::spawn().await;

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let stdout = command
        .args([
            "--agent-card",
            &format!("{}/custom/card.json", server.base_url),
            "--output",
            "json",
            "card",
            "get",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let card: Value = serde_json::from_str(String::from_utf8(stdout).unwrap().trim()).unwrap();
    assert_eq!(card["name"], "Fixture Agent");
    // Served from /custom/card.json, so the well-known handler was never hit.
    assert!(server.state.card_headers.lock().unwrap().is_empty());
}

fn write_card_file(dir: &std::path::Path, name: &str, contents: &str) -> std::path::PathBuf {
    std::fs::create_dir_all(dir).unwrap();
    let path = dir.join(name);
    std::fs::write(&path, contents).unwrap();
    path
}

fn scratch_dir(name: &str) -> std::path::PathBuf {
    let mut path = std::env::temp_dir();
    path.push(format!("a2acli-card-{name}-{}", std::process::id()));
    path
}

const FILE_CARD_JSON: &str = r#"{
  "name": "File Agent",
  "description": "resolved from a local file",
  "version": "1.0",
  "supportedInterfaces": [],
  "capabilities": {},
  "defaultInputModes": [],
  "defaultOutputModes": [],
  "skills": []
}"#;

/// A plain filesystem path resolves to a card on disk — how the tool is
/// driven in tests and air-gapped environments, with no agent running.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn agent_card_reads_a_plain_local_path() {
    let dir = scratch_dir("plain-path");
    let path = write_card_file(&dir, "card.json", FILE_CARD_JSON);

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--agent-card",
            path.to_str().unwrap(),
            "--output",
            "json",
            "card",
            "get",
        ])
        .assert()
        .success()
        .get_output()
        .clone();

    let card: Value =
        serde_json::from_str(String::from_utf8(output.stdout).unwrap().trim()).unwrap();
    assert_eq!(card["name"], "File Agent");
    assert!(String::from_utf8(output.stderr).unwrap().is_empty());

    let _ = std::fs::remove_dir_all(&dir);
}

/// The `file://` form resolves the same way as a plain path.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn agent_card_reads_a_file_url() {
    let dir = scratch_dir("file-url");
    let path = write_card_file(&dir, "card.json", FILE_CARD_JSON);

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let stdout = command
        .args([
            "--agent-card",
            &format!("file://{}", path.display()),
            "--output",
            "json",
            "card",
            "get",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let card: Value = serde_json::from_str(String::from_utf8(stdout).unwrap().trim()).unwrap();
    assert_eq!(card["name"], "File Agent");

    let _ = std::fs::remove_dir_all(&dir);
}

/// Appendix D: a card file that isn't there is `CARD_NOT_FOUND`/3, the same
/// class and status as a card URL that answers non-2xx — a caller branching
/// on the exit code needn't know which form was used.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn missing_card_file_reports_card_not_found() {
    let dir = scratch_dir("missing");
    let path = dir.join("absent.json");

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args(["--agent-card", path.to_str().unwrap(), "card", "get"])
        .assert()
        .failure()
        .get_output()
        .clone();

    let envelope = parse_error_envelope(&String::from_utf8(output.stderr).unwrap());
    assert_eq!(envelope["error"]["code"], "A2ACLI_ERR_CARD_NOT_FOUND");
    assert!(envelope["error"]["hint"].is_string());
    assert_eq!(output.status.code().unwrap(), 3);
}

/// A file that is there but isn't a card is `CARD_INVALID`/1 — the same
/// split the HTTP path makes between a bad response and a bad body.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn card_file_that_is_not_a_card_reports_card_invalid() {
    let dir = scratch_dir("invalid");
    let path = write_card_file(&dir, "bad.json", r#"{"not":"a card"}"#);

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args(["--agent-card", path.to_str().unwrap(), "card", "get"])
        .assert()
        .failure()
        .get_output()
        .clone();

    let envelope = parse_error_envelope(&String::from_utf8(output.stderr).unwrap());
    assert_eq!(envelope["error"]["code"], "A2ACLI_ERR_CARD_INVALID");
    assert_eq!(output.status.code().unwrap(), 1);

    let _ = std::fs::remove_dir_all(&dir);
}

/// `--base-url` keeps working so pre-#178 invocations don't break, but says
/// it is deprecated. The warning goes to stderr and leaves stdout intact.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn base_url_still_resolves_a_card_but_warns_it_is_deprecated() {
    let server = TestServer::spawn().await;

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--base-url",
            server.base_url.as_str(),
            "--output",
            "json",
            "card",
            "get",
        ])
        .assert()
        .success()
        .get_output()
        .clone();

    let card: Value =
        serde_json::from_str(String::from_utf8(output.stdout).unwrap().trim()).unwrap();
    assert_eq!(card["name"], "Fixture Agent");

    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("--base-url is deprecated"), "{stderr}");
    assert!(stderr.contains("--agent-card"), "{stderr}");
}

/// The warning names a flag the caller actually passed: leaving `--base-url`
/// at its built-in default is not a deprecated invocation.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn default_base_url_does_not_warn_about_deprecation() {
    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args(["config", "show"])
        .assert()
        .success()
        .get_output()
        .clone();

    assert!(
        !String::from_utf8(output.stderr)
            .unwrap()
            .contains("deprecated")
    );
}

/// §7.2: `--endpoint` connects straight to an interface, so no card is
/// fetched at all — asserted against the fixture's card handler never being
/// reached, not merely against the command succeeding.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn endpoint_connects_without_resolving_a_card() {
    let server = TestServer::spawn().await;

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let stdout = command
        .args([
            "--endpoint",
            &format!("{}/jsonrpc", server.base_url),
            "--transport",
            "jsonrpc",
            "--output",
            "json",
            "task",
            "get",
            "task-1",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let task: Value = serde_json::from_str(String::from_utf8(stdout).unwrap().trim()).unwrap();
    assert_eq!(task["id"], "task-1");
    assert!(
        server.state.card_headers.lock().unwrap().is_empty(),
        "--endpoint must not resolve an agent card"
    );
}

/// With no card to declare the binding, the caller must name exactly one
/// transport: zero leaves the protocol ambiguous, more than one asks for a
/// preference order over a single interface.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn endpoint_requires_exactly_one_transport() {
    let server = TestServer::spawn().await;
    let endpoint = format!("{}/jsonrpc", server.base_url);

    for transports in [vec![], vec!["jsonrpc", "rest"]] {
        let mut command = StdCommand::cargo_bin("a2acli").unwrap();
        command.args(["--endpoint", endpoint.as_str()]);
        for transport in &transports {
            command.args(["--transport", transport]);
        }
        let output = command
            .args(["task", "get", "task-1"])
            .assert()
            .failure()
            .get_output()
            .clone();

        let envelope = parse_error_envelope(&String::from_utf8(output.stderr).unwrap());
        assert_eq!(
            envelope["error"]["code"],
            "A2ACLI_ERR_USAGE",
            "with {} transport(s)",
            transports.len()
        );
        assert_eq!(output.status.code().unwrap(), 2);
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn endpoint_and_agent_card_are_mutually_exclusive() {
    let server = TestServer::spawn().await;

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--agent-card",
            server.base_url.as_str(),
            "--endpoint",
            &format!("{}/jsonrpc", server.base_url),
            "--transport",
            "jsonrpc",
            "task",
            "get",
            "task-1",
        ])
        .assert()
        .failure()
        .get_output()
        .clone();

    let stderr = String::from_utf8(output.stderr).unwrap();
    let envelope = parse_error_envelope(&stderr);
    assert_eq!(envelope["error"]["code"], "A2ACLI_ERR_USAGE");
    assert!(
        envelope["error"]["message"]
            .as_str()
            .unwrap()
            .contains("mutually exclusive"),
        "{stderr}"
    );
    assert_eq!(output.status.code().unwrap(), 2);
}

/// `config show` answers "which agent am I talking to?" in one line, so the
/// reader doesn't have to apply the reference rules themselves.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn config_show_reports_the_resolved_card_reference() {
    let server = TestServer::spawn().await;
    let scratch = ConfigScratchDir::new("resolved-card");

    let stdout = String::from_utf8(
        scratch
            .command(&server)
            .args(["config", "show"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        stdout.contains(&format!(
            "resolved-card: {}/.well-known/agent-card.json",
            server.base_url
        )),
        "{stdout}"
    );

    // Under --endpoint there is no card to resolve, and the line says so
    // rather than reporting a URL that is never fetched.
    let stdout = String::from_utf8(
        scratch
            .command(&server)
            .args([
                "--endpoint",
                &format!("{}/jsonrpc", server.base_url),
                "--transport",
                "jsonrpc",
                "config",
                "show",
            ])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        stdout.contains("resolved-card: (none; --endpoint"),
        "{stdout}"
    );
}

/// A local card file is reported as the file it will be read from, not as a
/// URL that would never be fetched. Built without `ConfigScratchDir`, whose
/// base command already supplies `--agent-card`.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn config_show_reports_a_local_card_file_as_the_resolved_card() {
    let dir = scratch_dir("resolved-card-file");
    let path = write_card_file(&dir, "card.json", FILE_CARD_JSON);

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let stdout = command
        .env_remove("A2ACLI_AGENT_CARD")
        .env_remove("A2ACLI_BASE_URL")
        .env_remove("A2ACLI_ENDPOINT")
        .args(["--agent-card", path.to_str().unwrap(), "config", "show"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let stdout = String::from_utf8(stdout).unwrap();
    assert!(
        stdout.contains(&format!("resolved-card: file://{}", path.display())),
        "{stdout}"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

// VER_001 / §13.2 (a2aproject/a2a-rs#179): protocol version signaling.

/// §13.2: the version is signaled on **every** request, and exactly once —
/// A2A reads an empty value as 0.3, and two values would leave which one
/// applies undefined.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a2a_version_is_signaled_once_on_every_request() {
    let server = TestServer::spawn().await;

    run_cli_success(&server, &["task", "get", "task-1"]);

    let headers = server.state.agent_headers.lock().unwrap().clone();
    assert!(
        !headers.is_empty(),
        "the agent call should have been recorded"
    );
    for (_, _, _, version) in &headers {
        // The fixture card declares this build's own version, so nothing is
        // negotiated away and exactly one value is sent.
        assert_eq!(version.as_deref(), Some(a2a::VERSION), "{headers:?}");
    }
}

/// An explicit `--a2a-version` is what goes on the wire, replacing the
/// client library's default rather than being appended to it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn explicit_a2a_version_replaces_the_default_rather_than_appending() {
    let server = TestServer::spawn().await;

    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args([
            "--agent-card",
            server.base_url.as_str(),
            "--output",
            "json",
            "--a2a-version",
            "1.4",
            "task",
            "get",
            "task-1",
        ])
        .assert()
        .success()
        .get_output()
        .clone();

    let headers = server.state.agent_headers.lock().unwrap().clone();
    let version = headers.last().unwrap().3.clone();
    // Exactly "1.4" — not "1.0,1.4", which is what appending would produce.
    assert_eq!(version.as_deref(), Some("1.4"), "{headers:?}");

    // §13.2: no silent change of the signaled version.
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("signaling A2A-Version 1.4"), "{stderr}");
}

/// §11.6: a bad `--a2a-version` is a usage error, reported before any
/// network work — it must not need a reachable agent to surface.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn invalid_a2a_version_is_a_usage_error_without_contacting_the_agent() {
    let server = TestServer::spawn().await;

    for bad in ["0.3", "2.0", "nonsense"] {
        let mut command = StdCommand::cargo_bin("a2acli").unwrap();
        let output = command
            .args([
                "--agent-card",
                server.base_url.as_str(),
                "--a2a-version",
                bad,
                "card",
                "get",
            ])
            .assert()
            .failure()
            .get_output()
            .clone();

        let envelope = parse_error_envelope(&String::from_utf8(output.stderr).unwrap());
        assert_eq!(
            envelope["error"]["code"], "A2ACLI_ERR_USAGE",
            "version {bad}"
        );
        assert_eq!(output.status.code().unwrap(), 2, "version {bad}");
    }

    // No card was ever fetched: the flag was rejected first.
    assert!(
        server.state.card_headers.lock().unwrap().is_empty(),
        "a usage error must not require contacting the agent"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn config_show_reports_the_effective_a2a_version() {
    let server = TestServer::spawn().await;
    let scratch = ConfigScratchDir::new("a2a-version");

    let stdout = String::from_utf8(
        scratch
            .command(&server)
            .args(["config", "show"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        stdout.contains("a2a-version: (negotiated from the agent card"),
        "{stdout}"
    );

    let stdout = String::from_utf8(
        scratch
            .command(&server)
            .args(["--a2a-version", "1.2", "config", "show"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        stdout.contains("a2a-version: 1.2 (source: flag)"),
        "{stdout}"
    );
}

// EXIT_002 / §6.6, §11.6 (a2aproject/a2a-rs#180): a non-success or paused
// outcome is named on stderr, while the exit status still reports only
// whether the CLI did its job.

/// Helper: run without `--output` overriding, returning (stdout, stderr, code).
fn run_cli_capturing(server: &TestServer, args: &[&str]) -> (String, String, i32) {
    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .args(["--agent-card", server.base_url.as_str()])
        .args(args)
        .assert()
        .success()
        .get_output()
        .clone();
    (
        String::from_utf8(output.stdout).unwrap(),
        String::from_utf8(output.stderr).unwrap(),
        output.status.code().unwrap(),
    )
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn failed_and_rejected_outcomes_are_named_on_stderr_and_still_exit_zero() {
    let server = TestServer::spawn().await;

    let (stdout, stderr, code) = run_cli_capturing(&server, &["task", "get", "task-failed"]);
    // §6.6: the CLI conducted and reported the turn, so it succeeded.
    assert_eq!(code, 0);
    assert!(stderr.contains("warning: task task-failed:"), "{stderr}");
    assert!(stderr.contains("FAILED"), "{stderr}");
    // The outcome is still carried in the payload on stdout.
    assert!(stdout.contains("State: FAILED"), "{stdout}");

    let (_stdout, stderr, code) = run_cli_capturing(&server, &["task", "get", "task-rejected"]);
    assert_eq!(code, 0);
    assert!(stderr.contains("warning: task task-rejected:"), "{stderr}");
    assert!(stderr.contains("REJECTED"), "{stderr}");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_paused_outcome_is_named_on_stderr() {
    let server = TestServer::spawn().await;

    let (stdout, stderr, code) = run_cli_capturing(&server, &["task", "get", "task-needs-input"]);
    assert_eq!(code, 0);
    assert!(stderr.contains("INPUT_REQUIRED"), "{stderr}");
    assert!(stderr.contains("needs a reply"), "{stderr}");
    // The resume hint stays on stdout, where it is copy-pasteable
    // (INTERACT_004); the warning does not replace it.
    assert!(stdout.contains("Resume with: a2acli send"), "{stdout}");
}

/// §11.4's rule for the error envelope applies here too: diagnostics are not
/// gated on the output format.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_outcome_warning_is_emitted_in_json_mode_too() {
    let server = TestServer::spawn().await;

    let (stdout, stderr, _code) =
        run_cli_capturing(&server, &["--output", "json", "task", "get", "task-failed"]);

    assert!(stderr.contains("warning: task task-failed:"), "{stderr}");
    // stdout stays exactly the protocol document — the warning never
    // contaminates the payload (§11.1).
    let task: Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(task["id"], "task-failed");
    assert_eq!(task["status"]["state"], "TASK_STATE_FAILED");
}

/// A successful task says nothing, and neither does a cancel: `CANCELED` is
/// the outcome `task cancel` was asked for, so warning about it is noise.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn successful_and_cancelled_outcomes_stay_silent() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr, code) = run_cli_capturing(&server, &["task", "get", "task-1"]);
    assert_eq!(code, 0);
    assert!(
        stderr.is_empty(),
        "completed task should be silent: {stderr}"
    );

    let (stdout, stderr, code) = run_cli_capturing(&server, &["task", "cancel", "task-1"]);
    assert_eq!(code, 0);
    assert!(stdout.contains("State: CANCELED"), "{stdout}");
    assert!(
        !stderr.contains("warning: task"),
        "cancel should not warn about the state it was asked to produce: {stderr}"
    );
}

/// `send` reports through the same path, so a task that lands non-successful
/// is named there too rather than only under `task get`.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_names_a_non_success_outcome() {
    let server = TestServer::spawn().await;

    let (stdout, stderr, code) = run_cli_capturing(&server, &["send", "send-failing"]);

    assert_eq!(code, 0);
    assert!(stderr.contains("warning: task task-send:"), "{stderr}");
    assert!(stderr.contains("FAILED"), "{stderr}");
    assert!(stdout.contains("State: FAILED"), "{stdout}");
}

/// Streamed status updates carry the outcome too, so `--stream` and
/// `task subscribe` are not a silent path around the warning.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn streamed_status_updates_name_a_paused_outcome() {
    let server = TestServer::spawn().await;

    let (_stdout, stderr, code) =
        run_cli_capturing(&server, &["task", "subscribe", "task-needs-input"]);

    assert_eq!(code, 0);
    assert!(
        stderr.contains("warning: task task-needs-input:"),
        "{stderr}"
    );
}

// OUT_004 / §11.4 (a2aproject/a2a-rs#193): a malformed invocation is a
// CLI-local failure and must still be machine-readable.

/// Run `a2acli` with no agent configured at all — a parse failure must be
/// reported without contacting anything.
fn run_raw(args: &[&str]) -> (String, String, i32) {
    let mut command = StdCommand::cargo_bin("a2acli").unwrap();
    let output = command
        .env_remove("A2ACLI_AGENT_CARD")
        .env_remove("A2ACLI_BASE_URL")
        .env_remove("A2ACLI_ENDPOINT")
        .args(args)
        .output()
        .unwrap();
    (
        String::from_utf8(output.stdout).unwrap(),
        String::from_utf8(output.stderr).unwrap(),
        output.status.code().unwrap(),
    )
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_malformed_invocation_reports_the_error_envelope() {
    // An unknown flag, a missing required argument, and an invalid enum
    // value are all parse failures, and all three are CLI-local (§11.4).
    let cases: [(&[&str], &str); 3] = [
        (&["--bogus-flag", "card", "get"], "--bogus-flag"),
        (&["task", "get"], "required"),
        (&["--transport", "smoke", "card", "get"], "smoke"),
    ];

    for (args, expected_fragment) in cases {
        let (stdout, stderr, code) = run_raw(args);

        let envelope = parse_error_envelope(&stderr);
        assert_eq!(
            envelope["error"]["code"], "A2ACLI_ERR_USAGE",
            "args {args:?}"
        );
        // clap's message is kept, since it names the offending argument.
        let message = envelope["error"]["message"].as_str().unwrap();
        assert!(
            message.contains(expected_fragment),
            "args {args:?}: {message}"
        );
        // One line, one object (§11.4) — no usage block trailing it.
        assert_eq!(stderr.trim().lines().count(), 1, "args {args:?}: {stderr}");
        assert!(envelope["error"]["hint"].is_string(), "args {args:?}");
        assert_eq!(code, 2, "args {args:?}");
        // §11.1: nothing on stdout when the command failed.
        assert!(stdout.is_empty(), "args {args:?}: {stdout}");
    }
}

/// `--help` and `--version` travel the same clap `Err` channel as a parse
/// failure but are not failures: they keep writing to stdout and exiting 0
/// (`A2ACLI_CLI_001`).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn help_and_version_are_not_treated_as_usage_errors() {
    for args in [
        vec!["--help"],
        vec!["-h"],
        vec!["help"],
        vec!["card", "--help"],
    ] {
        let (stdout, stderr, code) = run_raw(&args);
        assert_eq!(code, 0, "args {args:?}");
        assert!(!stdout.is_empty(), "args {args:?} should print to stdout");
        assert!(stderr.is_empty(), "args {args:?}: {stderr}");
        // Not an error envelope.
        assert!(!stdout.contains("A2ACLI_ERR"), "args {args:?}");
    }

    for args in [vec!["--version"], vec!["-V"]] {
        let (stdout, stderr, code) = run_raw(&args);
        assert_eq!(code, 0, "args {args:?}");
        assert!(stdout.contains("a2acli"), "args {args:?}: {stdout}");
        assert!(stderr.is_empty(), "args {args:?}: {stderr}");
    }
}

/// A bare invocation, and a command group with no subcommand, are usage
/// failures — clap already exits 2 for them — so they carry the envelope
/// like every other usage error rather than printing prose, with the hint
/// pointing at `--help` for the usage text it replaces.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_missing_subcommand_reports_the_error_envelope() {
    for args in [
        vec![],
        vec!["task"],
        vec!["card"],
        vec!["task", "push-config"],
    ] {
        let (stdout, stderr, code) = run_raw(&args);

        let envelope = parse_error_envelope(&stderr);
        assert_eq!(
            envelope["error"]["code"], "A2ACLI_ERR_USAGE",
            "args {args:?}"
        );
        assert!(
            envelope["error"]["hint"]
                .as_str()
                .unwrap()
                .contains("--help"),
            "args {args:?}"
        );
        assert_eq!(code, 2, "args {args:?}");
        assert!(stdout.is_empty(), "args {args:?}: {stdout}");
    }
}