a3s 0.10.5

a3s — A3S coding agent CLI; `a3s code` launches the interactive TUI
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
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use a3s_code_core::tools::{Tool, ToolContext, ToolErrorKind, ToolExecutor, ToolOutput};
use tokio::sync::Notify;

struct SearchFixture {
    queries: Arc<Mutex<Vec<String>>>,
    results: serde_json::Value,
}

struct QuerySearchFixture {
    queries: Arc<Mutex<Vec<String>>>,
    results_by_query: BTreeMap<String, serde_json::Value>,
}

struct FallbackNoticeSearchFixture {
    queries: Arc<Mutex<Vec<String>>>,
    results: serde_json::Value,
}

struct TextFetchFixture {
    urls: Arc<Mutex<Vec<String>>>,
    bodies: BTreeMap<String, String>,
}

struct SemanticSelectorFixture {
    preferred_fragments: Vec<String>,
    fail: bool,
    invalid_selection: bool,
}

struct RetryOnceSemanticSelectorFixture {
    calls: Arc<AtomicUsize>,
    selector: SemanticSelectorFixture,
    retry_web_source_selection: bool,
}

struct FailMatchingSemanticSelectorFixture {
    schema_name: &'static str,
    fragment: String,
    selector: SemanticSelectorFixture,
}

struct FailWebSourceSelectionFixture {
    selector: SemanticSelectorFixture,
}

struct PaginatedPdfFixture {
    offsets: Arc<Mutex<Vec<u64>>>,
}

struct PaginatedHtmlFixture {
    offsets: Arc<Mutex<Vec<u64>>>,
}

struct TransientFetchFixture {
    calls: Arc<Mutex<Vec<String>>>,
}

struct UntypedFetchFailureFixture {
    calls: Arc<AtomicUsize>,
}

struct InterruptedSiblingFetchFixture {
    calls: Arc<Mutex<Vec<String>>>,
    blocked_url: String,
    blocked_started: Arc<Notify>,
}

struct LocalEvidenceFixture;

const PDF_RANGE_ONE: &str =
    "第一段记录了双阶段检索方法以及证据保留边界,内容足够构成一个结构化文本块。";
const PDF_RANGE_TWO: &str = "第二段报告消融实验使引用完整率下降十七个百分点,并给出明确测量条件。";
const PDF_RANGE_THREE: &str =
    "第三段说明评测只覆盖英语技术主题,因此其他语言和领域仍然属于证据缺口。";
const HTML_RANGE_ONE: &str = "项目记录前段说明了阶段一背景和参与方,并提示后续还有完整进展记录。";
const HTML_RANGE_TWO: &str = "项目记录后段说明了阶段二进展,并确认阶段三结论、最终指标和发布日期。";
const HTML_RANGE_THREE: &str = "项目记录末段确认阶段三结论、最终指标和发布日期,构成完整事实记录。";

#[async_trait::async_trait]
impl Tool for SearchFixture {
    fn name(&self) -> &str {
        "fixture_web_search"
    }

    fn description(&self) -> &str {
        "Returns deterministic search candidates."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        assert!(
            args.get("engines").is_none(),
            "DeepResearch must inherit the default search engines from config.acl"
        );
        self.queries.lock().unwrap().push(
            args.get("query")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string(),
        );
        Ok(ToolOutput::success(self.results.to_string()))
    }
}

#[async_trait::async_trait]
impl Tool for QuerySearchFixture {
    fn name(&self) -> &str {
        "fixture_query_web_search"
    }

    fn description(&self) -> &str {
        "Returns deterministic candidates for each exact provider query."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        assert!(
            args.get("engines").is_none(),
            "DeepResearch must inherit the default search engines from config.acl"
        );
        let query = args
            .get("query")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string();
        self.queries.lock().unwrap().push(query.clone());
        let results = self
            .results_by_query
            .get(&query)
            .ok_or_else(|| anyhow::anyhow!("unexpected fixture query: {query}"))?;
        Ok(ToolOutput::success(results.to_string()))
    }
}

#[async_trait::async_trait]
impl Tool for FallbackNoticeSearchFixture {
    fn name(&self) -> &str {
        "fixture_fallback_web_search"
    }

    fn description(&self) -> &str {
        "Returns deterministic candidates with generic fallback metadata."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        assert!(
            args.get("engines").is_none(),
            "DeepResearch must inherit the default search engines from config.acl"
        );
        self.queries.lock().unwrap().push(
            args.get("query")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string(),
        );
        Ok(ToolOutput::success(self.results.to_string()).with_metadata(
            serde_json::json!({
                "status": "partial",
                "engine_selection_source": "config",
                "selected_engines": ["anysearch"],
                "notices": [
                    "Search degraded because AnySearch quota is exhausted; automatically fell back to Brave and Bing."
                ],
                "search_fallback": {
                    "trigger": "engine_failure",
                    "mode": "additional_engines",
                    "attempted": true,
                    "engines": ["brave", "bing"],
                    "successful": true,
                    "failures": [{
                        "engine": "AnySearch",
                        "provider": "anysearch",
                        "kind": "provider_quota",
                        "transient": false
                    }]
                }
            }),
        ))
    }
}

#[async_trait::async_trait]
impl Tool for TextFetchFixture {
    fn name(&self) -> &str {
        "fixture_web_fetch"
    }

    fn description(&self) -> &str {
        "Returns deterministic fetched source text."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        let url = args
            .get("url")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string();
        self.urls.lock().unwrap().push(url.clone());
        let body = self
            .bodies
            .get(&url)
            .ok_or_else(|| anyhow::anyhow!("unexpected fixture URL: {url}"))?;
        let offset = args
            .get("offset")
            .and_then(serde_json::Value::as_u64)
            .and_then(|value| usize::try_from(value).ok())
            .unwrap_or(0);
        let maximum = args
            .get("max_chars")
            .and_then(serde_json::Value::as_u64)
            .and_then(|value| usize::try_from(value).ok())
            .unwrap_or(50_000);
        let total_chars = body.chars().count();
        if offset > total_chars {
            return Ok(ToolOutput::error("fixture offset exceeds body"));
        }
        let content = body.chars().skip(offset).take(maximum).collect::<String>();
        let returned_chars = content.chars().count();
        let next_offset =
            (offset + returned_chars < total_chars).then_some(offset + returned_chars);
        let mut output = content;
        if let Some(next_offset) = next_offset {
            output.push_str(&format!(
                "\n\n... (fixture continuation; offset={next_offset})\n"
            ));
        }
        Ok(
            ToolOutput::success(output).with_metadata(serde_json::json!({
                "source_anchors": [url],
                "document_kind": "html",
                "content_type": "text/html",
                "range": {
                    "offset": offset,
                    "requested_max_chars": maximum,
                    "applied_max_chars": maximum,
                    "returned_chars": returned_chars,
                    "total_chars": total_chars,
                    "next_offset": next_offset,
                    "eof": next_offset.is_none(),
                    "limit_clamped": false
                }
            })),
        )
    }
}

#[async_trait::async_trait]
impl Tool for InterruptedSiblingFetchFixture {
    fn name(&self) -> &str {
        "fixture_interrupted_sibling_web_fetch"
    }

    fn description(&self) -> &str {
        "Completes one source while holding the first attempt for another source."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        let url = args
            .get("url")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string();
        let attempt = {
            let mut calls = self.calls.lock().unwrap();
            calls.push(url.clone());
            calls.iter().filter(|observed| *observed == &url).count()
        };
        if url == self.blocked_url && attempt == 1 {
            self.blocked_started.notify_one();
            std::future::pending::<()>().await;
        }
        let output = format!(
            "Durable source material for {url} remains independently recoverable after interruption."
        );
        let returned_chars = output.chars().count();
        Ok(
            ToolOutput::success(output).with_metadata(serde_json::json!({
                "source_anchors": [url],
                "document_kind": "html",
                "content_type": "text/html",
                "range": {
                    "offset": 0,
                    "requested_max_chars": 50_000,
                    "applied_max_chars": 50_000,
                    "returned_chars": returned_chars,
                    "total_chars": returned_chars,
                    "next_offset": null,
                    "eof": true,
                    "limit_clamped": false
                }
            })),
        )
    }
}

#[async_trait::async_trait]
impl Tool for SemanticSelectorFixture {
    fn name(&self) -> &str {
        "generate_object"
    }

    fn description(&self) -> &str {
        "Selects semantic chunk IDs from the closed evidence packet."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        let schema_name = args.get("schema_name").and_then(serde_json::Value::as_str);
        if matches!(
            schema_name,
            Some(
                "deep_research_web_source_selection"
                    | "deep_research_supplemental_web_source_selection"
            )
        ) {
            let prompt = args
                .get("prompt")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default();
            let marker = if schema_name == Some("deep_research_supplemental_web_source_selection") {
                "CLOSED_SUPPLEMENTAL_DISCOVERY_PACKET="
            } else {
                "CLOSED_WEB_DISCOVERY_PACKET="
            };
            let packet = prompt
                .split_once(marker)
                .map(|(_, packet)| packet)
                .ok_or_else(|| {
                    anyhow::anyhow!("web source selector omitted its closed discovery packet")
                })?;
            let packet: serde_json::Value = serde_json::from_str(packet)?;
            let candidates = packet["candidates"]
                .as_array()
                .ok_or_else(|| anyhow::anyhow!("web source selector packet omitted candidates"))?;
            let maximum = args["schema"]["properties"]["candidate_ids"]["maxItems"]
                .as_u64()
                .unwrap_or(candidates.len() as u64) as usize;
            let mut candidate_ids = Vec::new();
            for preferred in &self.preferred_fragments {
                if let Some(candidate) = candidates.iter().find(|candidate| {
                    ["title", "url", "content"].iter().any(|field| {
                        candidate[*field]
                            .as_str()
                            .is_some_and(|text| text.contains(preferred))
                    })
                }) {
                    let candidate_id = candidate["candidate_id"]
                        .as_str()
                        .ok_or_else(|| anyhow::anyhow!("candidate omitted ID"))?;
                    if !candidate_ids.iter().any(|seen| seen == candidate_id) {
                        candidate_ids.push(candidate_id.to_string());
                    }
                }
            }
            if candidate_ids.is_empty() {
                candidate_ids.extend(
                    candidates
                        .iter()
                        .take(maximum)
                        .filter_map(|candidate| candidate["candidate_id"].as_str())
                        .map(str::to_string),
                );
            }
            candidate_ids.truncate(maximum);
            return Ok(ToolOutput::success(
                serde_json::json!({
                    "object": { "candidate_ids": candidate_ids },
                    "repair_rounds": 0,
                    "mode_used": "fixture"
                })
                .to_string(),
            ));
        }
        if self.fail {
            return Ok(ToolOutput::error("simulated semantic selector failure"));
        }
        if self.invalid_selection {
            return Ok(ToolOutput::success(
                serde_json::json!({
                    "object": {
                        "chunk_ids": ["source-1:chunk:not-in-catalog"],
                        "source_coverage": [],
                        "source_relevance": []
                    },
                    "repair_rounds": 0,
                    "mode_used": "fixture"
                })
                .to_string(),
            ));
        }
        let prompt = args
            .get("prompt")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        let packet = prompt
            .split_once("CLOSED_EVIDENCE_PACKET=")
            .map(|(_, packet)| packet)
            .ok_or_else(|| anyhow::anyhow!("selector omitted its closed evidence packet"))?;
        let packet: serde_json::Value = serde_json::from_str(packet)?;
        let focuses = packet["focuses"]
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("selector packet omitted focuses"))?;
        for focus in focuses {
            assert!(
                focus["obligation_id"].is_string(),
                "selector focus omitted its stable obligation identity"
            );
            assert!(
                focus["material"].is_boolean(),
                "selector focus omitted its materiality"
            );
            assert!(
                focus["completion_criteria"].is_array(),
                "selector focus omitted its completion criteria"
            );
            assert!(
                focus["evidence_requirements"].is_object(),
                "selector focus omitted its source-quality requirements"
            );
        }
        let sources = packet["sources"]
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("selector packet omitted sources"))?;
        let mut chunk_ids = Vec::new();
        for source in sources {
            let chunks = source["chunks"]
                .as_array()
                .ok_or_else(|| anyhow::anyhow!("selector source omitted chunks"))?;
            let mut retained_for_source = Vec::new();
            for preferred in &self.preferred_fragments {
                if let Some(chunk) = chunks.iter().find(|chunk| {
                    chunk["text"]
                        .as_str()
                        .is_some_and(|text| text.contains(preferred))
                }) {
                    let chunk_id = chunk["chunk_id"]
                        .as_str()
                        .ok_or_else(|| anyhow::anyhow!("selector chunk omitted ID"))?;
                    if !retained_for_source.iter().any(|seen| seen == chunk_id) {
                        retained_for_source.push(chunk_id.to_string());
                    }
                }
            }
            if retained_for_source.is_empty() {
                let chunk_id = chunks
                    .first()
                    .and_then(|chunk| chunk["chunk_id"].as_str())
                    .ok_or_else(|| anyhow::anyhow!("selector source omitted chunks"))?;
                retained_for_source.push(chunk_id.to_string());
            }
            chunk_ids.extend(retained_for_source);
        }
        let maximum = args["schema"]["properties"]["chunk_ids"]["maxItems"]
            .as_u64()
            .unwrap_or(chunk_ids.len() as u64) as usize;
        chunk_ids.truncate(maximum);
        let selected_chunk_ids = chunk_ids
            .iter()
            .map(String::as_str)
            .collect::<std::collections::HashSet<_>>();
        let mut source_coverage = Vec::new();
        let mut source_relevance = Vec::new();
        for source in sources {
            let selected = source["chunks"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(|chunk| chunk["chunk_id"].as_str())
                .any(|chunk_id| selected_chunk_ids.contains(chunk_id));
            if !selected {
                continue;
            }
            let source_id = source["source_id"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("selector source omitted ID"))?;
            for focus in focuses {
                source_relevance.push(serde_json::json!({
                    "source_id": source_id,
                    "obligation_id": focus["obligation_id"],
                }));
                let completion_criterion_count = focus["completion_criteria"]
                    .as_array()
                    .map(Vec::len)
                    .unwrap_or_default();
                let roles = serde_json::json!({
                    "supporting": true,
                    "primary":
                        focus["evidence_requirements"]["primary_source_required"] == true,
                    "independent":
                        focus["evidence_requirements"]["independent_corroboration_required"]
                            == true,
                });
                source_coverage.push(serde_json::json!({
                    "source_id": source_id,
                    "obligation_id": focus["obligation_id"],
                    "completion_criterion_indexes":
                        (0..completion_criterion_count).collect::<Vec<_>>(),
                    "roles": roles,
                }));
            }
        }
        assert!(
            !focuses.is_empty(),
            "selector packet omitted semantic focuses"
        );
        Ok(ToolOutput::success(
            serde_json::json!({
                "object": {
                    "chunk_ids": chunk_ids,
                    "source_coverage": source_coverage,
                    "source_relevance": source_relevance
                },
                "repair_rounds": 0,
                "mode_used": "fixture"
            })
            .to_string(),
        ))
    }
}

#[async_trait::async_trait]
impl Tool for RetryOnceSemanticSelectorFixture {
    fn name(&self) -> &str {
        "generate_object"
    }

    fn description(&self) -> &str {
        "Fails once before selecting semantic chunk IDs from the closed evidence packet."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        let web_source_selection = matches!(
            args.get("schema_name").and_then(serde_json::Value::as_str),
            Some(
                "deep_research_web_source_selection"
                    | "deep_research_supplemental_web_source_selection"
            )
        );
        if web_source_selection == self.retry_web_source_selection
            && self.calls.fetch_add(1, Ordering::SeqCst) == 0
        {
            return Ok(ToolOutput::error(
                "simulated transient semantic selector failure",
            ));
        }
        self.selector.execute(args, ctx).await
    }
}

#[async_trait::async_trait]
impl Tool for FailMatchingSemanticSelectorFixture {
    fn name(&self) -> &str {
        "generate_object"
    }

    fn description(&self) -> &str {
        "Fails only semantic selector packets containing one exact fixture fragment."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        let prompt = args
            .get("prompt")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        if args["schema_name"] == self.schema_name && prompt.contains(&self.fragment) {
            return Ok(ToolOutput::error("simulated source-local shard timeout"));
        }
        self.selector.execute(args, ctx).await
    }
}

#[async_trait::async_trait]
impl Tool for FailWebSourceSelectionFixture {
    fn name(&self) -> &str {
        "generate_object"
    }

    fn description(&self) -> &str {
        "Fails web source admission while allowing fetched-text selection."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        if matches!(
            args.get("schema_name").and_then(serde_json::Value::as_str),
            Some(
                "deep_research_web_source_selection"
                    | "deep_research_supplemental_web_source_selection"
            )
        ) {
            return Ok(ToolOutput::error(
                "simulated permanent web source admission failure",
            ));
        }
        self.selector.execute(args, ctx).await
    }
}

#[async_trait::async_trait]
impl Tool for PaginatedPdfFixture {
    fn name(&self) -> &str {
        "fixture_pdf_fetch"
    }

    fn description(&self) -> &str {
        "Returns three deterministic extracted PDF ranges from one admitted source."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        let offset = args
            .get("offset")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or_default();
        self.offsets.lock().unwrap().push(offset);
        let second_offset = PDF_RANGE_ONE.chars().count() as u64;
        let third_offset = second_offset + PDF_RANGE_TWO.chars().count() as u64;
        let (body, next_offset) = match offset {
            0 => (PDF_RANGE_ONE, Some(second_offset)),
            value if value == second_offset => (PDF_RANGE_TWO, Some(third_offset)),
            value if value == third_offset => (PDF_RANGE_THREE, None),
            _ => return Ok(ToolOutput::error("unexpected PDF range offset")),
        };
        Ok(ToolOutput::success(body).with_metadata(serde_json::json!({
            "document_kind": "pdf",
            "content_type": "application/pdf",
            "range": {
                "offset": offset,
                "returned_chars": body.chars().count(),
                "next_offset": next_offset,
                "eof": next_offset.is_none()
            }
        })))
    }
}

#[async_trait::async_trait]
impl Tool for PaginatedHtmlFixture {
    fn name(&self) -> &str {
        "fixture_html_fetch"
    }

    fn description(&self) -> &str {
        "Returns three deterministic HTML ranges from one admitted source."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        let offset = args
            .get("offset")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or_default();
        self.offsets.lock().unwrap().push(offset);
        let second_offset = HTML_RANGE_ONE.chars().count() as u64;
        let third_offset = second_offset + HTML_RANGE_TWO.chars().count() as u64;
        let (body, next_offset) = match offset {
            0 => (HTML_RANGE_ONE, Some(second_offset)),
            value if value == second_offset => (HTML_RANGE_TWO, Some(third_offset)),
            value if value == third_offset => (HTML_RANGE_THREE, None),
            _ => return Ok(ToolOutput::error("unexpected HTML range offset")),
        };
        Ok(ToolOutput::success(body).with_metadata(serde_json::json!({
            "document_kind": "html",
            "content_type": "text/html; charset=utf-8",
            "range": {
                "offset": offset,
                "returned_chars": body.chars().count(),
                "next_offset": next_offset,
                "eof": next_offset.is_none()
            }
        })))
    }
}

#[async_trait::async_trait]
impl Tool for TransientFetchFixture {
    fn name(&self) -> &str {
        "fixture_transient_fetch"
    }

    fn description(&self) -> &str {
        "Fails each initial fetch and succeeds on the bounded retry."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        let url = args
            .get("url")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string();
        let attempt = {
            let mut calls = self.calls.lock().unwrap();
            calls.push(url.clone());
            calls.iter().filter(|observed| *observed == &url).count()
        };
        if attempt == 1 {
            return Ok(ToolOutput::error("typed timeout failure").with_error_kind(
                ToolErrorKind::Timeout {
                    op: "fixture fetch".to_string(),
                    duration_ms: 1_000,
                },
            ));
        }
        let output =
            format!("The bounded retry fetched substantive authoritative evidence from {url}.");
        Ok(
            ToolOutput::success(output.clone()).with_metadata(serde_json::json!({
                "source_anchors": [url],
                "document_kind": "html",
                "content_type": "text/html",
                "range": {
                    "offset": 0,
                    "returned_chars": output.chars().count(),
                    "next_offset": null,
                    "eof": true
                }
            })),
        )
    }
}

#[async_trait::async_trait]
impl Tool for UntypedFetchFailureFixture {
    fn name(&self) -> &str {
        "fixture_untyped_fetch_failure"
    }

    fn description(&self) -> &str {
        "Returns transport-like prose without a typed error classification."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        _args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        Ok(ToolOutput::error("TLS handshake timed out during lookup"))
    }
}

#[async_trait::async_trait]
impl Tool for LocalEvidenceFixture {
    fn name(&self) -> &str {
        "task"
    }

    fn description(&self) -> &str {
        "Returns observed and fabricated local source paths."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(
        &self,
        _args: &serde_json::Value,
        _ctx: &ToolContext,
    ) -> anyhow::Result<ToolOutput> {
        Ok(
            ToolOutput::success("local evidence").with_metadata(serde_json::json!({
                "success": true,
                "source_anchors": [{
                    "tool": "read",
                    "url_or_path": "src/research.rs"
                }, {
                    "tool": "ls",
                    "url_or_path": "src/listed-only.rs"
                }],
                "structured": {
                    "sources": [{
                        "url_or_path": "src/research.rs",
                        "ranges": [{"offset": 0, "limit": 20}]
                    }, {
                        "url_or_path": "src/fabricated.rs",
                        "ranges": [{"offset": 0, "limit": 20}]
                    }, {
                        "url_or_path": "src/listed-only.rs",
                        "ranges": [{"offset": 0, "limit": 20}]
                    }]
                }
            })),
        )
    }
}

fn minimal_plan(
    tracks: serde_json::Value,
    search_queries: serde_json::Value,
    seed_urls: serde_json::Value,
) -> serde_json::Value {
    serde_json::json!({
        "report_title": "Retrieval fixture",
        "research_scope": "focused",
        "freshness_required": false,
        "workspace_evidence_required": false,
        "tracks": tracks,
        "search_queries": search_queries,
        "seed_urls": seed_urls,
        "budget": {
            "retrieval_timeout_ms": 30_000,
            "direct_searches": 4,
            "direct_fetches": 8
        },
        "stop_conditions": ["Retain traceable evidence or a bounded gap."]
    })
}

fn track(id: &str, title: &str, focus: &str) -> serde_json::Value {
    serde_json::json!({
        "id": id,
        "title": title,
        "focus": focus,
        "material": true,
        "questions": [focus],
        "completion_criteria": ["The focus has traceable evidence or a bounded gap."],
        "evidence_requirements": {
            "primary_source_required": false,
            "independent_corroboration_required": false
        }
    })
}

fn replace_web_tools(source: &str, search: &str, fetch: &str) -> String {
    source
        .replace("ctx.tool(\"web_search\"", &format!("ctx.tool(\"{search}\""))
        .replace("ctx.tool(\"web_fetch\"", &format!("ctx.tool(\"{fetch}\""))
        .replace("tool: \"web_search\"", &format!("tool: \"{search}\""))
        .replace("tool: \"web_fetch\"", &format!("tool: \"{fetch}\""))
}

fn workflow_args(
    query: &str,
    scope: super::DeepResearchEvidenceScope,
    plan: serde_json::Value,
    search: &str,
    fetch: &str,
) -> serde_json::Value {
    let mut args = super::deep_research_workflow_args_with_scope(query, scope);
    args["input"]["research_plan"] = plan;
    args["input"]["execution_mode"] = serde_json::json!("collect_only");
    args["limits"]["timeoutMs"] = serde_json::json!(45_000);
    args["limits"]["maxToolCalls"] = serde_json::json!(24);
    if scope == super::DeepResearchEvidenceScope::WebAndWorkspace {
        args["source"] = serde_json::Value::String(replace_web_tools(
            args["source"].as_str().expect("workflow source"),
            search,
            fetch,
        ));
    }
    args
}

async fn execute(executor: &ToolExecutor, args: &serde_json::Value) -> serde_json::Value {
    a3s_code_core::tools::register_dynamic_workflow(executor.registry());
    let result = executor
        .execute("dynamic_workflow", args)
        .await
        .expect("retrieval workflow execution");
    assert_eq!(result.exit_code, 0, "{}", result.output);
    serde_json::from_str(&result.output).expect("retrieval output")
}

fn assert_exact_calls_in_any_order(observed: &[String], expected: &[&str]) {
    let mut observed = observed.to_vec();
    observed.sort();
    let mut expected = expected
        .iter()
        .map(|value| (*value).to_string())
        .collect::<Vec<_>>();
    expected.sort();
    assert_eq!(observed, expected);
}

fn research_source_urls(output: &serde_json::Value) -> Vec<String> {
    output["research"]["results"]
        .as_array()
        .into_iter()
        .flatten()
        .flat_map(|result| {
            result["structured"]["sources"]
                .as_array()
                .into_iter()
                .flatten()
        })
        .filter_map(|source| source["url_or_path"].as_str().map(str::to_string))
        .collect()
}

#[tokio::test]
async fn process_interruption_persists_completed_source_without_replaying_its_fetch() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = Arc::new(ToolExecutor::new(
        workspace.path().to_string_lossy().to_string(),
    ));
    let calls = Arc::new(Mutex::new(Vec::new()));
    let blocked_started = Arc::new(Notify::new());
    let first_url = "https://durable-effects.example/first";
    let second_url = "https://durable-effects.example/second";
    executor.register_dynamic_tool(Arc::new(InterruptedSiblingFetchFixture {
        calls: Arc::clone(&calls),
        blocked_url: second_url.to_string(),
        blocked_started: Arc::clone(&blocked_started),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: false,
        invalid_selection: false,
    }));
    let query = "Compare two independently acquired records";
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "records.comparison",
            "Independent records",
            "Compare the two acquired records"
        )]),
        serde_json::json!([]),
        serde_json::json!([first_url, second_url]),
    );
    plan["budget"]["direct_searches"] = serde_json::json!(0);
    plan["budget"]["direct_fetches"] = serde_json::json!(2);
    let mut args = workflow_args(
        query,
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "unused_fixture_web_search",
        "fixture_interrupted_sibling_web_fetch",
    );
    args["run_id"] = serde_json::json!("deepresearch-independent-source-effects");
    a3s_code_core::tools::register_dynamic_workflow(executor.registry());

    let first_execution = {
        let executor = Arc::clone(&executor);
        let args = args.clone();
        tokio::spawn(async move { executor.execute("dynamic_workflow", &args).await })
    };
    tokio::time::timeout(Duration::from_secs(5), blocked_started.notified())
        .await
        .expect("the second source fetch should enter its first attempt");

    let workflow_log = workspace
        .path()
        .join(".a3s/workflow/deepresearch-independent-source-effects.jsonl");
    tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            let completed = tokio::fs::read_to_string(&workflow_log)
                .await
                .ok()
                .is_some_and(|history| {
                    history.lines().any(|line| {
                        serde_json::from_str::<serde_json::Value>(line)
                            .ok()
                            .is_some_and(|event| {
                                event["event"]["type"] == "step_completed"
                                    && event["event"]["step_id"] == "retrieve_web_source_1"
                            })
                    })
                });
            if completed {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("the completed sibling source must be durable before the batch finishes");
    first_execution.abort();
    let _ = first_execution.await;

    let resumed = tokio::time::timeout(
        Duration::from_secs(10),
        executor.execute("dynamic_workflow", &args),
    )
    .await
    .expect("the exact interrupted run should resume")
    .expect("resumed retrieval workflow");
    assert_eq!(resumed.exit_code, 0, "{}", resumed.output);
    let output: serde_json::Value =
        serde_json::from_str(&resumed.output).expect("resumed workflow output");
    assert_eq!(
        output["research"]["metadata"]["source_count"],
        2,
        "{}",
        serde_json::to_string_pretty(&output).unwrap()
    );
    let calls = calls.lock().unwrap();
    assert_eq!(
        calls.iter().filter(|url| url.as_str() == first_url).count(),
        1,
        "a durably completed source fetch must not be replayed"
    );
    assert_eq!(
        calls
            .iter()
            .filter(|url| url.as_str() == second_url)
            .count(),
        2,
        "the ambiguous running source attempt must be redelivered"
    );
}

#[tokio::test]
async fn bootstrap_acquisition_preserves_visible_text_and_drops_a_structural_payload_prefix() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let urls = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::clone(&queries),
        results: serde_json::json!([{
            "title": "First ranked source",
            "url": "https://bootstrap.example/first",
            "engines": ["fixture"]
        }, {
            "title": "Accountable Reuters alternative",
            "url": "https://www.reuters.com/bootstrap/second",
            "engines": ["fixture"]
        }, {
            "title": "Unspent candidate",
            "url": "https://bootstrap.example/third",
            "engines": ["fixture"]
        }]),
    }));
    let serialized_state = serde_json::json!({
        "state": "HIDDEN_STRUCTURAL_PAYLOAD".repeat(80)
    })
    .to_string();
    let encoded_markup_state = format!(
        r#"{{"transport":"{}","content":"\\u003carticle\\u003e\\u003cp\\u003eThe structurally decoded excerpt remains visible.\\u003c/p\\u003e\\u003c/article\\u003e""#,
        "HIDDEN_TRUNCATED_SERIALIZED_STATE".repeat(40)
    );
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([
            (
                "https://bootstrap.example/first".to_string(),
                format!(
                    "{serialized_state} The first fetched source contains substantive traceable bootstrap evidence.\n\
                     {encoded_markup_state}\n\
                     Your current User-Agent string appears to be from an automated process.\n\
                     <script>window.__BOOTSTRAP__ = true;</script>\n\
                     Toggle the table of contents 164 languages [Afrikaans](https://example.test/af)"
                ),
            ),
            (
                "https://www.reuters.com/bootstrap/second".to_string(),
                "The second fetched source contains separate substantive bootstrap evidence."
                    .to_string(),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec![
            "First ranked source".to_string(),
            "HIDDEN_STRUCTURAL_PAYLOAD".to_string(),
            "HIDDEN_TRUNCATED_SERIALIZED_STATE".to_string(),
            "substantive traceable bootstrap evidence".to_string(),
            "structurally decoded excerpt remains visible".to_string(),
        ],
        fail: false,
        invalid_selection: false,
    }));
    let query = "Acquire evidence before semantic planning";
    let mut plan = minimal_plan(
        serde_json::json!([track("request.primary", "Original request", query)]),
        serde_json::json!([query]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_searches"] = serde_json::json!(1);
    plan["budget"]["direct_fetches"] = serde_json::json!(2);
    let mut args = workflow_args(
        query,
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );
    args["input"]["execution_mode"] = serde_json::json!("bootstrap_acquisition");
    args["run_id"] = serde_json::json!("deepresearch-bootstrap-acquisition-test");

    let output = execute(&executor, &args).await;

    assert_eq!(*queries.lock().unwrap(), [query]);
    assert_eq!(*urls.lock().unwrap(), ["https://bootstrap.example/first"]);
    assert_eq!(output["mode"], "bootstrap_acquisition");
    assert_eq!(
        output["acquisition"]["packet"]["sources"]
            .as_array()
            .map(Vec::len),
        Some(1)
    );
    let retained_text = output["acquisition"]["packet"]["sources"][0]["chunks"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|chunk| chunk["text"].as_str())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(retained_text.contains("substantive traceable bootstrap evidence"));
    assert!(retained_text.contains("User-Agent"), "{retained_text}");
    assert!(!retained_text.contains("__BOOTSTRAP__"), "{retained_text}");
    assert!(
        !retained_text.contains("HIDDEN_STRUCTURAL_PAYLOAD"),
        "{retained_text}"
    );
    assert!(
        !retained_text.contains("HIDDEN_TRUNCATED_SERIALIZED_STATE"),
        "{retained_text}"
    );
    assert!(
        retained_text.contains("structurally decoded excerpt remains visible"),
        "{retained_text}"
    );
    assert!(retained_text.contains("164 languages"), "{retained_text}");
    assert_eq!(
        output["acquisition"]["metadata"]["source_selection_mode"],
        "semantic_candidate_ids"
    );
    let history = std::fs::read_to_string(
        workspace
            .path()
            .join(".a3s/workflow/deepresearch-bootstrap-acquisition-test.jsonl"),
    )
    .expect("durable bootstrap history");
    assert!(history.lines().any(|line| {
        let event: serde_json::Value = serde_json::from_str(line).unwrap();
        event["event"]["type"] == "step_completed"
            && event["event"]["step_id"] == "checkpoint_bootstrap_acquisition"
    }));
}

#[tokio::test]
async fn bootstrap_source_admission_failure_still_acquires_bounded_candidates() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let urls = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::clone(&queries),
        results: serde_json::json!([{
            "title": "First bounded bootstrap fallback",
            "url": "https://bootstrap-fallback-one.example/record",
            "engines": ["fixture"]
        }, {
            "title": "Second bounded bootstrap fallback",
            "url": "https://bootstrap-fallback-two.example/record",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([
            (
                "https://bootstrap-fallback-one.example/record".to_string(),
                "The first bounded bootstrap source is retained for later semantic review."
                    .to_string(),
            ),
            (
                "https://bootstrap-fallback-two.example/record".to_string(),
                "The second bounded bootstrap source is retained on a distinct host.".to_string(),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(FailWebSourceSelectionFixture {
        selector: SemanticSelectorFixture {
            preferred_fragments: Vec::new(),
            fail: false,
            invalid_selection: false,
        },
    }));
    let query = "Acquire evidence when source admission fails";
    let mut plan = minimal_plan(
        serde_json::json!([track("request.primary", "Original request", query)]),
        serde_json::json!([query]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_searches"] = serde_json::json!(1);
    plan["budget"]["direct_fetches"] = serde_json::json!(2);
    let mut args = workflow_args(
        query,
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );
    args["input"]["execution_mode"] = serde_json::json!("bootstrap_acquisition");
    args["run_id"] = serde_json::json!("deepresearch-bootstrap-fallback-test");

    let output = execute(&executor, &args).await;

    assert_eq!(*queries.lock().unwrap(), [query]);
    assert_exact_calls_in_any_order(
        &urls.lock().unwrap(),
        &[
            "https://bootstrap-fallback-one.example/record",
            "https://bootstrap-fallback-two.example/record",
        ],
    );
    assert_eq!(
        output["acquisition"]["metadata"]["source_selection_mode"],
        "bounded_discovery_fallback"
    );
    assert_eq!(
        output["acquisition"]["packet"]["sources"]
            .as_array()
            .map(Vec::len),
        Some(2)
    );
    assert_eq!(
        output["acquisition"]["packet"]["sources"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|source| source["url_or_path"].as_str())
            .collect::<Vec<_>>(),
        [
            "https://bootstrap-fallback-one.example/record",
            "https://bootstrap-fallback-two.example/record",
        ]
    );
    assert!(output
        .to_string()
        .contains("simulated permanent web source admission failure"));
}

#[tokio::test]
async fn semantic_retrieval_reuses_bootstrap_packet_without_repeating_transport() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec!["preserved raw evidence".to_string()],
        fail: false,
        invalid_selection: false,
    }));
    let query = "Reuse already fetched evidence";
    let plan = minimal_plan(
        serde_json::json!([track("request.primary", "Original request", query)]),
        serde_json::json!([query]),
        serde_json::json!([]),
    );
    let mut args = super::deep_research_workflow_args_with_scope(
        query,
        super::DeepResearchEvidenceScope::WebAndWorkspace,
    );
    args["input"]["research_plan"] = plan;
    args["input"]["execution_mode"] = serde_json::json!("collect_only");
    args["input"]["bootstrap_acquisition"] = serde_json::json!({
        "status": "success",
        "packet": {
            "version": 1,
            "focuses": [],
            "sources": [{
                "source_id": "bootstrap-web-source-1",
                "title": "Preserved source",
                "url_or_path": "https://bootstrap.example/preserved",
                "reliability": "Fetched and durably preserved before planning.",
                "chunks": [{
                    "chunk_id": "bootstrap-web-source-1:chunk:1",
                    "text": "This preserved raw evidence remains available after planning settles."
                }]
            }]
        },
        "errors": [],
        "metadata": {
            "source_selection_mode": "provider_round_robin",
            "fetched_count": 1
        }
    });
    args["run_id"] = serde_json::json!("deepresearch-bootstrap-reuse-test");
    args["limits"]["timeoutMs"] = serde_json::json!(45_000);
    args["limits"]["maxToolCalls"] = serde_json::json!(24);

    // No search or fetch fixture is registered. The final retrieval can only
    // succeed by consuming the immutable bootstrap packet.
    let output = execute(&executor, &args).await;

    assert_eq!(output["mode"], "inquiry_collection");
    assert_eq!(output["research"]["metadata"]["bootstrap_source_count"], 1);
    assert_eq!(
        output["research"]["results"][0]["structured"]["sources"][0]["url_or_path"],
        "https://bootstrap.example/preserved"
    );
}

#[tokio::test]
async fn semantic_retrieval_searches_only_supplements_and_merges_bootstrap_evidence() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let urls = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::clone(&queries),
        results: serde_json::json!([{
            "title": "Independent Aurora assessment",
            "url": "https://www.reuters.com/technology/aurora-assessment",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([(
            "https://www.reuters.com/technology/aurora-assessment".to_string(),
            "The independent Aurora assessment documents deployment constraints and operating risks."
                .to_string(),
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec![
            "preserved primary Aurora evidence".to_string(),
            "deployment constraints".to_string(),
        ],
        fail: false,
        invalid_selection: false,
    }));
    let query = "Aurora";
    let supplemental = "Aurora deployment constraints independent assessment";
    let plan = minimal_plan(
        serde_json::json!([track(
            "aurora.primary",
            "Aurora evidence",
            "Establish Aurora's primary record and independent constraints",
        )]),
        serde_json::json!([query, supplemental]),
        serde_json::json!([]),
    );
    let mut args = workflow_args(
        query,
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );
    args["input"]["bootstrap_acquisition"] = serde_json::json!({
        "status": "success",
        "packet": {
            "version": 1,
            "focuses": [],
            "sources": [{
                "source_id": "bootstrap-web-source-1",
                "title": "Aurora primary record",
                "url_or_path": "https://docs.rs/aurora/latest/aurora",
                "reliability": "Fetched before semantic planning.",
                "chunks": [{
                    "chunk_id": "bootstrap-web-source-1:chunk:1",
                    "text": "The preserved primary Aurora evidence records the public release."
                }]
            }]
        },
        "errors": [],
        "metadata": {}
    });
    args["run_id"] = serde_json::json!("deepresearch-planned-supplement-merge-test");

    let output = execute(&executor, &args).await;

    assert_eq!(*queries.lock().unwrap(), [supplemental]);
    assert_eq!(
        *urls.lock().unwrap(),
        ["https://www.reuters.com/technology/aurora-assessment"]
    );
    let anchors = output["research"]["results"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|result| {
            result["structured"]["sources"][0]["url_or_path"]
                .as_str()
                .map(str::to_string)
        })
        .collect::<BTreeSet<_>>();
    assert_eq!(
        anchors,
        BTreeSet::from([
            "https://docs.rs/aurora/latest/aurora".to_string(),
            "https://www.reuters.com/technology/aurora-assessment".to_string(),
        ])
    );
}

#[tokio::test]
async fn provider_query_and_cross_language_semantic_selection_are_preserved() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let urls = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::clone(&queries),
        results: serde_json::json!([{
            "title": "運用監査記録",
            "url": "https://primary.example/record",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls,
        bodies: BTreeMap::from([(
            "https://primary.example/record".to_string(),
            "監査ログはサービスが正常に稼働していること、観測時刻、監査範囲、証拠境界を記録している。".to_string(),
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec!["正常に稼働".to_string()],
        fail: false,
        invalid_selection: false,
    }));
    let provider_query = "MiXeD Case?!  日本語/中文 — café №42";
    let plan = minimal_plan(
        serde_json::json!([track("operating.state", "运行状态", "核实服务是否正常运行")]),
        serde_json::json!([provider_query]),
        serde_json::json!([]),
    );
    let args = workflow_args(
        "Assess the operating condition",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(*queries.lock().unwrap(), [provider_query]);
    assert_eq!(
        output["research"]["metadata"]["evidence_selection_mode"],
        "semantic_chunk_ids_with_typed_coverage"
    );
    assert!(
        output["research"]["results"][0]["structured"]["sources"][0]["quote_or_fact"]
            .as_str()
            .is_some_and(|text| text.contains("正常に稼働"))
    );
}

#[tokio::test]
async fn search_fallback_notice_is_preserved_as_partial_research_metadata() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let url = "https://fallback.example/record";
    executor.register_dynamic_tool(Arc::new(FallbackNoticeSearchFixture {
        queries: Arc::clone(&queries),
        results: serde_json::json!([{
            "title": "Fallback record",
            "url": url,
            "engines": ["Brave"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::new(Mutex::new(Vec::new())),
        bodies: BTreeMap::from([(
            url.to_string(),
            "The fallback engine returned substantive source text that remains traceable after provider quota exhaustion."
                .to_string(),
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec!["substantive source text".to_string()],
        fail: false,
        invalid_selection: false,
    }));
    let query = "Preserve generic search fallback diagnostics";
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "search.fallback",
            "Search fallback",
            "Retain evidence returned by an automatic fallback engine"
        )]),
        serde_json::json!([query]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_searches"] = serde_json::json!(1);
    plan["budget"]["direct_fetches"] = serde_json::json!(1);
    let args = workflow_args(
        query,
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_fallback_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(*queries.lock().unwrap(), [query]);
    assert_eq!(output["research"]["status"], "partial_success");
    assert_eq!(
        output["research"]["metadata"]["web"]["search_fallback_count"],
        1
    );
    assert_eq!(
        output["research"]["metadata"]["web"]["search_fallback_engines"],
        serde_json::json!(["brave", "bing"])
    );
    assert_eq!(
        output["research"]["metadata"]["web"]["search_engine_selection_sources"],
        serde_json::json!(["config"])
    );
    assert!(output["research"]["warnings"]["collection_errors"]
        .as_array()
        .is_some_and(|errors| errors.iter().any(|error| error
            .as_str()
            .is_some_and(|error| error.contains("AnySearch quota is exhausted")))));
    assert_eq!(
        output["research"]["results"][0]["structured"]["sources"][0]["url_or_path"],
        url
    );
}

#[tokio::test]
async fn provider_publication_date_remains_discovery_metadata() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "Provider-dated record",
            "url": "https://dates.example/record",
            "published_date": "2099-12-31",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::new(Mutex::new(Vec::new())),
        bodies: BTreeMap::from([(
            "https://dates.example/record".to_string(),
            "The fetched record establishes the requested operational fact without publishing a date."
                .to_string(),
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec!["requested operational fact".to_string()],
        fail: false,
        invalid_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([track(
            "date.provenance",
            "Date provenance",
            "Retain only dates established by fetched evidence"
        )]),
        serde_json::json!(["provider date provenance"]),
        serde_json::json!([]),
    );
    let args = workflow_args(
        "Do not treat provider metadata as publication evidence",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    let source = &output["research"]["results"][0]["structured"]["sources"][0];
    assert_eq!(source["url_or_path"], "https://dates.example/record");
    assert!(
        source.get("date").is_none() || source["date"].is_null(),
        "provider-supplied dates must not cross the fetched-evidence boundary: {source}"
    );
    assert!(
        !output.to_string().contains("2099-12-31"),
        "unverified discovery dates must not survive evidence materialization"
    );
}

#[tokio::test]
async fn seed_urls_are_fetched_without_publisher_specific_rewrites() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let urls = Arc::new(Mutex::new(Vec::new()));
    let atom_feed = format!(
        "<?xml version=\"1.0\"?><feed><title>Release notes</title><subtitle>{}</subtitle><entry><id>tag:github.com,2008:Repository/1/v1.13.2</id><updated>2025-08-15T01:43:57Z</updated><link href=\"https://github.com/example/runtime/releases/tag/v1.13.2\"/><title>v1.13.2</title><content>Latest bounded official release notes.</content></entry><entry><id>tag:github.com,2008:Repository/1/v1.13.1</id><updated>2025-03-15T22:05:29Z</updated><title>v1.13.1</title></entry></feed>",
        "feed metadata ".repeat(80)
    );
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([(
            "https://github.com/example/runtime/releases".to_string(),
            atom_feed,
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec!["v1.13.2".to_string()],
        fail: false,
        invalid_selection: false,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "release.feed",
            "Release feed",
            "Verify the latest official release record"
        )]),
        serde_json::json!([]),
        serde_json::json!(["https://github.com/example/runtime/releases"]),
    );
    plan["budget"]["direct_searches"] = serde_json::json!(0);
    plan["budget"]["direct_fetches"] = serde_json::json!(1);
    let args = workflow_args(
        "Read a bounded official GitHub release catalog",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "unused_fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(
        *urls.lock().unwrap(),
        ["https://github.com/example/runtime/releases"]
    );
    assert_eq!(
        output["research"]["results"][0]["structured"]["sources"][0]["url_or_path"],
        "https://github.com/example/runtime/releases"
    );
    let fact = output["research"]["results"][0]["structured"]["sources"][0]["quote_or_fact"]
        .as_str()
        .expect("selected release fact");
    assert!(fact.contains("v1.13.2"), "{fact}");
    assert!(fact.contains("2025-08-15T01:43:57Z"), "{fact}");
}

#[tokio::test]
async fn independent_source_effects_avoid_cross_source_batch_truncation() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let urls = Arc::new(Mutex::new(Vec::new()));
    let source_urls = [
        "https://batch.example/one",
        "https://batch.example/two",
        "https://batch.example/three",
    ];
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: source_urls
            .iter()
            .enumerate()
            .map(|(index, url)| {
                (
                    (*url).to_string(),
                    format!(
                        "Authoritative evidence source {}. {}",
                        index + 1,
                        "bounded evidence text ".repeat(1_550)
                    ),
                )
            })
            .collect(),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: false,
        invalid_selection: false,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "source.effects",
            "Independent source effects",
            "Retain every independently completed source effect"
        )]),
        serde_json::json!([]),
        serde_json::json!(source_urls),
    );
    plan["budget"]["direct_searches"] = serde_json::json!(0);
    plan["budget"]["direct_fetches"] = serde_json::json!(3);
    let args = workflow_args(
        "Retain all independently completed source effects",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "unused_fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(
        output["research"]["metadata"]["source_count"],
        3,
        "{}",
        serde_json::to_string_pretty(&output).unwrap()
    );
    assert_eq!(
        output["research"]["metadata"]["web"]["completed_source_effect_count"],
        3
    );
    assert_eq!(
        output["research"]["metadata"]["web"]["batch_output_recovery_count"],
        0
    );
    assert_exact_calls_in_any_order(&urls.lock().unwrap(), &source_urls);
    assert_eq!(
        research_source_urls(&output),
        source_urls.map(str::to_string)
    );
}

#[tokio::test]
async fn oversubscribed_provider_catalog_is_semantically_admitted_before_fetch() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let urls = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "Unrelated first provider result",
            "url": "https://selection.example/unrelated-first",
            "content": "A valid page that does not address the planned research focus.",
            "engines": ["fixture"]
        }, {
            "title": "另一个无关结果",
            "url": "https://selection.example/unrelated-second",
            "content": "Este resultado tampoco responde a la pregunta.",
            "engines": ["fixture"]
        }, {
            "title": "真正相关的跨语言记录",
            "url": "https://selection.example/authoritative",
            "content": "This authoritative record directly addresses the planned focus.",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([
            (
                "https://selection.example/unrelated-first".to_string(),
                "Unrelated but substantive provider text.".to_string(),
            ),
            (
                "https://selection.example/unrelated-second".to_string(),
                "Otro texto sustantivo pero irrelevante.".to_string(),
            ),
            (
                "https://selection.example/authoritative".to_string(),
                "真正相关的跨语言记录提供了可追溯的一手证据,并明确回答了计划中的研究问题。"
                    .to_string(),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec!["真正相关的跨语言记录".to_string()],
        fail: false,
        invalid_selection: false,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "semantic.admission",
            "语义来源准入",
            "从完整供应商候选目录中选择真正相关的跨语言记录"
        )]),
        serde_json::json!(["MiXeD provider catalog"]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_fetches"] = serde_json::json!(1);
    let args = workflow_args(
        "验证跨语言语义来源准入",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(
        *urls.lock().unwrap(),
        ["https://selection.example/authoritative"]
    );
    assert_eq!(output["research"]["metadata"]["source_count"], 1);
    assert!(
        output["research"]["results"][0]["structured"]["sources"][0]["quote_or_fact"]
            .as_str()
            .is_some_and(|text| text.contains("可追溯的一手证据"))
    );
}

#[tokio::test]
async fn plan_seed_does_not_displace_semantically_selected_source_portfolio() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let urls = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "Canonical first-party record",
            "url": "https://official.example/canonical",
            "content": "The canonical record directly establishes the planned focus.",
            "engines": ["fixture"]
        }, {
            "title": "Provider-selected independent record",
            "url": "https://selection.example/independent",
            "content": "The independent record directly corroborates the planned focus.",
            "engines": ["fixture"]
        }, {
            "title": "Unrelated provider record",
            "url": "https://selection.example/unrelated",
            "content": "This page does not address the planned focus.",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([
            (
                "https://seed.example/generic".to_string(),
                "A generic seed page does not establish the planned fact.".to_string(),
            ),
            (
                "https://official.example/canonical".to_string(),
                "The canonical first-party record establishes the planned fact.".to_string(),
            ),
            (
                "https://selection.example/independent".to_string(),
                "The independent record directly corroborates the planned fact.".to_string(),
            ),
            (
                "https://selection.example/unrelated".to_string(),
                "Unrelated but substantive provider text.".to_string(),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec![
            "Canonical first-party record".to_string(),
            "Provider-selected independent record".to_string(),
        ],
        fail: false,
        invalid_selection: false,
    }));
    let mut source_track = track(
        "source.portfolio",
        "Source portfolio",
        "Retain the canonical record and independent corroboration",
    );
    source_track["evidence_requirements"]["primary_source_required"] = serde_json::json!(true);
    source_track["evidence_requirements"]["independent_corroboration_required"] =
        serde_json::json!(true);
    let mut plan = minimal_plan(
        serde_json::json!([source_track]),
        serde_json::json!(["independent corroborating record"]),
        serde_json::json!(["https://seed.example/generic"]),
    );
    plan["budget"]["direct_fetches"] = serde_json::json!(2);
    let args = workflow_args(
        "Retain a typed source portfolio",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    let expected_urls = [
        "https://official.example/canonical",
        "https://selection.example/independent",
    ];
    assert_exact_calls_in_any_order(&urls.lock().unwrap(), &expected_urls);
    assert_eq!(output["research"]["metadata"]["source_count"], 2);
    assert_eq!(
        research_source_urls(&output),
        expected_urls.map(str::to_string)
    );
    let structured = output["research"]["results"]
        .as_array()
        .unwrap()
        .iter()
        .map(|result| &result["structured"])
        .collect::<Vec<_>>();
    assert_eq!(structured.len(), 2);
    assert!(structured.iter().all(|item| {
        item["sources"]
            .as_array()
            .is_some_and(|sources| sources.len() == 1)
            && item["source_coverage"]
                .as_array()
                .is_some_and(|bindings| bindings.len() == 1)
            && item["relevant_obligation_ids"]
                .as_array()
                .is_some_and(|obligations| obligations.len() == 1)
    }));
    assert!(structured
        .iter()
        .flat_map(|item| item["source_coverage"].as_array().into_iter().flatten())
        .all(|binding| binding["roles"]
            .as_array()
            .is_some_and(|roles| roles.contains(&serde_json::json!("supporting")))));

    let ledger =
        super::deep_research_evidence_ledger::accepted_evidence_ledger(&output.to_string(), None);
    assert_eq!(ledger.len(), 2);
    assert!(ledger.iter().all(|item| item.sources.len() == 1
        && item.source_coverage.len() == 1
        && item.relevant_obligation_ids == ["source.portfolio"]
        && item.source_coverage[0].source_id == item.sources[0].id));
}

#[tokio::test]
async fn typed_source_gap_drives_one_supplemental_retrieval_pass() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let urls = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "Independent corroborating record",
            "url": "https://loop.example/independent",
            "content": "A separately attributable record corroborates the direct finding.",
            "engines": ["fixture"]
        }, {
            "title": "Unrelated remaining record",
            "url": "https://loop.example/unrelated",
            "content": "This candidate does not address the research obligation.",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([
            (
                "https://loop.example/primary".to_string(),
                "The direct first-party record establishes the finding.".to_string(),
            ),
            (
                "https://loop.example/independent".to_string(),
                "A separately attributable record corroborates the direct finding.".to_string(),
            ),
            (
                "https://loop.example/unrelated".to_string(),
                "Unrelated but substantive source text.".to_string(),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec![
            "https://loop.example/primary".to_string(),
            "Independent corroborating record".to_string(),
        ],
        fail: false,
        invalid_selection: false,
    }));
    let mut source_track = track(
        "source.loop",
        "Source loop",
        "Close direct support and independent corroboration",
    );
    source_track["evidence_requirements"]["primary_source_required"] = serde_json::json!(true);
    source_track["evidence_requirements"]["independent_corroboration_required"] =
        serde_json::json!(true);
    let mut plan = minimal_plan(
        serde_json::json!([source_track]),
        serde_json::json!(["independent corroborating record"]),
        serde_json::json!(["https://loop.example/primary"]),
    );
    plan["budget"]["direct_fetches"] = serde_json::json!(1);
    let mut args = workflow_args(
        "Close a typed source portfolio with one supplemental pass",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );
    args["run_id"] = serde_json::json!("deepresearch-initial-checkpoint-test");

    let output = execute(&executor, &args).await;

    assert_eq!(
        *urls.lock().unwrap(),
        [
            "https://loop.example/primary",
            "https://loop.example/independent"
        ]
    );
    assert_eq!(output["research"]["metadata"]["retrieval_pass_count"], 2);
    assert_eq!(
        output["research"]["metadata"]["supplemental_retrieval_attempted"],
        true
    );
    assert_eq!(output["research"]["metadata"]["source_count"], 2);
    let ledger =
        super::deep_research_evidence_ledger::accepted_evidence_ledger(&output.to_string(), None);
    assert_eq!(ledger.len(), 2);
    assert_eq!(
        ledger
            .iter()
            .flat_map(|item| item.source_coverage.iter())
            .filter(|binding| binding
                .roles
                .contains(&a3s::research::SourceEvidenceRole::Independent))
            .map(|binding| binding.source_id.as_str())
            .collect::<std::collections::HashSet<_>>()
            .len(),
        2
    );
    let history = std::fs::read_to_string(
        workspace
            .path()
            .join(".a3s/workflow/deepresearch-initial-checkpoint-test.jsonl"),
    )
    .expect("durable retrieval history");
    let events = history
        .lines()
        .map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
        .collect::<Vec<_>>();
    let checkpoint_sequence = events
        .iter()
        .find(|event| {
            event["event"]["type"] == "step_completed"
                && event["event"]["step_id"] == "checkpoint_initial_retrieval"
        })
        .and_then(|event| event["sequence"].as_u64())
        .expect("completed initial checkpoint");
    let supplemental_sequence = events
        .iter()
        .find(|event| {
            event["event"]["type"] == "step_created"
                && event["event"]["step_id"] == "select_supplemental_web_sources"
        })
        .and_then(|event| event["sequence"].as_u64())
        .expect("supplemental source selection");
    assert!(checkpoint_sequence < supplemental_sequence);
}

#[tokio::test]
async fn failed_initial_fetch_uses_bounded_supplemental_replacement() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let urls = Arc::new(Mutex::new(Vec::new()));
    let unavailable = "https://replacement.example/unavailable";
    let replacement = "https://replacement.example/authoritative";
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "Initially selected unavailable source",
            "url": unavailable,
            "content": "A promising initial source that fails during fetch.",
            "engines": ["fixture"]
        }, {
            "title": "Authoritative replacement source",
            "url": replacement,
            "content": "A replacement that directly establishes the planned finding.",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([(
            replacement.to_string(),
            "The authoritative replacement directly establishes the planned finding.".to_string(),
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec![
            "Initially selected unavailable source".to_string(),
            "Authoritative replacement source".to_string(),
        ],
        fail: false,
        invalid_selection: false,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "replacement.fetch",
            "Replacement fetch",
            "Retain traceable evidence after the first admitted fetch fails"
        )]),
        serde_json::json!(["replacement evidence"]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_fetches"] = serde_json::json!(1);
    let args = workflow_args(
        "Recover one failed admitted fetch",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(*urls.lock().unwrap(), [unavailable, replacement]);
    assert_eq!(output["research"]["metadata"]["retrieval_pass_count"], 2);
    assert_eq!(
        output["research"]["metadata"]["supplemental"]["operational_gap_count"],
        1
    );
    assert_eq!(output["research"]["metadata"]["source_count"], 1);
    assert!(output.to_string().contains("authoritative replacement"));
    assert!(!output.to_string().contains("promising initial source"));
}

#[tokio::test]
async fn supplemental_replacement_keeps_the_full_closed_candidate_catalog() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let urls = Arc::new(Mutex::new(Vec::new()));
    let unavailable = "https://registry.example/items/unavailable";
    let same_authority = "https://registry.example/items/alternate";
    let different_authority = "https://official.example/releases/current";
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "Initially selected unavailable registry page",
            "url": unavailable,
            "content": "A promising registry record that retains no fetched text.",
            "engines": ["fixture"]
        }, {
            "title": "Replacement candidate B",
            "url": same_authority,
            "content": "A replacement candidate with an exact closed identity.",
            "engines": ["fixture"]
        }, {
            "title": "Replacement candidate C",
            "url": different_authority,
            "content": "Another replacement candidate with an exact closed identity.",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([
            (
                same_authority.to_string(),
                "The selected replacement directly establishes the planned finding.".to_string(),
            ),
            (
                different_authority.to_string(),
                "The second selected replacement independently establishes the planned finding."
                    .to_string(),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec![
            "Initially selected unavailable registry page".to_string(),
            "Replacement candidate B".to_string(),
            "Replacement candidate C".to_string(),
        ],
        fail: false,
        invalid_selection: false,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "replacement.identity",
            "Replacement identity",
            "Recover traceable evidence through a closed supplemental candidate"
        )]),
        serde_json::json!(["release evidence"]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_fetches"] = serde_json::json!(1);
    let args = workflow_args(
        "Recover a failed fetch from the closed supplemental catalog",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_exact_calls_in_any_order(
        &urls.lock().unwrap(),
        &[unavailable, same_authority, different_authority],
    );
    assert_eq!(
        output["research"]["metadata"]["supplemental"]["web"]["failed_candidate_count"],
        1
    );
    assert_eq!(output["research"]["metadata"]["source_count"], 2);
    assert_eq!(
        research_source_urls(&output),
        [same_authority.to_string(), different_authority.to_string()]
    );
}

#[tokio::test]
async fn transient_web_source_selector_failure_replays_only_source_admission() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let urls = Arc::new(Mutex::new(Vec::new()));
    let selector_calls = Arc::new(AtomicUsize::new(0));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::clone(&queries),
        results: serde_json::json!([{
            "title": "Unrelated discovery candidate",
            "url": "https://source-retry.example/unrelated",
            "content": "Unrelated discovery metadata.",
            "engines": ["fixture"]
        }, {
            "title": "Authoritative source retry record",
            "url": "https://source-retry.example/authoritative",
            "content": "The authoritative source retry record addresses the focus.",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([
            (
                "https://source-retry.example/unrelated".to_string(),
                "Unrelated but substantive source text.".to_string(),
            ),
            (
                "https://source-retry.example/authoritative".to_string(),
                "The authoritative source retry record remains traceable after recovery."
                    .to_string(),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(RetryOnceSemanticSelectorFixture {
        calls: Arc::clone(&selector_calls),
        selector: SemanticSelectorFixture {
            preferred_fragments: vec!["authoritative source retry record".to_string()],
            fail: false,
            invalid_selection: false,
        },
        retry_web_source_selection: true,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "source.retry",
            "Source retry",
            "Retain the authoritative source retry record"
        )]),
        serde_json::json!(["source selector recovery"]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_fetches"] = serde_json::json!(1);
    let args = workflow_args(
        "Verify source selector recovery",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );
    a3s_code_core::tools::register_dynamic_workflow(executor.registry());

    let result = executor
        .execute("dynamic_workflow", &args)
        .await
        .expect("retrieval workflow execution");

    assert_eq!(result.exit_code, 0, "{}", result.output);
    assert_eq!(selector_calls.load(Ordering::SeqCst), 2);
    assert_eq!(queries.lock().unwrap().len(), 1);
    assert_eq!(
        *urls.lock().unwrap(),
        ["https://source-retry.example/authoritative"]
    );
    let steps = result
        .metadata
        .as_ref()
        .and_then(|metadata| metadata["dynamic_workflow"]["snapshot"]["steps"].as_object())
        .expect("durable workflow steps");
    assert_eq!(steps.len(), 5);
    assert_eq!(steps["discover_web_sources"]["attempt"], 1);
    assert_eq!(steps["select_web_sources"]["attempt"], 2);
    assert_eq!(steps["retrieve_web_source_1"]["attempt"], 1);
    assert!(!steps.contains_key("retrieve_web"));
    assert_eq!(steps["select_evidence_chunks"]["attempt"], 1);
    assert_eq!(steps["checkpoint_initial_retrieval"]["attempt"], 1);
}

#[tokio::test]
async fn fetch_candidates_preserve_query_and_provider_result_order() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let urls = Arc::new(Mutex::new(Vec::new()));
    let first_query = "First exact provider query";
    let second_query = "第二个精确查询";
    let first_urls = [
        "https://order-a.example/one",
        "https://order-a.example/two",
        "https://order-c.example/three",
    ];
    let second_urls = ["https://order-b.example/one", "https://order-d.example/two"];
    executor.register_dynamic_tool(Arc::new(QuerySearchFixture {
        queries: Arc::clone(&queries),
        results_by_query: BTreeMap::from([
            (
                first_query.to_string(),
                serde_json::json!(first_urls
                    .iter()
                    .map(|url| serde_json::json!({
                        "title": url,
                        "url": url,
                        "engines": ["fixture"]
                    }))
                    .collect::<Vec<_>>()),
            ),
            (
                second_query.to_string(),
                serde_json::json!(second_urls
                    .iter()
                    .map(|url| serde_json::json!({
                        "title": url,
                        "url": url,
                        "engines": ["fixture"]
                    }))
                    .collect::<Vec<_>>()),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: first_urls
            .iter()
            .chain(second_urls.iter())
            .map(|url| {
                (
                    (*url).to_string(),
                    format!("Substantive provider-ordered evidence from {url}."),
                )
            })
            .collect(),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: false,
        invalid_selection: false,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "provider.order",
            "Provider order",
            "Preserve provider discovery order"
        )]),
        serde_json::json!([first_query, second_query]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_fetches"] = serde_json::json!(4);
    let args = workflow_args(
        "Preserve provider discovery order",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_query_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_exact_calls_in_any_order(&queries.lock().unwrap(), &[first_query, second_query]);
    let expected_urls = [first_urls[0], first_urls[1], first_urls[2], second_urls[0]];
    assert_exact_calls_in_any_order(&urls.lock().unwrap(), &expected_urls);
    assert_eq!(output["research"]["metadata"]["source_count"], 4);
    assert_eq!(
        research_source_urls(&output),
        expected_urls.map(str::to_string)
    );
}

#[tokio::test]
async fn oversized_chunk_catalog_fails_closed_without_positional_sampling() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let source_urls = (1..=8)
        .map(|index| format!("https://overflow.example/evidence-{index}"))
        .collect::<Vec<_>>();
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!(source_urls
            .iter()
            .map(|url| serde_json::json!({
                "title": url,
                "url": url,
                "engines": ["fixture"]
            }))
            .collect::<Vec<_>>()),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::new(Mutex::new(Vec::new())),
        bodies: source_urls
            .iter()
            .enumerate()
            .map(|(source_index, url)| {
                let body = (0..82)
                    .map(|chunk_index| {
                        format!(
                            "OVERFLOW_SECRET_EVIDENCE_{}_{chunk_index:03} {}",
                            source_index + 1,
                            "bounded-source-content ".repeat(15)
                        )
                    })
                    .collect::<Vec<_>>()
                    .join("\n");
                (url.clone(), body)
            })
            .collect(),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: false,
        invalid_selection: false,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "closed.catalog",
            "Closed catalog",
            "Retain a complete bounded chunk catalog or fail closed"
        )]),
        serde_json::json!(["oversized evidence catalog"]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_fetches"] = serde_json::json!(8);
    let args = workflow_args(
        "Retain a complete bounded catalog",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(output["research"]["status"], "failed");
    assert_eq!(output["research"]["metadata"]["source_count"], 0);
    let catalog_chunk_count = output["research"]["metadata"]["web"]["catalog_chunk_count"]
        .as_u64()
        .unwrap_or_default();
    assert!(
        catalog_chunk_count > 640,
        "fixture produced only {catalog_chunk_count} chunks"
    );
    assert!(output.to_string().contains("closed catalog limit"));
    assert!(!output.to_string().contains("OVERFLOW_SECRET_EVIDENCE"));
}

#[tokio::test]
async fn eight_source_catalog_above_the_old_limit_uses_one_selector_per_source() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let urls = Arc::new(Mutex::new(Vec::new()));
    let source_urls = (1..=8)
        .map(|index| format!("https://source-local-selection.example/source-{index}"))
        .collect::<Vec<_>>();
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::clone(&queries),
        results: serde_json::json!(source_urls
            .iter()
            .map(|url| serde_json::json!({
                "title": url,
                "url": url,
                "engines": ["fixture"]
            }))
            .collect::<Vec<_>>()),
    }));
    let bodies = source_urls
        .iter()
        .enumerate()
        .map(|(source_index, url)| {
            let lines = (1..=30)
                .map(|chunk_index| {
                    format!(
                        "SHARDED_TARGET_{}_{} {}",
                        source_index + 1,
                        chunk_index,
                        "complete semantic shard evidence ".repeat(19)
                    )
                })
                .collect::<Vec<_>>()
                .join("\n");
            (url.clone(), lines)
        })
        .collect::<BTreeMap<_, _>>();
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies,
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: (1..=8)
            .flat_map(|source| {
                [1, 10, 20, 30]
                    .into_iter()
                    .map(move |chunk| format!("SHARDED_TARGET_{source}_{chunk}"))
            })
            .collect(),
        fail: false,
        invalid_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([track(
            "selector.sources",
            "Semantic source selectors",
            "Retain the late source-local target after every chunk is semantically considered"
        )]),
        serde_json::json!(["complete source-local semantic catalog"]),
        serde_json::json!([]),
    );
    let args = workflow_args(
        "Verify complete source-local semantic selection",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );
    a3s_code_core::tools::register_dynamic_workflow(executor.registry());

    let result = executor
        .execute("dynamic_workflow", &args)
        .await
        .expect("source-local retrieval workflow execution");

    assert_eq!(result.exit_code, 0, "{}", result.output);
    assert_eq!(queries.lock().unwrap().len(), 1);
    let expected_urls = source_urls.iter().map(String::as_str).collect::<Vec<_>>();
    assert_exact_calls_in_any_order(&urls.lock().unwrap(), &expected_urls);
    let output: serde_json::Value =
        serde_json::from_str(&result.output).expect("sharded retrieval output");
    assert_eq!(
        output["research"]["status"],
        "success",
        "{}",
        serde_json::to_string_pretty(&output).unwrap()
    );
    assert_eq!(
        output["research"]["metadata"]["semantic_selection_shard_count"],
        8
    );
    assert_eq!(research_source_urls(&output), source_urls);
    assert!(
        output["research"]["metadata"]["catalog_chunk_count"]
            .as_u64()
            .is_some_and(|count| count > 192 && count <= 384),
        "the complete eight-source catalog must cross the retired 192-chunk ceiling"
    );
    assert!(
        output["research"]["metadata"]["semantic_selection_candidate_count"]
            .as_u64()
            .is_some_and(|count| count > 0 && count <= 32)
    );
    assert!(output["research"]["results"]
        .as_array()
        .into_iter()
        .flatten()
        .flat_map(|result| {
            result["structured"]["sources"]
                .as_array()
                .into_iter()
                .flatten()
        })
        .flat_map(|source| source["evidence_excerpts"].as_array().into_iter().flatten())
        .any(|excerpt| excerpt["quote_or_fact"]
            .as_str()
            .is_some_and(|text| text.contains("SHARDED_TARGET_8_30"))));
    assert_eq!(
        output["research"]["results"]
            .as_array()
            .into_iter()
            .flatten()
            .flat_map(|result| {
                result["structured"]["key_evidence"]
                    .as_array()
                    .into_iter()
                    .flatten()
            })
            .count(),
        32,
        "all bounded source-local selections must reach closed question review"
    );

    let steps = result
        .metadata
        .as_ref()
        .and_then(|metadata| metadata["dynamic_workflow"]["snapshot"]["steps"].as_object())
        .expect("source-local durable workflow steps");
    assert_eq!(steps["discover_web_sources"]["attempt"], 1);
    for index in 1..=8 {
        assert_eq!(steps[&format!("retrieve_web_source_{index}")]["attempt"], 1);
    }
    assert!(!steps.contains_key("retrieve_web"));
    assert!(!steps.contains_key("select_evidence_chunks"));
    let mut shard_attempts = (1..=8)
        .map(|index| {
            steps[&format!("select_evidence_chunks_shard_{index}")]["attempt"]
                .as_u64()
                .expect("shard attempt")
        })
        .collect::<Vec<_>>();
    shard_attempts.sort_unstable();
    assert_eq!(shard_attempts, [1, 1, 1, 1, 1, 1, 1, 1]);
}

#[tokio::test]
async fn failed_shards_promote_no_own_text_but_preserve_valid_siblings() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let failed_url = "https://partial-shards.example/failed";
    let retained_url = "https://partial-shards.example/retained";
    let body = |prefix: &str| {
        (1..=12)
            .map(|index| {
                format!(
                    "{prefix}_{index:02} {}",
                    "bounded source-local semantic evidence ".repeat(16)
                )
            })
            .collect::<Vec<_>>()
            .join("\n")
    };
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::new(Mutex::new(Vec::new())),
        bodies: BTreeMap::from([
            (failed_url.to_string(), body("FAILED_SHARD_TEXT")),
            (retained_url.to_string(), body("RETAINED_SHARD_TEXT")),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(FailMatchingSemanticSelectorFixture {
        schema_name: "deep_research_evidence_shard_selection",
        fragment: "FAILED_SHARD_TEXT".to_string(),
        selector: SemanticSelectorFixture {
            preferred_fragments: vec!["RETAINED_SHARD_TEXT_12".to_string()],
            fail: false,
            invalid_selection: false,
        },
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "partial.shards",
            "Partial shards",
            "Preserve only independently validated source-local shard text"
        )]),
        serde_json::json!([]),
        serde_json::json!([failed_url, retained_url]),
    );
    plan["budget"]["direct_searches"] = serde_json::json!(0);
    plan["budget"]["direct_fetches"] = serde_json::json!(2);
    let args = workflow_args(
        "Retain validated siblings after one source-local selector fails",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "unused_fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(output["research"]["status"], "partial_success");
    assert_eq!(output["research"]["metadata"]["source_count"], 1);
    assert_eq!(
        output["research"]["metadata"]["semantic_selection_failed_shard_count"],
        1
    );
    let encoded = output.to_string();
    assert!(encoded.contains("RETAINED_SHARD_TEXT"));
    assert!(!encoded.contains("FAILED_SHARD_TEXT"));
    assert!(encoded.contains("simulated source-local shard timeout"));
}

#[tokio::test]
async fn failed_source_local_selection_drops_only_that_source() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let failed_url = "https://partial-reduction.example/failed";
    let retained_url = "https://partial-reduction.example/retained";
    let failed_body = (1..=40)
        .map(|index| {
            format!(
                "FAILED_SOURCE_REDUCTION_{index:02} {}",
                "bounded source reduction evidence ".repeat(18)
            )
        })
        .collect::<Vec<_>>()
        .join("\n");
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::new(Mutex::new(Vec::new())),
        bodies: BTreeMap::from([
            (failed_url.to_string(), failed_body),
            (
                retained_url.to_string(),
                "RETAINED_WITHOUT_REDUCTION direct independently validated evidence.".to_string(),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(FailMatchingSemanticSelectorFixture {
        schema_name: "deep_research_evidence_shard_selection",
        fragment: "FAILED_SOURCE_REDUCTION".to_string(),
        selector: SemanticSelectorFixture {
            preferred_fragments: vec![
                "FAILED_SOURCE_REDUCTION_05".to_string(),
                "FAILED_SOURCE_REDUCTION_08".to_string(),
                "FAILED_SOURCE_REDUCTION_15".to_string(),
                "FAILED_SOURCE_REDUCTION_18".to_string(),
                "FAILED_SOURCE_REDUCTION_25".to_string(),
                "FAILED_SOURCE_REDUCTION_28".to_string(),
                "FAILED_SOURCE_REDUCTION_35".to_string(),
                "FAILED_SOURCE_REDUCTION_38".to_string(),
                "RETAINED_WITHOUT_REDUCTION".to_string(),
            ],
            fail: false,
            invalid_selection: false,
        },
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "partial.source-reduction",
            "Partial source reduction",
            "Drop only the source whose final bounded reduction fails"
        )]),
        serde_json::json!([]),
        serde_json::json!([failed_url, retained_url]),
    );
    plan["budget"]["direct_searches"] = serde_json::json!(0);
    plan["budget"]["direct_fetches"] = serde_json::json!(2);
    let args = workflow_args(
        "Retain independent sources after one source reducer fails",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "unused_fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(output["research"]["status"], "partial_success");
    assert_eq!(output["research"]["metadata"]["source_count"], 1);
    assert_eq!(
        output["research"]["metadata"]["semantic_selection_failed_shard_count"],
        1
    );
    assert_eq!(
        output["research"]["metadata"]["semantic_selection_source_reduction_count"],
        0
    );
    let encoded = output.to_string();
    assert!(encoded.contains("RETAINED_WITHOUT_REDUCTION"));
    assert!(!encoded.contains("FAILED_SOURCE_REDUCTION"));
    assert!(encoded.contains("simulated source-local shard timeout"));
}

#[tokio::test]
async fn large_source_is_structurally_windowed_then_semantically_reduced() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let urls = Arc::new(Mutex::new(Vec::new()));
    let source_url = "https://source-reduction.example/complete";
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::clone(&queries),
        results: serde_json::json!([{
            "title": "Complete source reduction fixture",
            "url": source_url,
            "engines": ["fixture"]
        }]),
    }));
    let body = (1..=70)
        .map(|chunk_index| {
            format!(
                "SOURCE_REDUCER_TARGET_{chunk_index} {}",
                "closed semantic source evidence ".repeat(20)
            )
        })
        .collect::<Vec<_>>()
        .join("\n");
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([(source_url.to_string(), body)]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: [70, 60, 50, 35, 20, 1]
            .into_iter()
            .map(|index| format!("SOURCE_REDUCER_TARGET_{index}"))
            .collect(),
        fail: false,
        invalid_selection: false,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "selector.source-reduction",
            "Semantic source reduction",
            "Retain the strongest late candidate while enforcing the per-source evidence limit"
        )]),
        serde_json::json!(["complete source semantic reduction"]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_fetches"] = serde_json::json!(1);
    let args = workflow_args(
        "Verify semantic per-source reduction",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );
    a3s_code_core::tools::register_dynamic_workflow(executor.registry());

    let result = executor
        .execute("dynamic_workflow", &args)
        .await
        .expect("semantic source-reduction workflow");

    assert_eq!(result.exit_code, 0, "{}", result.output);
    assert_eq!(queries.lock().unwrap().len(), 1);
    let fetched_urls = urls.lock().unwrap();
    assert!(
        !fetched_urls.is_empty() && fetched_urls.iter().all(|url| url == source_url),
        "batch-output recovery may repeat only the exact closed URL: {fetched_urls:?}"
    );
    drop(fetched_urls);
    let output: serde_json::Value =
        serde_json::from_str(&result.output).expect("source-reduction output");
    assert_eq!(
        output["research"]["status"],
        "success",
        "{}",
        serde_json::to_string_pretty(&output).unwrap()
    );
    assert!(
        output["research"]["metadata"]["semantic_selection_shard_count"]
            .as_u64()
            .is_some_and(|count| count > 1)
    );
    assert_eq!(
        output["research"]["metadata"]["semantic_selection_source_reduction_count"],
        1
    );
    assert_eq!(
        output["research"]["metadata"]["semantic_selection_materialized_count"],
        4
    );
    let excerpts = output["research"]["results"][0]["structured"]["sources"][0]
        ["evidence_excerpts"]
        .as_array()
        .expect("bounded source excerpts");
    assert_eq!(excerpts.len(), 4);
    assert!(excerpts.iter().any(|excerpt| excerpt["quote_or_fact"]
        .as_str()
        .is_some_and(|text| text.contains("SOURCE_REDUCER_TARGET_70"))));

    let steps = result
        .metadata
        .as_ref()
        .and_then(|metadata| metadata["dynamic_workflow"]["snapshot"]["steps"].as_object())
        .expect("source-reduction durable steps");
    assert_eq!(steps["select_evidence_chunks_shard_1"]["attempt"], 1);
    assert_eq!(steps["select_evidence_chunks_shard_2"]["attempt"], 1);
    assert_eq!(steps["select_evidence_chunks_source_1"]["attempt"], 1);
    assert!(!steps.contains_key("select_evidence_chunks"));
}

#[tokio::test]
async fn transient_selector_failure_retries_only_the_durable_selection_step() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let urls = Arc::new(Mutex::new(Vec::new()));
    let selector_calls = Arc::new(AtomicUsize::new(0));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::clone(&queries),
        results: serde_json::json!([{
            "title": "Durable selector record",
            "url": "https://selector-retry.example/record",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([(
            "https://selector-retry.example/record".to_string(),
            "The durable semantic selection retry retains this exact authoritative evidence."
                .to_string(),
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(RetryOnceSemanticSelectorFixture {
        calls: Arc::clone(&selector_calls),
        selector: SemanticSelectorFixture {
            preferred_fragments: vec!["durable semantic selection retry".to_string()],
            fail: false,
            invalid_selection: false,
        },
        retry_web_source_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([track(
            "selector.retry",
            "Selector retry",
            "Verify durable semantic selection recovery"
        )]),
        serde_json::json!(["durable selector evidence"]),
        serde_json::json!([]),
    );
    let args = workflow_args(
        "Verify durable semantic selection recovery",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );
    a3s_code_core::tools::register_dynamic_workflow(executor.registry());

    let result = executor
        .execute("dynamic_workflow", &args)
        .await
        .expect("retrieval workflow execution");

    assert_eq!(result.exit_code, 0, "{}", result.output);
    assert_eq!(selector_calls.load(Ordering::SeqCst), 2);
    assert_eq!(queries.lock().unwrap().len(), 1);
    assert_eq!(urls.lock().unwrap().len(), 1);
    let output: serde_json::Value = serde_json::from_str(&result.output).expect("retrieval output");
    assert_eq!(output["research"]["status"], "success");
    assert!(
        output["research"]["results"][0]["structured"]["sources"][0]["quote_or_fact"]
            .as_str()
            .is_some_and(|text| text.contains("exact authoritative evidence"))
    );
    let steps = result
        .metadata
        .as_ref()
        .and_then(|metadata| metadata["dynamic_workflow"]["snapshot"]["steps"].as_object())
        .expect("durable workflow steps");
    assert_eq!(steps.len(), 5);
    assert_eq!(steps["discover_web_sources"]["attempt"], 1);
    assert_eq!(steps["select_web_sources"]["attempt"], 1);
    assert_eq!(steps["retrieve_web_source_1"]["attempt"], 1);
    assert!(!steps.contains_key("retrieve_web"));
    assert_eq!(steps["select_evidence_chunks"]["attempt"], 2);
    assert_eq!(steps["checkpoint_initial_retrieval"]["attempt"], 1);
}

#[tokio::test]
async fn source_admission_failure_uses_bounded_discovery_fallback_before_chunk_review() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let queries = Arc::new(Mutex::new(Vec::new()));
    let urls = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::clone(&queries),
        results: serde_json::json!([{
            "title": "Fallback candidate one",
            "url": "https://fallback-one.example/record",
            "content": "A candidate that requires fetched-text review.",
            "engines": ["fixture"]
        }, {
            "title": "Fallback candidate two",
            "url": "https://fallback-two.example/record",
            "content": "An independent candidate on another host.",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([
            (
                "https://fallback-one.example/record".to_string(),
                "The verified fallback evidence directly resolves the requested focus.".to_string(),
            ),
            (
                "https://fallback-two.example/record".to_string(),
                "The second fetched candidate remains available for closed review.".to_string(),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(FailWebSourceSelectionFixture {
        selector: SemanticSelectorFixture {
            preferred_fragments: vec!["verified fallback evidence".to_string()],
            fail: false,
            invalid_selection: false,
        },
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "fallback.review",
            "Fallback review",
            "Review verified fallback evidence"
        )]),
        serde_json::json!(["fallback evidence"]),
        serde_json::json!([]),
    );
    plan["budget"]["direct_fetches"] = serde_json::json!(2);
    let args = workflow_args(
        "Verify source-admission failure recovery",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(queries.lock().unwrap().len(), 1);
    let expected_urls = [
        "https://fallback-one.example/record",
        "https://fallback-two.example/record",
    ];
    assert_exact_calls_in_any_order(&urls.lock().unwrap(), &expected_urls);
    assert_eq!(
        output["research"]["metadata"]["web"]["source_selection_mode"],
        "bounded_discovery_fallback"
    );
    assert_eq!(output["research"]["metadata"]["source_count"], 2);
    assert_eq!(
        research_source_urls(&output),
        expected_urls.map(str::to_string)
    );
    assert!(output.to_string().contains("verified fallback evidence"));
    assert!(output
        .to_string()
        .contains("simulated permanent web source admission failure"));
}

#[tokio::test]
async fn selector_failure_promotes_no_fetched_text() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "Fetched record",
            "url": "https://failure.example/record",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::new(Mutex::new(Vec::new())),
        bodies: BTreeMap::from([(
            "https://failure.example/record".to_string(),
            "RAW_SECRET_EVIDENCE must never be promoted when semantic selection fails.".to_string(),
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: true,
        invalid_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([track("failure.boundary", "Boundary", "Verify the boundary")]),
        serde_json::json!(["boundary record"]),
        serde_json::json!([]),
    );
    let args = workflow_args(
        "Verify the boundary",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(output["research"]["status"], "failed");
    assert_eq!(output["research"]["metadata"]["source_count"], 0);
    assert_eq!(
        output["research"]["results"].as_array().map(Vec::len),
        Some(0)
    );
    assert!(!output.to_string().contains("RAW_SECRET_EVIDENCE"));
}

#[tokio::test]
async fn selector_id_outside_closed_catalog_promotes_no_fetched_text() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "Fetched record",
            "url": "https://invalid-selection.example/record",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::new(Mutex::new(Vec::new())),
        bodies: BTreeMap::from([(
            "https://invalid-selection.example/record".to_string(),
            "OUT_OF_CATALOG_SECRET must never be promoted from fetched text.".to_string(),
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: false,
        invalid_selection: true,
    }));
    let plan = minimal_plan(
        serde_json::json!([track(
            "closed.catalog",
            "Closed catalog",
            "Verify selector IDs against the fetched catalog",
        )]),
        serde_json::json!(["closed catalog record"]),
        serde_json::json!([]),
    );
    let args = workflow_args(
        "Verify the closed evidence catalog",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(output["research"]["status"], "failed");
    assert_eq!(output["research"]["metadata"]["source_count"], 0);
    assert_eq!(
        output["research"]["results"].as_array().map(Vec::len),
        Some(0)
    );
    assert!(!output.to_string().contains("OUT_OF_CATALOG_SECRET"));
    assert!(output.to_string().contains("outside the closed catalog"));
}

#[tokio::test]
async fn pdf_additional_ranges_remain_one_source_in_one_retrieval_pass() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let offsets = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(PaginatedPdfFixture {
        offsets: Arc::clone(&offsets),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec![
            "双阶段检索方法".to_string(),
            "引用完整率下降".to_string(),
            "只覆盖英语技术主题".to_string(),
        ],
        fail: false,
        invalid_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([
            track("method", "方法", "双阶段检索方法"),
            track("evaluation", "评测", "引用完整率下降"),
            track("limitations", "限制", "只覆盖英语技术主题")
        ]),
        serde_json::json!([]),
        serde_json::json!(["https://papers.example/report.pdf"]),
    );
    let args = workflow_args(
        "分析报告的方法、评测与限制",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_pdf_fetch",
    );

    let output = execute(&executor, &args).await;

    let second_offset = PDF_RANGE_ONE.chars().count() as u64;
    let third_offset = second_offset + PDF_RANGE_TWO.chars().count() as u64;
    assert_eq!(*offsets.lock().unwrap(), [0, second_offset, third_offset]);
    assert_eq!(
        output["research"]["metadata"]["web"]["document_range_count"],
        3
    );
    let sources = output["research"]["results"][0]["structured"]["sources"]
        .as_array()
        .expect("PDF sources");
    assert_eq!(sources.len(), 1);
    assert_eq!(
        sources[0]["evidence_excerpts"].as_array().map(Vec::len),
        Some(3)
    );
}

#[tokio::test]
async fn html_additional_ranges_reach_late_article_evidence() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let offsets = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(PaginatedHtmlFixture {
        offsets: Arc::clone(&offsets),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec![
            "阶段一背景".to_string(),
            "阶段二进展".to_string(),
            "阶段三结论".to_string(),
        ],
        fail: false,
        invalid_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([
            track("stage-one", "阶段一", "阶段一背景"),
            track("stage-two", "阶段二", "阶段二进展"),
            track("stage-three", "阶段三", "阶段三结论")
        ]),
        serde_json::json!([]),
        serde_json::json!(["https://records.example/multi-stage.html"]),
    );
    let args = workflow_args(
        "分析项目从阶段一到阶段三的完整记录",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_html_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(
        *offsets.lock().unwrap(),
        [0, HTML_RANGE_ONE.chars().count() as u64]
    );
    assert_eq!(
        output["research"]["metadata"]["web"]["document_range_count"],
        2
    );
    let sources = output["research"]["results"][0]["structured"]["sources"]
        .as_array()
        .expect("HTML sources");
    assert_eq!(sources.len(), 1);
    assert_eq!(
        sources[0]["evidence_excerpts"].as_array().map(Vec::len),
        Some(2)
    );
    assert!(sources[0]["evidence_excerpts"]
        .as_array()
        .into_iter()
        .flatten()
        .any(|excerpt| excerpt["quote_or_fact"]
            .as_str()
            .is_some_and(|text| text.contains("阶段三结论"))));
}

#[tokio::test]
async fn visible_constructor_like_text_is_not_removed_by_vocabulary() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let urls = Arc::new(Mutex::new(Vec::new()));
    let source_url = "https://records.example.test/generic-project";
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([(
            source_url.to_string(),
            "项目机构公布了第三阶段的最终记录。[完整记录](https://records.example.test/final) var swiper\\_results = new Swiper(\"#results .swiper\", { navigation: { nextEl: \".next\" } });"
                .to_string(),
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec!["第三阶段的最终记录".to_string()],
        fail: false,
        invalid_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([track("stage-three", "阶段三", "第三阶段的最终记录")]),
        serde_json::json!([]),
        serde_json::json!([source_url]),
    );
    let args = workflow_args(
        "项目状态记录",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(*urls.lock().unwrap(), [source_url]);
    assert!(output.to_string().contains("第三阶段的最终记录"));
    assert!(output.to_string().contains("Swiper"));
    assert!(output.to_string().contains("swiper\\\\_results"));
}

#[tokio::test]
async fn visible_serialized_text_is_not_removed_by_vocabulary() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let urls = Arc::new(Mutex::new(Vec::new()));
    let source_url = "https://records.example.test/generic-project";
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([(
            source_url.to_string(),
            r#"项目机构公布了第三阶段的最终记录。 },{\"type\":\"keyValue\",\"key\":\"ddna_timeout\",\"value\":\"5000\"},{\"type\":\"keyValue\",\"key\":\"enabletracking\",\"value\":true}"#
                .to_string(),
        )]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: vec!["第三阶段的最终记录".to_string()],
        fail: false,
        invalid_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([track("stage-three", "阶段三", "第三阶段的最终记录")]),
        serde_json::json!([]),
        serde_json::json!([source_url]),
    );
    let args = workflow_args(
        "项目状态记录",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;
    let rendered = output.to_string();

    assert_eq!(*urls.lock().unwrap(), [source_url]);
    assert!(rendered.contains("第三阶段的最终记录"), "{rendered}");
    assert!(rendered.contains("keyValue"), "{rendered}");
    assert!(rendered.contains("ddna_"), "{rendered}");
    assert!(rendered.contains("enabletracking"), "{rendered}");
}

#[tokio::test]
async fn local_only_retrieval_accepts_only_read_or_grep_anchors() {
    let workspace = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(workspace.path().join("src")).unwrap();
    std::fs::write(
        workspace.path().join("src/research.rs"),
        "pub const RESEARCH_BOUNDARY: &str = \"The observed file defines the research boundary from exact workspace text.\";\n",
    )
    .unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    executor.register_dynamic_tool(Arc::new(LocalEvidenceFixture));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: false,
        invalid_selection: false,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "workspace",
            "Workspace",
            "Inspect observed workspace evidence"
        )]),
        serde_json::json!([]),
        serde_json::json!([]),
    );
    plan["workspace_evidence_required"] = serde_json::json!(true);
    let args = workflow_args(
        "Inspect the local workspace",
        super::DeepResearchEvidenceScope::LocalOnly,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(output["research"]["status"], "partial_success");
    assert_eq!(
        output["research"]["metadata"]["evidence_selection_mode"],
        "semantic_chunk_ids_with_typed_coverage"
    );
    let sources = output["research"]["results"][0]["structured"]["sources"]
        .as_array()
        .expect("local sources");
    assert_eq!(sources.len(), 1);
    assert_eq!(sources[0]["url_or_path"], "src/research.rs");
    assert!(sources[0]["quote_or_fact"]
        .as_str()
        .is_some_and(|text| text.contains("exact workspace text")));
    assert_eq!(
        output["research"]["results"][0]["structured"]["gaps"],
        serde_json::json!([]),
        "collection diagnostics must not become semantic research gaps"
    );
    assert!(output["research"]["warnings"]["collection_errors"]
        .as_array()
        .is_some_and(|errors| !errors.is_empty()));
    assert!(!output.to_string().contains("fabricated.rs"));
    assert!(!output.to_string().contains("listed-only.rs"));
}

#[tokio::test]
async fn local_text_is_not_promoted_when_closed_chunk_selection_fails() {
    let workspace = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(workspace.path().join("src")).unwrap();
    let exact_text =
        "This exact local sentence must remain behind the failed semantic selector boundary.";
    std::fs::write(
        workspace.path().join("src/research.rs"),
        format!("pub const LOCAL_EVIDENCE: &str = \"{exact_text}\";\n"),
    )
    .unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    executor.register_dynamic_tool(Arc::new(LocalEvidenceFixture));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: true,
        invalid_selection: false,
    }));
    let mut plan = minimal_plan(
        serde_json::json!([track(
            "workspace",
            "Workspace",
            "Inspect observed workspace evidence"
        )]),
        serde_json::json!([]),
        serde_json::json!([]),
    );
    plan["workspace_evidence_required"] = serde_json::json!(true);
    let args = workflow_args(
        "Inspect the local workspace",
        super::DeepResearchEvidenceScope::LocalOnly,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(output["research"]["status"], "failed");
    assert_eq!(output["research"]["metadata"]["source_count"], 0);
    assert!(!output.to_string().contains(exact_text));
}

#[tokio::test]
async fn url_path_vocabulary_does_not_preclassify_fetchability() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let urls = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "Avatar",
            "url": "https://cdn.example/avatar.png",
            "engines": ["fixture"]
        }, {
            "title": "Archive",
            "url": "https://downloads.example/research.zip",
            "engines": ["fixture"]
        }, {
            "title": "Evidence",
            "url": "https://valid.example/evidence",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TextFetchFixture {
        urls: Arc::clone(&urls),
        bodies: BTreeMap::from([
            (
                "https://cdn.example/avatar.png".to_string(),
                "The first endpoint returns substantive traceable evidence for the requested focus."
                    .to_string(),
            ),
            (
                "https://downloads.example/research.zip".to_string(),
                "The second endpoint returns separate traceable evidence for the requested focus."
                    .to_string(),
            ),
            (
                "https://valid.example/evidence".to_string(),
                "The third endpoint returns additional traceable evidence for the requested focus."
                    .to_string(),
            ),
        ]),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: false,
        invalid_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([track("filter", "Filter", "Retain document evidence")]),
        serde_json::json!(["document evidence"]),
        serde_json::json!([]),
    );
    let args = workflow_args(
        "Retain document evidence",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_web_fetch",
    );

    let output = execute(&executor, &args).await;

    let expected_urls = [
        "https://cdn.example/avatar.png",
        "https://downloads.example/research.zip",
        "https://valid.example/evidence",
    ];
    assert_exact_calls_in_any_order(&urls.lock().unwrap(), &expected_urls);
    assert_eq!(output["research"]["metadata"]["source_count"], 3);
    assert_eq!(
        research_source_urls(&output),
        expected_urls.map(str::to_string)
    );
}

#[tokio::test]
async fn transient_fetches_receive_exactly_one_retry() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let calls = Arc::new(Mutex::new(Vec::new()));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "First",
            "url": "https://first.example/evidence",
            "engines": ["fixture"]
        }, {
            "title": "Second",
            "url": "https://second.example/evidence",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(TransientFetchFixture {
        calls: Arc::clone(&calls),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: false,
        invalid_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([track("retry", "Retry", "Retain retried evidence")]),
        serde_json::json!(["retried evidence"]),
        serde_json::json!([]),
    );
    let args = workflow_args(
        "Retain retried evidence",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_transient_fetch",
    );

    let output = execute(&executor, &args).await;

    assert_exact_calls_in_any_order(
        &calls.lock().unwrap(),
        &[
            "https://first.example/evidence",
            "https://first.example/evidence",
            "https://second.example/evidence",
            "https://second.example/evidence",
        ],
    );
    assert_eq!(output["research"]["metadata"]["source_count"], 2);
    assert_eq!(
        output["research"]["metadata"]["web"]["transport_retry_count"],
        2
    );
    assert_eq!(
        output["research"]["metadata"]["web"]["transport_retry_success_count"],
        2
    );
}

#[tokio::test]
async fn transport_like_error_text_does_not_trigger_an_untyped_retry() {
    let workspace = tempfile::tempdir().unwrap();
    let executor = ToolExecutor::new(workspace.path().to_string_lossy().to_string());
    let calls = Arc::new(AtomicUsize::new(0));
    executor.register_dynamic_tool(Arc::new(SearchFixture {
        queries: Arc::new(Mutex::new(Vec::new())),
        results: serde_json::json!([{
            "title": "Untyped failure",
            "url": "https://failure.example/evidence",
            "engines": ["fixture"]
        }]),
    }));
    executor.register_dynamic_tool(Arc::new(UntypedFetchFailureFixture {
        calls: Arc::clone(&calls),
    }));
    executor.register_dynamic_tool(Arc::new(SemanticSelectorFixture {
        preferred_fragments: Vec::new(),
        fail: false,
        invalid_selection: false,
    }));
    let plan = minimal_plan(
        serde_json::json!([track(
            "typed-retry",
            "Typed retry",
            "Retry only structured transport failures"
        )]),
        serde_json::json!(["structured retry"]),
        serde_json::json!([]),
    );
    let args = workflow_args(
        "Retry only structured transport failures",
        super::DeepResearchEvidenceScope::WebAndWorkspace,
        plan,
        "fixture_web_search",
        "fixture_untyped_fetch_failure",
    );

    let output = execute(&executor, &args).await;

    assert_eq!(calls.load(Ordering::SeqCst), 1);
    assert_eq!(
        output["research"]["metadata"]["web"]["transport_retry_count"],
        0
    );
    assert_eq!(output["research"]["status"], "failed");
}