awaken-server 0.6.0

Multi-protocol HTTP server with SSE, mailbox, and protocol adapters for Awaken
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
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
//! HTTP-level integration tests for ADR-0032 D6 + D1 + D7 routes:
//!
//!   /v1/eval/datasets          — list / create
//!   /v1/eval/datasets/:id      — get / put / delete
//!   /v1/eval/datasets/:id/items — curate from trace
//!   /v1/eval/runs              — list / start
//!   /v1/eval/runs/:id          — fetch (+ optional ?baseline= diff)
//!
//! Each test stands up a minimal `ServerState` with in-memory
//! ConfigStore + file-backed TraceStore + file-backed EvalRunStore, then
//! drives the router via `tower::ServiceExt::oneshot`. The harness is
//! deliberately leaner than `config_api.rs`: eval CRUD doesn't touch the
//! agent runtime except for `POST /v1/eval/runs`, which uses the
//! bundled scripted-executor path that doesn't need a real provider.

use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use awaken_eval::test_support::UnusedExecutor;
use awaken_eval::{
    DATASETS_NAMESPACE, DatasetSpec, EvalRun, EvalRunExecutionMode, EvalRunItem, EvalRunStore,
    FileEvalRunStore, Fixture, MatrixCell,
};
use awaken_ext_observability::trace_store::{TraceStore, file::FileTraceStore};
use awaken_ext_observability::{DelegationSpan, GenAISpan, MetricsEvent, SpanContext};
use awaken_runtime::builder::AgentRuntimeBuilder;
use awaken_server::app::{
    AdminApiConfig, ConfigModuleState, EvalModuleState, EventModuleState, ServerConfig,
    ServerState, TraceModuleState,
};
use awaken_server::mailbox::{Mailbox, MailboxConfig};
use awaken_server::routes::build_router;
use awaken_server::services::config_runtime::ConfigRuntimeManager;
use awaken_server_contract::config_record::{ConfigRecord, RecordMeta};
use awaken_server_contract::contract::config_store::ConfigStore;
use awaken_server_contract::contract::event_store::{EventReader, EventScope, EventVisibility};
use awaken_server_contract::contract::storage::StorageError;
use awaken_stores::{InMemoryEventStore, InMemoryStore};
use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use serde_json::{Value, json};
use tower::ServiceExt;

// ── Harness ───────────────────────────────────────────────────────────────

const BEARER: &str = "test-admin-token";

fn temp_dir(prefix: &str) -> std::path::PathBuf {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or_default();
    let dir = std::env::temp_dir().join(format!("awaken-{prefix}-{nanos}"));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

struct TestApp {
    router: axum::Router,
    config_store: Arc<dyn ConfigStore>,
    trace_store: Arc<FileTraceStore>,
    eval_run_store: Arc<FileEvalRunStore>,
    /// Root passed to `FileEvalRunStore::new`. Tests that need to seed a
    /// corrupt on-disk run (e.g. one with duplicate item keys that the
    /// store's `write()` would normally reject) write the JSON file
    /// straight to `{root}/eval_runs/{yyyy-mm}/{run_id}.json`.
    eval_run_root: std::path::PathBuf,
    event_store: Arc<InMemoryEventStore>,
}

async fn build_test_app_without_run_store() -> axum::Router {
    // Variant used by persist+no-store regression test: state has no
    // EvalRunStore attached so the online handler must refuse
    // persist=true BEFORE any provider call burns tokens.
    let thread_store = Arc::new(InMemoryStore::new());
    let config_store: Arc<dyn awaken_server_contract::contract::config_store::ConfigStore> =
        Arc::new(InMemoryStore::new());
    let runtime = Arc::new(
        AgentRuntimeBuilder::new()
            .with_provider("bootstrap", Arc::new(UnusedExecutor))
            .with_in_memory_thread_run_store(thread_store.clone())
            .build()
            .expect("build runtime"),
    );
    let resolver = runtime.resolver_arc();
    let mailbox = Arc::new(Mailbox::new(
        runtime.clone(),
        Arc::new(awaken_stores::InMemoryMailboxStore::new()),
        thread_store.clone(),
        "eval-test".into(),
        MailboxConfig::default(),
    ));
    let config_runtime_manager = Arc::new(
        ConfigRuntimeManager::new(runtime.clone(), config_store.clone())
            .expect("config runtime manager"),
    );

    let mut state = ServerState::new(
        runtime,
        mailbox,
        thread_store,
        resolver,
        ServerConfig {
            address: "127.0.0.1:0".to_string(),
            ..ServerConfig::default()
        },
    );
    state.config = Some(ConfigModuleState::new(config_store, config_runtime_manager));
    state.admin.admin_api_config = AdminApiConfig {
        expose_config_routes: true,
        bearer_token: Some(BEARER.into()),
        ..AdminApiConfig::default()
    };
    build_router(&state)
}

async fn build_test_app() -> TestApp {
    build_test_app_with_config_store(Arc::new(InMemoryStore::new())).await
}

async fn build_test_app_with_config_store(config_store: Arc<dyn ConfigStore>) -> TestApp {
    let thread_store = Arc::new(InMemoryStore::new());
    let trace_store = Arc::new(FileTraceStore::new(temp_dir("eval-trace")).unwrap());
    let eval_run_root = temp_dir("eval-runs");
    let eval_run_store = Arc::new(FileEvalRunStore::new(eval_run_root.clone()).unwrap());
    let event_store = Arc::new(InMemoryEventStore::new());

    let runtime = Arc::new(
        AgentRuntimeBuilder::new()
            .with_provider("bootstrap", Arc::new(UnusedExecutor))
            .with_in_memory_thread_run_store(thread_store.clone())
            .build()
            .expect("build runtime"),
    );
    let resolver = runtime.resolver_arc();
    let mailbox = Arc::new(Mailbox::new(
        runtime.clone(),
        Arc::new(awaken_stores::InMemoryMailboxStore::new()),
        thread_store.clone(),
        "eval-test".into(),
        MailboxConfig::default(),
    ));

    let config_runtime_manager = Arc::new(
        ConfigRuntimeManager::new(runtime.clone(), config_store.clone())
            .expect("config runtime manager"),
    );

    let mut state = ServerState::new(
        runtime,
        mailbox,
        thread_store,
        resolver,
        ServerConfig {
            address: "127.0.0.1:0".to_string(),
            ..ServerConfig::default()
        },
    );
    state.config = Some(ConfigModuleState::new(
        config_store.clone(),
        config_runtime_manager,
    ));
    state.trace = Some(TraceModuleState {
        trace_store: trace_store.clone() as Arc<dyn TraceStore>,
    });
    state.eval = Some(EvalModuleState {
        eval_run_store: eval_run_store.clone() as Arc<dyn EvalRunStore>,
    });
    state.events = Some(EventModuleState {
        event_store: event_store.clone(),
    });
    state.admin.admin_api_config = AdminApiConfig {
        expose_config_routes: true,
        expose_trace_routes: true,
        bearer_token: Some(BEARER.into()),
        ..AdminApiConfig::default()
    };

    TestApp {
        router: build_router(&state),
        config_store,
        trace_store,
        eval_run_store,
        eval_run_root,
        event_store,
    }
}

struct CasConflictConfigStore {
    inner: Arc<InMemoryStore>,
    conflict_id: String,
}

impl CasConflictConfigStore {
    fn new(conflict_id: &str) -> Self {
        Self {
            inner: Arc::new(InMemoryStore::new()),
            conflict_id: conflict_id.to_string(),
        }
    }
}

#[async_trait::async_trait]
impl ConfigStore for CasConflictConfigStore {
    async fn get(&self, namespace: &str, id: &str) -> Result<Option<Value>, StorageError> {
        self.inner.get(namespace, id).await
    }

    async fn list(
        &self,
        namespace: &str,
        offset: usize,
        limit: usize,
    ) -> Result<Vec<(String, Value)>, StorageError> {
        self.inner.list(namespace, offset, limit).await
    }

    async fn put(&self, namespace: &str, id: &str, value: &Value) -> Result<(), StorageError> {
        self.inner.put(namespace, id, value).await
    }

    async fn delete(&self, namespace: &str, id: &str) -> Result<(), StorageError> {
        self.inner.delete(namespace, id).await
    }

    async fn put_if_absent(
        &self,
        namespace: &str,
        id: &str,
        value: &Value,
    ) -> Result<(), StorageError> {
        self.inner.put_if_absent(namespace, id, value).await
    }

    async fn put_if_revision(
        &self,
        namespace: &str,
        id: &str,
        value: &Value,
        expected_revision: u64,
    ) -> Result<(), StorageError> {
        if namespace == DATASETS_NAMESPACE && id == self.conflict_id {
            return Err(StorageError::VersionConflict {
                expected: expected_revision,
                actual: expected_revision.saturating_add(1),
            });
        }
        self.inner
            .put_if_revision(namespace, id, value, expected_revision)
            .await
    }
}

/// Test-only backdoor: write a hand-crafted `EvalRun` JSON file straight
/// into the `FileEvalRunStore` shard layout, bypassing
/// `EvalRunStore::write`. Needed for regression tests that exercise
/// "what if a corrupt run is already on disk" scenarios — the normal
/// `write()` path now rejects duplicate-key runs, so the only way to
/// stage one is to drop the file in by hand.
fn seed_corrupt_eval_run(root: &std::path::Path, run: &EvalRun) {
    let (year, month) = {
        // Mirror FileEvalRunStore's shard layout: yyyy-mm derived from
        // started_at_secs, UTC. Use chrono via time so we don't pull in
        // a new test dep — the started_at is fully under test control
        // and we can hard-code the shard if we generate it ourselves.
        use chrono::{TimeZone, Utc};
        let dt = Utc.timestamp_opt(run.started_at_secs as i64, 0).unwrap();
        (dt.format("%Y").to_string(), dt.format("%m").to_string())
    };
    let shard = root.join("eval_runs").join(format!("{year}-{month}"));
    std::fs::create_dir_all(&shard).unwrap();
    let path = shard.join(format!("{}.json", run.id));
    let bytes = serde_json::to_vec(run).unwrap();
    std::fs::write(&path, bytes).unwrap();
}

async fn request(
    app: &axum::Router,
    method: &str,
    uri: &str,
    body: Option<Value>,
) -> (StatusCode, Value) {
    let mut builder = Request::builder()
        .method(method)
        .uri(uri)
        .header("Authorization", format!("Bearer {BEARER}"));
    let req = if let Some(b) = body {
        builder = builder.header("Content-Type", "application/json");
        builder
            .body(Body::from(serde_json::to_vec(&b).unwrap()))
            .unwrap()
    } else {
        builder.body(Body::empty()).unwrap()
    };
    let resp = app.clone().oneshot(req).await.unwrap();
    let status = resp.status();
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let value: Value = if bytes.is_empty() {
        Value::Null
    } else {
        serde_json::from_slice(&bytes).unwrap_or(Value::Null)
    };
    (status, value)
}

async fn request_bytes(
    app: &axum::Router,
    method: &str,
    uri: &str,
    body: Option<Value>,
) -> (StatusCode, Vec<u8>) {
    let mut builder = Request::builder()
        .method(method)
        .uri(uri)
        .header("Authorization", format!("Bearer {BEARER}"));
    let req = if let Some(b) = body {
        builder = builder.header("Content-Type", "application/json");
        builder
            .body(Body::from(serde_json::to_vec(&b).unwrap()))
            .unwrap()
    } else {
        builder.body(Body::empty()).unwrap()
    };
    let resp = app.clone().oneshot(req).await.unwrap();
    let status = resp.status();
    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    (status, bytes.to_vec())
}

fn sample_fixture(id: &str) -> Fixture {
    serde_json::from_value(json!({
        "id": id,
        "user_input": "what is six times seven",
        "provider_script": [
            {"kind": "chat_response", "content": "42", "tokens": {"total_tokens": 5}}
        ],
        "expect": { "final_answer_contains": ["42"] }
    }))
    .unwrap()
}

fn seed_indexed_trace(
    trace_store: &FileTraceStore,
    id: &str,
    text: &str,
    with_user: bool,
    started_secs: u64,
) {
    use awaken_ext_observability::trace_store::RunSummary;
    trace_store
        .append(
            id,
            &MetricsEvent::Inference(captured_inference_span(id, text, with_user)),
        )
        .unwrap();
    trace_store
        .write_index_for_run(
            id,
            &RunSummary {
                run_id: id.into(),
                agent_id: "default".into(),
                started_at: UNIX_EPOCH + std::time::Duration::from_secs(started_secs),
                ended_at: None,
                prompt_ids: vec![],
                experiment_id: None,
                variant_name: None,
                final_status: None,
                judge_score: None,
            },
        )
        .unwrap();
}

fn prune_all_unreferenced_traces(trace_store: &FileTraceStore) -> u64 {
    trace_store
        .prune(
            UNIX_EPOCH + std::time::Duration::from_secs(4_000_000_000),
            &std::collections::HashSet::new(),
        )
        .unwrap()
}

async fn seed_dataset_record(app: &TestApp, id: &str, spec: DatasetSpec) {
    let record = ConfigRecord {
        spec,
        meta: RecordMeta::new_user(),
    };
    let value = record.to_value().unwrap();
    app.config_store
        .put(DATASETS_NAMESPACE, id, &value)
        .await
        .unwrap();
}

// ── Dataset CRUD ──────────────────────────────────────────────────────────

#[tokio::test]
async fn dataset_create_get_list_delete_round_trip() {
    let app = build_test_app().await;

    // Create.
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-A",
            "spec": { "description": "smoke", "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "body: {body}");
    assert_eq!(body["meta"]["revision"], 0);

    // Get.
    let (status, body) = request(&app.router, "GET", "/v1/eval/datasets/DS-A", None).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["spec"]["description"], "smoke");
    assert_eq!(body["spec"]["fixtures"].as_array().unwrap().len(), 1);

    // List.
    let (status, body) = request(&app.router, "GET", "/v1/eval/datasets", None).await;
    assert_eq!(status, StatusCode::OK);
    let datasets = body["datasets"].as_array().unwrap();
    assert_eq!(datasets.len(), 1);
    assert_eq!(datasets[0]["id"], "DS-A");
    assert_eq!(datasets[0]["fixture_count"], 1);

    // Delete (idempotent).
    let (status, _) = request(&app.router, "DELETE", "/v1/eval/datasets/DS-A", None).await;
    assert_eq!(status, StatusCode::NO_CONTENT);
    let (status, _) = request(&app.router, "DELETE", "/v1/eval/datasets/DS-A", None).await;
    assert_eq!(status, StatusCode::NO_CONTENT, "delete is idempotent");
}

/// `DELETE ?expected_revision=N` is a compare-and-swap. The trace →
/// fixture rollback relies on it: if a concurrent operator appended a
/// fixture between the inline create and the failed curate, the revision
/// has moved and the guarded delete must reject (409) rather than wipe
/// their work. An unguarded delete (no query param) still removes
/// unconditionally.
#[tokio::test]
async fn delete_dataset_guarded_by_expected_revision() {
    let app = build_test_app().await;

    // Inline-created dataset starts at revision 0 (mirrors the rollback
    // path: SaveTraceAsFixtureModal creates an empty dataset, captures
    // its revision, then tries to curate).
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-GUARD", "spec": { "fixtures": [] } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "body: {body}");
    assert_eq!(body["meta"]["revision"], 0);

    // Simulate the concurrent write that the rollback must not destroy:
    // another operator appends a fixture, bumping the revision to 1.
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-GUARD/fixtures",
        Some(json!({ "fixture": sample_fixture("concurrent"), "expected_revision": 0 })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    // Rollback deletes against the *stale* revision it captured at create
    // time (0). The dataset is now at revision 1 → 409, data preserved.
    let (status, _) = request(
        &app.router,
        "DELETE",
        "/v1/eval/datasets/DS-GUARD?expected_revision=0",
        None,
    )
    .await;
    assert_eq!(
        status,
        StatusCode::CONFLICT,
        "stale revision must not delete"
    );
    let (status, body) = request(&app.router, "GET", "/v1/eval/datasets/DS-GUARD", None).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "dataset survived the guarded delete"
    );
    assert_eq!(body["spec"]["fixtures"].as_array().unwrap().len(), 1);

    // Guarded delete against the current revision (1) succeeds.
    let (status, _) = request(
        &app.router,
        "DELETE",
        "/v1/eval/datasets/DS-GUARD?expected_revision=1",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::NO_CONTENT);
    let (status, _) = request(&app.router, "GET", "/v1/eval/datasets/DS-GUARD", None).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn dataset_create_400s_on_duplicate_fixture_id() {
    // Duplicate fixture ids would silently overwrite each other inside
    // the diff map (`BTreeMap` keyed by fixture_id) and produce a result
    // whose meaning depends on Vec ordering. Reject up front.
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-DUPFX",
            "spec": { "fixtures": [sample_fixture("twin"), sample_fixture("twin")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("duplicate fixture id"),
        "body: {body}"
    );
}

#[tokio::test]
async fn dataset_create_400s_on_invalid_min_judge_score() {
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-BAD-JUDGE-THRESHOLD",
            "spec": {
                "fixtures": [{
                    "id": "bad-threshold",
                    "user_input": "grade this",
                    "provider_script": [
                        {"kind": "chat_response", "content": "ok"}
                    ],
                    "expect": { "min_judge_score": 1.5 }
                }]
            }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    let err = body["error"].as_str().unwrap_or("");
    assert!(err.contains("min_judge_score"), "body: {body}");
    assert!(err.contains("[0.0, 1.0]"), "body: {body}");
}

#[tokio::test]
async fn dataset_put_400s_on_duplicate_fixture_id() {
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-DUPPUT", "spec": { "fixtures": [sample_fixture("a")] } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    let (status, body) = request(
        &app.router,
        "PUT",
        "/v1/eval/datasets/DS-DUPPUT",
        Some(json!({
            "expected_revision": 0,
            "spec": { "fixtures": [sample_fixture("twin"), sample_fixture("twin")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("duplicate fixture id"),
        "body: {body}"
    );
}

#[tokio::test]
async fn dataset_create_conflicts_on_duplicate_id() {
    let app = build_test_app().await;
    let body = json!({
        "id": "DS-DUP",
        "spec": { "fixtures": [sample_fixture("a")] }
    });
    let (status, _) = request(&app.router, "POST", "/v1/eval/datasets", Some(body.clone())).await;
    assert_eq!(status, StatusCode::CREATED);
    let (status, body) = request(&app.router, "POST", "/v1/eval/datasets", Some(body)).await;
    assert_eq!(status, StatusCode::CONFLICT, "body: {body}");
}

#[tokio::test]
async fn dataset_put_with_stale_revision_returns_409() {
    let app = build_test_app().await;
    let initial = json!({
        "id": "DS-REV",
        "spec": { "fixtures": [sample_fixture("a")] }
    });
    let (status, _) = request(&app.router, "POST", "/v1/eval/datasets", Some(initial)).await;
    assert_eq!(status, StatusCode::CREATED);

    // PUT with revision=0 (matches the freshly-created record).
    let put_body = json!({
        "expected_revision": 0,
        "spec": { "fixtures": [sample_fixture("a"), sample_fixture("b")] }
    });
    let (status, body) = request(
        &app.router,
        "PUT",
        "/v1/eval/datasets/DS-REV",
        Some(put_body.clone()),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    assert_eq!(body["meta"]["revision"], 1);

    // Repeat PUT with the now-stale revision=0 — must 409.
    let (status, body) = request(
        &app.router,
        "PUT",
        "/v1/eval/datasets/DS-REV",
        Some(put_body),
    )
    .await;
    assert_eq!(status, StatusCode::CONFLICT, "body: {body}");
}

#[tokio::test]
async fn dataset_get_returns_404_for_unknown_id() {
    let app = build_test_app().await;
    let (status, _) = request(&app.router, "GET", "/v1/eval/datasets/ghost", None).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── Curate from trace ─────────────────────────────────────────────────────

fn captured_inference_span(run_id: &str, text: &str, with_user: bool) -> GenAISpan {
    let request_messages = if with_user {
        Some(json!([
            {"role": "user", "content": [{"type": "text", "text": "auto prompt"}]}
        ]))
    } else {
        None
    };
    GenAISpan {
        context: SpanContext {
            run_id: run_id.into(),
            agent_id: "default".into(),
            ..Default::default()
        },
        step_index: Some(0),
        model: "claude-opus-4-7".into(),
        provider: "anthropic".into(),
        operation: "chat".into(),
        response_model: None,
        response_id: None,
        finish_reasons: vec!["end_turn".into()],
        error_type: None,
        error_class: None,
        thinking_tokens: None,
        input_tokens: Some(10),
        output_tokens: Some(4),
        total_tokens: Some(14),
        cache_read_input_tokens: None,
        cache_creation_input_tokens: None,
        temperature: None,
        top_p: None,
        max_tokens: None,
        stop_sequences: vec![],
        duration_ms: 1,
        started_at_ms: 0,
        ended_at_ms: 0,
        response_content: Some(json!([{"type": "text", "text": text}])),
        response_tool_calls: None,
        request_messages,
    }
}

fn unsupported_provider_script_span(run_id: &str) -> GenAISpan {
    let mut span = captured_inference_span(run_id, "", true);
    span.finish_reasons = vec!["tool_use".into()];
    span.response_content = None;
    span.response_tool_calls = Some(json!([
        {"id": "call-1", "name": "search", "arguments": {"q": "alpha"}},
        {"id": "call-2", "name": "write", "arguments": {"text": "beta"}}
    ]));
    span
}

fn delegation_span(parent_run_id: &str, child_run_id: &str) -> DelegationSpan {
    DelegationSpan {
        context: SpanContext {
            run_id: parent_run_id.into(),
            agent_id: "default".into(),
            ..Default::default()
        },
        parent_run_id: parent_run_id.into(),
        child_run_id: Some(child_run_id.into()),
        target_agent_id: "researcher".into(),
        tool_call_id: "call-subagent".into(),
        duration_ms: Some(7),
        success: true,
        error_message: None,
        timestamp_ms: 1,
    }
}

#[tokio::test]
async fn curate_items_appends_fixture_recovered_from_trace() {
    let app = build_test_app().await;

    // Seed a trace whose first span captured the user prompt — the
    // server must recover user_input without operator help.
    let run_id = "01HXCUR0000000000000000001";
    app.trace_store
        .append(
            run_id,
            &MetricsEvent::Inference(captured_inference_span(run_id, "the answer is 42", true)),
        )
        .unwrap();

    // Empty dataset to receive the curated fixture.
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-CUR", "spec": {} })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    // Curate.
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-CUR/items",
        Some(json!({
            "from_run_id": run_id,
            "expected": { "final_answer_contains": ["42"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "body: {body}");
    assert_eq!(body["spec"]["fixtures"].as_array().unwrap().len(), 1);
    let added = &body["spec"]["fixtures"][0];
    assert_eq!(added["id"], run_id);
    assert_eq!(added["user_input"], "auto prompt");
    assert_eq!(added["source_run_id"], run_id);
    assert_eq!(added["expect"]["final_answer_contains"][0], "42");

    let removed = app
        .trace_store
        .prune(
            UNIX_EPOCH + std::time::Duration::from_secs(4_000_000_000),
            &std::collections::HashSet::new(),
        )
        .unwrap();
    assert_eq!(removed, 0, "curated source trace must be pinned");
    assert!(
        !app.trace_store.read(run_id).unwrap().is_empty(),
        "source trace should survive retention after curation"
    );
}

#[tokio::test]
async fn trace_to_dataset_to_eval_round_trips_with_subagent_trace() {
    let app = build_test_app().await;
    let parent_run_id = "01HXE2E000000000000000001";
    let child_run_id = "01HXE2E000000000000000002";

    app.trace_store
        .append(
            parent_run_id,
            &MetricsEvent::Delegation(delegation_span(parent_run_id, child_run_id)),
        )
        .unwrap();
    app.trace_store
        .append(
            parent_run_id,
            &MetricsEvent::Inference(captured_inference_span(
                parent_run_id,
                "sub-agent found answer 42",
                true,
            )),
        )
        .unwrap();
    app.trace_store
        .append(
            child_run_id,
            &MetricsEvent::Inference(captured_inference_span(
                child_run_id,
                "child research result",
                true,
            )),
        )
        .unwrap();

    let (status, bytes) = request_bytes(
        &app.router,
        "GET",
        &format!("/v1/traces/{parent_run_id}"),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let trace_body = String::from_utf8(bytes).unwrap();
    assert!(trace_body.contains("\"type\":\"delegation\""));
    assert!(trace_body.contains(child_run_id));
    assert!(trace_body.contains("sub-agent found answer 42"));

    let (status, bytes) = request_bytes(
        &app.router,
        "GET",
        &format!("/v1/traces/{child_run_id}"),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        String::from_utf8(bytes)
            .unwrap()
            .contains("child research result")
    );

    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-E2E-SUB", "spec": {} })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, dataset) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-E2E-SUB/items",
        Some(json!({
            "from_run_id": parent_run_id,
            "expected": { "final_answer_contains": ["42"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "body: {dataset}");
    let fixture = &dataset["spec"]["fixtures"][0];
    assert_eq!(fixture["source_run_id"], parent_run_id);
    assert_eq!(fixture["source_model_id"], "claude-opus-4-7");
    assert_eq!(fixture["user_input"], "auto prompt");
    assert_eq!(
        fixture["provider_script"][0]["content"],
        "sub-agent found answer 42"
    );

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-E2E-SUB",
            "mode": "scripted",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    let item = &body["run"]["items"][0];
    assert!(item["report"]["passed"].as_bool().unwrap());
    assert_eq!(item["report"]["final_text"], "sub-agent found answer 42");
    assert!(
        item["trace_run_id"].is_string(),
        "eval item should link to replay trace: {item}"
    );
}

#[tokio::test]
async fn curate_items_cas_failure_does_not_pin_trace() {
    let app =
        build_test_app_with_config_store(Arc::new(CasConflictConfigStore::new("DS-CUR-CAS"))).await;
    let run_id = "01HXCUR0000000000000000CAS";
    app.trace_store
        .append(
            run_id,
            &MetricsEvent::Inference(captured_inference_span(run_id, "the answer is 42", true)),
        )
        .unwrap();
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-CUR-CAS", "spec": {} })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-CUR-CAS/items",
        Some(json!({
            "from_run_id": run_id,
            "expected": { "final_answer_contains": ["42"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CONFLICT);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("revision conflict"),
        "body: {body}"
    );
    assert_eq!(
        prune_all_unreferenced_traces(app.trace_store.as_ref()),
        1,
        "failed dataset CAS must not create trace retention references"
    );
}

#[tokio::test]
async fn parallel_tool_trace_curates_live_only_and_scripted_eval_fails_closed() {
    // The primary curation value for Live eval is the captured user
    // prompt + expectations. `provider_script` is an optional scripted
    // snapshot; when its schema cannot represent the trace, the server
    // must not reject an otherwise useful real-agent fixture.
    let app = build_test_app().await;
    let run_id = "01HXCUR0000000000000000004";
    app.trace_store
        .append(
            run_id,
            &MetricsEvent::Inference(unsupported_provider_script_span(run_id)),
        )
        .unwrap();

    let (status, bytes) =
        request_bytes(&app.router, "GET", &format!("/v1/traces/{run_id}"), None).await;
    assert_eq!(status, StatusCode::OK);
    let trace_body = String::from_utf8(bytes).unwrap();
    assert!(trace_body.contains("\"name\":\"search\""));
    assert!(trace_body.contains("\"name\":\"write\""));

    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-CUR-LIVE", "spec": {} })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-CUR-LIVE/items",
        Some(json!({
            "from_run_id": run_id,
            "expected": { "final_answer_contains": ["answer"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "body: {body}");
    let added = &body["spec"]["fixtures"][0];
    assert_eq!(added["user_input"], "auto prompt");
    assert!(added["provider_script"].is_null());
    assert!(
        added["provider_script_error"]
            .as_str()
            .unwrap_or("")
            .contains("provider_script currently supports one tool call"),
        "fixture: {added}"
    );

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-CUR-LIVE",
            "mode": "scripted",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    let report = &body["run"]["items"][0]["report"];
    assert!(!report["passed"].as_bool().unwrap());
    assert_eq!(report["runtime_failure"]["kind"], "runtime_error");
    assert!(
        report["runtime_failure"]["message"]
            .as_str()
            .unwrap_or("")
            .contains("no replayable provider_script"),
        "report: {report}"
    );
}

#[tokio::test]
async fn curate_items_require_mode_rejects_unsupported_provider_script() {
    let app = build_test_app().await;
    let run_id = "01HXCUR0000000000000000005";
    app.trace_store
        .append(
            run_id,
            &MetricsEvent::Inference(unsupported_provider_script_span(run_id)),
        )
        .unwrap();

    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-CUR-REQ", "spec": {} })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-CUR-REQ/items",
        Some(json!({
            "from_run_id": run_id,
            "provider_script_mode": "require",
            "expected": { "final_answer_contains": ["answer"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("provider_script currently supports one tool call"),
        "body: {body}"
    );
}

#[tokio::test]
async fn curate_items_400s_on_empty_expected() {
    let app = build_test_app().await;
    let run_id = "01HXCUR0000000000000000003";
    app.trace_store
        .append(
            run_id,
            &MetricsEvent::Inference(captured_inference_span(run_id, "ok", true)),
        )
        .unwrap();

    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-CUR3", "spec": {} })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-CUR3/items",
        Some(json!({ "from_run_id": run_id, "expected": {} })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("at least one expectation"),
        "body: {body}"
    );
}

#[tokio::test]
async fn curate_items_400s_when_trace_lacks_user_and_body_lacks_input() {
    let app = build_test_app().await;

    let run_id = "01HXCUR0000000000000000002";
    app.trace_store
        .append(
            run_id,
            &MetricsEvent::Inference(captured_inference_span(run_id, "ok", false)),
        )
        .unwrap();

    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-CUR2", "spec": {} })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-CUR2/items",
        Some(json!({
            "from_run_id": run_id,
            "expected": { "final_answer_contains": ["ok"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("user_input"),
        "body: {body}"
    );
}

// ── Eval runs ─────────────────────────────────────────────────────────────

#[tokio::test]
async fn start_eval_run_drives_dataset_and_persists() {
    let app = build_test_app().await;

    // Seed a dataset that the run will exercise.
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-RUN",
            "spec": {
                "fixtures": [sample_fixture("alpha"), sample_fixture("beta")]
            }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({ "dataset_id": "DS-RUN" })),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    let run = &body["run"];
    assert_eq!(run["dataset_id"], "DS-RUN");
    assert_eq!(run["execution_mode"], "scripted");
    let items = run["items"].as_array().unwrap();
    assert_eq!(items.len(), 2);
    for item in items {
        assert!(item["report"]["passed"].as_bool().unwrap());
        // Tee sink wired in the harness — trace_run_id must be present.
        assert!(item["trace_run_id"].is_string());
    }
    // No baseline requested → no diff.
    assert!(body["diff"].is_null());

    let run_id = run["id"].as_str().unwrap();
    let page = app
        .event_store
        .list(EventScope::run(run_id), None, 10)
        .await
        .unwrap();
    assert_eq!(page.events.len(), 2);
    assert_eq!(page.events[0].event_kind.as_str(), "EvalRunStarted");
    assert_eq!(page.events[0].payload["dataset_id"], "DS-RUN");
    assert_eq!(page.events[0].payload["planned_item_count"], 2);
    assert_eq!(page.events[1].event_kind.as_str(), "EvalRunCompleted");
    assert_eq!(page.events[1].payload["item_count"], 2);
    assert_eq!(page.events[1].payload["passed_count"], 2);
    assert_eq!(page.events[1].payload["persisted"], true);
    assert_eq!(page.events[1].visibility, EventVisibility::Internal);
}

#[tokio::test]
async fn start_eval_run_accepts_explicit_scripted_mode() {
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-RUN-SCRIPTED",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-RUN-SCRIPTED",
            "mode": "scripted",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    assert_eq!(body["run"]["execution_mode"], "scripted");
    assert_eq!(body["run"]["items"].as_array().unwrap().len(), 1);
    assert!(body["run"]["items"][0]["cell"].is_null());
}

#[tokio::test]
async fn start_eval_run_400s_for_empty_dataset() {
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-EMPTY", "spec": {} })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({ "dataset_id": "DS-EMPTY" })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("no fixtures to replay"),
        "body: {body}"
    );
}

#[tokio::test]
async fn get_eval_run_with_baseline_surfaces_diff() {
    let app = build_test_app().await;

    // Pre-seed two runs directly via EvalRunStore so we don't have to
    // double-replay through the route (already covered above) and can
    // craft a guaranteed difference between them.
    let store = app.eval_run_store.clone();
    let baseline = baseline_run("BASE-001");
    let new = new_run_with_drift("NEW-001");
    store.write(&baseline).unwrap();
    store.write(&new).unwrap();

    let (status, body) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/NEW-001?baseline=BASE-001",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    let diff = &body["diff"];
    assert!(diff.is_object(), "diff present");
    // At least one drift/regression entry from the seeded difference.
    let entries = diff["entries"].as_array().unwrap();
    assert!(
        entries
            .iter()
            .any(|e| e["kind"] == "drift" || e["kind"] == "regression"),
        "expected a drift or regression; got {entries:?}"
    );
}

#[tokio::test]
async fn get_eval_run_diff_keys_cell_less_samples_by_sample_index() {
    let app = build_test_app().await;
    let store = app.eval_run_store.clone();

    let mut baseline = baseline_run("BASE-SAMPLES");
    baseline.items = vec![
        {
            let mut it = item("alpha", true, "same");
            it.sample_index = Some(0);
            it
        },
        {
            let mut it = item("alpha", true, "old");
            it.sample_index = Some(1);
            it
        },
    ];
    let mut new = baseline_run("NEW-SAMPLES");
    new.items = vec![
        {
            let mut it = item("alpha", true, "same");
            it.sample_index = Some(0);
            it
        },
        {
            let mut it = item("alpha", false, "bad");
            it.sample_index = Some(1);
            it
        },
    ];
    store.write(&baseline).unwrap();
    store.write(&new).unwrap();

    let (status, body) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/NEW-SAMPLES?baseline=BASE-SAMPLES",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    let entries = body["diff"]["entries"].as_array().unwrap();
    assert_eq!(entries.len(), 2, "body: {body}");
    assert!(
        entries
            .iter()
            .any(|e| e["sample_index"] == 0 && e["kind"] == "unchanged"),
        "sample 0 should pair independently: {body}"
    );
    assert!(
        entries
            .iter()
            .any(|e| e["sample_index"] == 1 && e["kind"] == "regression"),
        "sample 1 should pair independently: {body}"
    );
}

#[tokio::test]
async fn get_eval_run_diff_400s_on_sample_count_mismatch() {
    let app = build_test_app().await;
    let store = app.eval_run_store.clone();
    let cell = MatrixCell {
        model_id: Some("m1".into()),
    };

    let mut baseline = baseline_run("BASE-SAMPLE-DIFF");
    baseline.execution_mode = EvalRunExecutionMode::Live;
    baseline.items[0].cell = Some(cell.clone());

    let mut new = baseline_run("NEW-SAMPLE-DIFF");
    new.execution_mode = EvalRunExecutionMode::Live;
    new.items = (0..2)
        .map(|sample| {
            let mut it = item("alpha", true, &format!("sample {sample}"));
            it.cell = Some(cell.clone());
            it.sample_index = Some(sample);
            it
        })
        .collect();

    store.write(&baseline).unwrap();
    store.write(&new).unwrap();
    let (status, body) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/NEW-SAMPLE-DIFF?baseline=BASE-SAMPLE-DIFF",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("different sample counts"),
        "body: {body}"
    );
}

#[tokio::test]
async fn get_eval_run_baseline_400s_on_adhoc_run() {
    // Ad-hoc online runs all carry dataset_id="_adhoc" + revision 0.
    // Without an explicit guard, two unrelated _adhoc runs would pass
    // the dataset-revision schema check and produce a meaningless diff.
    let app = build_test_app().await;
    let mut adhoc_a = baseline_run("ADHOC-A");
    let mut adhoc_b = baseline_run("ADHOC-B");
    adhoc_a.dataset_id = "_adhoc".into();
    adhoc_a.dataset_revision = 0;
    adhoc_b.dataset_id = "_adhoc".into();
    adhoc_b.dataset_revision = 0;
    app.eval_run_store.write(&adhoc_a).unwrap();
    app.eval_run_store.write(&adhoc_b).unwrap();
    let (status, body) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/ADHOC-B?baseline=ADHOC-A",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("ad-hoc"),
        "body: {body}"
    );
}

#[tokio::test]
async fn get_eval_run_dirty_historical_run_500s_without_diff_context() {
    // Reading an already-corrupt stored run directly is a store
    // corruption signal, not a bad diff selection. The diff routes map
    // the same duplicate-key shape to 400 because the caller selected a
    // non-diffable current/baseline pair; a plain GET has no such
    // request context and should stay fail-loud as 500.
    let app = build_test_app().await;
    let mut dirty = baseline_run("DIRTY-NODIFF");
    let dup = dirty.items[0].clone();
    dirty.items.push(dup);
    seed_corrupt_eval_run(&app.eval_run_root, &dirty);

    let (status, body) = request(&app.router, "GET", "/v1/eval/runs/DIRTY-NODIFF", None).await;
    assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("duplicate eval-run item key"),
        "body: {body}"
    );
}

#[tokio::test]
async fn get_eval_run_diff_400s_when_selected_current_has_duplicate_item_keys() {
    // Diff must refuse to silently collapse duplicate (fixture_id, cell,
    // sample_index) keys via the BTreeMap pairing. A run that managed
    // to land two items with the same key (e.g. a future store impl
    // with weaker write-once guarantees) should surface a structured
    // error from /v1/eval/runs/:id?baseline=, not produce an
    // order-dependent diff.
    let app = build_test_app().await;
    let mut baseline = baseline_run("BASE-DUP");
    let mut newer = baseline_run("NEW-DUP");
    // Inject a duplicate item into the new run.
    let dup = newer.items[0].clone();
    newer.items.push(dup);
    baseline.dataset_id = newer.dataset_id.clone();
    baseline.dataset_revision = newer.dataset_revision;
    app.eval_run_store.write(&baseline).unwrap();
    // `FileEvalRunStore::write` now rejects duplicate-key runs at the
    // store boundary, so the only way to stage the corrupt-newer
    // scenario this test exercises is to drop the JSON in by hand —
    // exactly the "future store impl with weaker guarantees" the diff
    // guard is supposed to catch.
    seed_corrupt_eval_run(&app.eval_run_root, &newer);
    let (status, body) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/NEW-DUP?baseline=BASE-DUP",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("duplicate"),
        "body: {body}"
    );
}

#[tokio::test]
async fn get_eval_run_diff_400s_when_selected_baseline_has_duplicate_item_keys() {
    // Symmetric to the corrupt-current case above: selecting a baseline
    // that cannot be diffed is a bad diff request, not an internal
    // failure. The normal store write path rejects this shape, so seed
    // it directly to model already-corrupt on-disk state.
    let app = build_test_app().await;
    let mut baseline = baseline_run("BASE-DUP");
    let dup = baseline.items[0].clone();
    baseline.items.push(dup);
    let newer = new_run_with_drift("NEW-GOOD");
    app.eval_run_store.write(&newer).unwrap();
    seed_corrupt_eval_run(&app.eval_run_root, &baseline);

    let (status, body) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/NEW-GOOD?baseline=BASE-DUP",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("duplicate eval-run item key"),
        "body: {body}"
    );
}

#[tokio::test]
async fn get_eval_run_baseline_400s_on_dataset_id_mismatch() {
    // Baseline run is for DS-DIFF; new run is for DS-OTHER. The
    // diff is meaningless across dataset schemas, so the route must
    // reject rather than silently produce a misleading diff on
    // coincidentally-matching fixture ids.
    let app = build_test_app().await;
    let baseline = baseline_run("BASE-X");
    let mut other = baseline_run("NEW-X");
    other.dataset_id = "DS-OTHER".into();
    app.eval_run_store.write(&baseline).unwrap();
    app.eval_run_store.write(&other).unwrap();

    let (status, body) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/NEW-X?baseline=BASE-X",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("across datasets"),
        "body: {body}"
    );
}

#[tokio::test]
async fn get_eval_run_baseline_400s_on_dataset_revision_mismatch() {
    // Same dataset_id, different revision — the fixture set behind
    // each revision may differ; reject rather than silently diff.
    let app = build_test_app().await;
    let baseline = baseline_run("BASE-R");
    let mut newer = baseline_run("NEW-R");
    newer.dataset_revision = 2;
    app.eval_run_store.write(&baseline).unwrap();
    app.eval_run_store.write(&newer).unwrap();

    let (status, body) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/NEW-R?baseline=BASE-R",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("dataset revisions"),
        "body: {body}"
    );
}

#[tokio::test]
async fn get_eval_run_with_unknown_baseline_returns_404() {
    let app = build_test_app().await;
    let run = baseline_run("LONELY");
    app.eval_run_store.write(&run).unwrap();
    let (status, _) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/LONELY?baseline=ghost",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── Atomic fixture append (POST /v1/eval/datasets/:id/fixtures) ──────────

#[tokio::test]
async fn append_fixture_adds_to_existing_dataset_and_bumps_revision() {
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-APPEND",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-APPEND/fixtures",
        Some(json!({
            "fixture": sample_fixture("beta"),
            "expected_revision": 0
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "body: {body}");
    assert_eq!(body["meta"]["revision"], 1);
    let names: Vec<&str> = body["spec"]["fixtures"]
        .as_array()
        .unwrap()
        .iter()
        .map(|f| f["id"].as_str().unwrap())
        .collect();
    assert_eq!(names, vec!["alpha", "beta"]);
}

#[tokio::test]
async fn append_fixture_409s_on_stale_revision() {
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-STALE",
            "spec": { "fixtures": [sample_fixture("a")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-STALE/fixtures",
        Some(json!({
            "fixture": sample_fixture("b"),
            "expected_revision": 99
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CONFLICT, "body: {body}");
}

#[tokio::test]
async fn append_fixture_409s_on_duplicate_id() {
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-DUP-FX",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-DUP-FX/fixtures",
        Some(json!({
            "fixture": sample_fixture("alpha"),
            "expected_revision": 0
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CONFLICT, "body: {body}");
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("already has fixture"),
        "body: {body}"
    );
}

// ── Dataset run matrix-mode validation ────────────────────────────────────

#[tokio::test]
async fn start_eval_run_with_models_404s_on_unknown_model() {
    // Dataset has fixtures (scripted) but the matrix references an
    // unregistered model — fast-fail with 404 before any cell runs.
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-MATRIX",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-MATRIX",
            "models": ["unknown-model"]
        })),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("unknown-model"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_revalidates_dataset_fixture_ids_before_model_lookup() {
    // Directly seed a corrupt historical dataset: normal dataset CRUD would
    // reject duplicate fixture ids. start_eval_run must catch it before model
    // lookup/provider calls, so the response is a dataset 400 rather than a
    // missing-model 404 after partial preflight.
    let app = build_test_app().await;
    seed_dataset_record(
        &app,
        "DS-CORRUPT-DUP-FX",
        DatasetSpec {
            description: String::new(),
            fixtures: vec![sample_fixture("dup"), sample_fixture("dup")],
        },
    )
    .await;

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-CORRUPT-DUP-FX",
            "mode": "live",
            "models": ["missing-model"]
        })),
    )
    .await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("duplicate fixture id"),
        "body: {body}"
    );
    assert!(
        app.eval_run_store
            .list(&awaken_eval::EvalRunFilter::default())
            .unwrap()
            .is_empty(),
        "dirty dataset preflight must not persist a run"
    );
}

#[tokio::test]
async fn start_eval_run_caps_total_cells() {
    // 50 fixtures × 3 models = 150 cells exceeds MAX_CELLS_PER_SYNC_RUN (100).
    let app = build_test_app().await;
    let fixtures: Vec<_> = (0..50).map(|i| sample_fixture(&format!("f{i}"))).collect();
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-BIG", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-BIG",
            "models": ["m1", "m2", "m3"]
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("expands to 150 units"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_on_zero_walltime() {
    // `Some(0)` is rejected explicitly (mirrors /v1/eval/online) so the
    // operator notices the typo instead of silently inheriting the 60s
    // default. Omitting the field still takes the default.
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-WALLTIME",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-WALLTIME",
            "models": ["m1"],
            "max_walltime_secs": 0,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("max_walltime_secs"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_when_scripted_sets_walltime() {
    // The field is Live-only. Accepting a non-zero value on scripted
    // mode would be a silent no-op, which makes API behaviour harder to
    // reason about than rejecting the misconfiguration.
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-SCRIPTED-WALLTIME",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-SCRIPTED-WALLTIME",
            "mode": "scripted",
            "max_walltime_secs": 10,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("requires mode=\"live\""),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_when_scripted_sets_token_budget() {
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-SCRIPTED-TOKENS",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-SCRIPTED-TOKENS",
            "mode": "scripted",
            "max_total_tokens": 10,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("max_total_tokens requires mode=\"live\""),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_on_zero_samples() {
    // `samples: 0` is rejected explicitly instead of silently coerced to
    // 1 — the operator who typed 0 most likely meant "off" (omit) or a
    // real number, and coercing hides the typo.
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-SAMPLES",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-SAMPLES",
            "models": ["m1"],
            "samples": 0,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("samples"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_when_scripted_passes_samples() {
    // `samples` is a Live-only request field (documented on
    // `StartRunRequest.samples` and listed in the PR summary). Scripted
    // replays are deterministic, so an explicit value is misconfiguration
    // and gets rejected before the numeric cap check. Omitting `samples`
    // still works in both modes.
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-SAMPLES-SCRIPTED",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-SAMPLES-SCRIPTED",
            "mode": "scripted",
            "samples": 999999,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("samples requires mode=\"live\""),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_baseline_validated_before_replay() {
    // Bad baseline_run_id must fail BEFORE any provider call or run
    // persist. The whole point is symmetry with the persist+no-store
    // guard: typo / wrong-dataset / wrong-revision baselines should not
    // silently burn tokens and leave a polluting half-finished run in
    // the store.
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-PREFLIGHT",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    // Baseline that points at a non-existent run.
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-PREFLIGHT",
            "baseline_run_id": "nonexistent",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("baseline eval run not found"),
        "body: {body}"
    );
    // Store stays empty — the missing-baseline check ran before any
    // replay or persist.
    assert_eq!(
        app.eval_run_store.list(&Default::default()).unwrap().len(),
        0
    );
}

#[tokio::test]
async fn start_eval_run_shape_errors_surface_before_baseline_check() {
    // Regression: when a request is BOTH shape-malformed (e.g.
    // `mode=scripted` with a `models` axis) AND references a bad
    // baseline, the response should report the shape error — the caller
    // needs to fix the request itself before the baseline matters. An
    // earlier ordering ran the baseline preflight first, so the caller
    // saw "baseline not found" while the real bug was the body.
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-PRIORITY",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-PRIORITY",
            "mode": "scripted",
            "models": ["any-model"],
            "baseline_run_id": "nonexistent",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("`models` is only valid with mode=\"live\""),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_baseline_rejects_wrong_dataset_before_replay() {
    // Baseline that points at a real run, but a different dataset, must
    // fail upfront — never persist the new run before learning the diff
    // request is malformed.
    let app = build_test_app().await;
    let other_baseline = EvalRun {
        id: "WRONG-DS".into(),
        dataset_id: "different-dataset".into(),
        dataset_revision: 0,
        execution_mode: EvalRunExecutionMode::Scripted,
        items: vec![],
        started_at_secs: 1_700_000_000,
        ended_at_secs: 1_700_000_001,
    };
    app.eval_run_store.write(&other_baseline).unwrap();

    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-MISMATCH",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-MISMATCH",
            "baseline_run_id": "WRONG-DS",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("across datasets"),
        "body: {body}"
    );
    // Pre-existing baseline is the only run in the store.
    let runs = app.eval_run_store.list(&Default::default()).unwrap();
    assert_eq!(runs.len(), 1);
    assert_eq!(runs[0].id, "WRONG-DS");
}

#[tokio::test]
async fn start_eval_run_baseline_rejects_execution_mode_mismatch_before_replay() {
    // Scripted and Live runs have different semantics even when they
    // point at the same dataset revision: scripted measures replay
    // determinism; Live measures real provider/agent behaviour. Diffing
    // them would be a misleading apples-to-oranges regression gate.
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-MODE-MISMATCH",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let live_baseline = EvalRun {
        id: "LIVE-BASE".into(),
        dataset_id: "DS-MODE-MISMATCH".into(),
        dataset_revision: 0,
        execution_mode: EvalRunExecutionMode::Live,
        items: vec![],
        started_at_secs: 1_700_000_000,
        ended_at_secs: 1_700_000_001,
    };
    app.eval_run_store.write(&live_baseline).unwrap();

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-MODE-MISMATCH",
            "mode": "scripted",
            "baseline_run_id": "LIVE-BASE",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("execution modes"),
        "body: {body}"
    );

    let runs = app.eval_run_store.list(&Default::default()).unwrap();
    assert_eq!(runs.len(), 1);
    assert_eq!(runs[0].id, "LIVE-BASE");
    assert_eq!(runs[0].execution_mode, EvalRunExecutionMode::Live);
}

#[tokio::test]
async fn start_eval_run_baseline_with_duplicate_item_keys_rejected_before_replay() {
    // Regression: a baseline whose items collide on
    // (fixture_id, cell, sample_index) used to slip past the preflight
    // and only fail inside `compute_diff_from_baseline` — i.e. AFTER
    // live replay had burned provider tokens and the new run had been
    // persisted to the store. `load_and_validate_baseline` now runs the
    // duplicate-key check up front so the request fails fast and the
    // store stays untouched.
    let app = build_test_app().await;

    // Register a dataset (dataset_revision=0) the baseline can pair with.
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-DUP-BASE",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    // Hand-craft a baseline with two items sharing the same key. The
    // store-write paths now reject duplicate keys (see
    // `file_store_rejects_duplicate_item_keys`) so we have to drop
    // the JSON file in by hand to simulate a pre-existing corrupt
    // on-disk record — exactly the case the preflight guard exists for.
    let dup_baseline = EvalRun {
        id: "DUP-BASE".into(),
        dataset_id: "DS-DUP-BASE".into(),
        dataset_revision: 0,
        execution_mode: EvalRunExecutionMode::Scripted,
        items: vec![item("alpha", true, "first"), item("alpha", true, "second")],
        started_at_secs: 1_700_000_000,
        ended_at_secs: 1_700_000_001,
    };
    seed_corrupt_eval_run(&app.eval_run_root, &dup_baseline);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-DUP-BASE",
            "baseline_run_id": "DUP-BASE",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("duplicate eval-run item key"),
        "body: {body}"
    );
    // No valid run was persisted before the diff bailed. The
    // pre-existing duplicate-key baseline is still on disk, but
    // FileEvalRunStore::list deliberately skips historical dirty runs
    // so list endpoints don't expose invalid eval data.
    let runs = app.eval_run_store.list(&Default::default()).unwrap();
    assert!(runs.is_empty());
    assert!(matches!(
        app.eval_run_store.read("DUP-BASE").unwrap_err(),
        awaken_eval::EvalRunStoreError::DuplicateItemKeys(_, _)
    ));
}

#[tokio::test]
async fn start_eval_run_baseline_rejects_sample_count_mismatch_before_replay() {
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-SAMPLE-MISMATCH",
            "spec": { "fixtures": [sample_fixture("alpha")] }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let mut one_sample_baseline = EvalRun {
        id: "BASE-SAMPLE-1".into(),
        dataset_id: "DS-SAMPLE-MISMATCH".into(),
        dataset_revision: 0,
        execution_mode: EvalRunExecutionMode::Live,
        items: vec![item("alpha", true, "baseline")],
        started_at_secs: 1_700_000_000,
        ended_at_secs: 1_700_000_001,
    };
    one_sample_baseline.items[0].cell = Some(MatrixCell {
        model_id: Some("missing-model".into()),
    });
    app.eval_run_store.write(&one_sample_baseline).unwrap();

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-SAMPLE-MISMATCH",
            "mode": "live",
            "models": ["missing-model"],
            "samples": 2,
            "baseline_run_id": "BASE-SAMPLE-1"
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "body: {body}");
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("different sample counts"),
        "body: {body}"
    );
    let runs = app.eval_run_store.list(&Default::default()).unwrap();
    assert_eq!(runs.len(), 1);
    assert_eq!(runs[0].id, "BASE-SAMPLE-1");
}

// ── Online eval (POST /v1/eval/online) — validation paths ────────────────
//
// The happy path (cell execution against a real provider) is unit-tested
// in awaken-eval's runtime_replayer Live mode; the integration tests
// here cover the server-side validation and registry-lookup branches
// that don't require a live LLM.

#[tokio::test]
async fn online_eval_400s_on_empty_models() {
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({ "user_input": "test", "models": [] })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("models"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_400s_on_too_many_models() {
    // MAX_CELLS_PER_SYNC_ONLINE = 10; 11 must be rejected up-front
    // before any provider lookup or token spend.
    let app = build_test_app().await;
    let models: Vec<String> = (0..11).map(|i| format!("m{i}")).collect();
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({ "user_input": "test", "models": models })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("exceed sync online cap"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_404s_on_unknown_model() {
    // No model bindings registered in this TestApp's config_store —
    // the resolver must surface a NotFound with the missing id.
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({ "user_input": "test", "models": ["missing-model"] })),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("missing-model"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_route_absent_without_eval_run_store() {
    // Eval routes are mounted only when the eval module is wired. This keeps
    // absent optional modules as 404 route absence instead of handler-local
    // service-unavailable fallbacks.
    let app = build_test_app_without_run_store().await;
    let (status, body) = request(
        &app,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "test",
            "models": ["missing-model"],
            "persist": true,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND, "body: {body}");
}

#[tokio::test]
async fn online_eval_400s_on_zero_walltime() {
    // max_walltime_secs=0 would time out every cell immediately — the
    // request body accepts it but the handler must reject up front, not
    // race the timeout against the first scheduled task.
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "test",
            "models": ["missing-model"],
            "max_walltime_secs": 0,
            "persist": false,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("max_walltime_secs"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_400s_on_zero_samples() {
    // `samples: 0` would silently coerce to 1 under `unwrap_or(1).max(1)`
    // — the explicit Some(0) guard rejects it instead so the operator
    // notices the typo. Mirrors /v1/eval/runs same-named guard.
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "test",
            "models": ["missing-model"],
            "samples": 0,
            "persist": false,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("samples"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_404s_on_unknown_agent_id() {
    // `agent_id` resolution runs BEFORE per-cell model resolution so a
    // typo'd agent surfaces a 404 immediately, with the missing id in
    // the body — operators don't get an opaque 500 after token spend.
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "test",
            "models": ["missing-model"],
            "agent_id": "missing-agent",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("missing-agent"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_404s_on_unknown_agent_id() {
    // Same wiring on the dataset run path — agent lookup runs before
    // model resolution so a typo'd agent fails before the matrix even
    // starts.
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-AGT", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-AGT",
            "models": ["missing-model"],
            "agent_id": "missing-agent",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("missing-agent"),
        "body: {body}"
    );
}

// ── Flakiness sampling (samples=N per cell) — validation paths ───────────

#[tokio::test]
async fn start_eval_run_400s_when_samples_above_cap() {
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-S", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-S",
            "models": ["m1"],
            "samples": 50,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("samples=50"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_when_samples_without_models() {
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-S2", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-S2",
            "samples": 3,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("deterministic"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_on_duplicate_models() {
    // Duplicate model ids would spawn the same matrix cell twice and
    // generate duplicate (fixture_id, cell, sample_index) keys that
    // diff_eval_items would silently collapse. Reject at the entry point.
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-DUPM", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-DUPM",
            "models": ["m1", "m1"],
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("duplicate model"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_400s_on_duplicate_models() {
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "p",
            "models": ["m1", "m1"],
            "persist": false,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("duplicate model"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_when_scripted_with_agent_id() {
    // agent_id only makes sense in Live (matrix) mode — scripted runs
    // use the fixture's provider_script + a fixed stub agent. Rather
    // than silently ignore agent_id on a scripted request, reject it
    // so the operator isn't misled.
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-SAID", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-SAID",
            "agent_id": "some-agent",
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("agent_id requires mode=\"live\""),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_when_live_mode_omits_models() {
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-LIVE-NOMODELS", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({ "dataset_id": "DS-LIVE-NOMODELS", "mode": "live" })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("mode=\"live\" requires"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_when_scripted_mode_has_models() {
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-SCRIPTED-MODELS", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-SCRIPTED-MODELS",
            "mode": "scripted",
            "models": ["m1"],
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("only valid with mode=\"live\""),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_when_models_supplied_but_empty() {
    // `models: []` would otherwise pass `body.models.is_some()`, expand
    // into a 1-cell default with `model_id: None`, and panic inside
    // `run_matrix_cells` on the "matrix expansion always sets model_id"
    // expect. Reject the empty array up front.
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-EM", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({ "dataset_id": "DS-EM", "models": [] })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("non-empty"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_when_samples_blow_total_units() {
    // 25 fixtures × 2 models × 3 samples = 150 > MAX_CELLS_PER_SYNC_RUN (100).
    let app = build_test_app().await;
    let fixtures: Vec<_> = (0..25).map(|i| sample_fixture(&format!("f{i}"))).collect();
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-S3", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-S3",
            "models": ["m1", "m2"],
            "samples": 3,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("150 units"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_400s_on_samples_above_cap() {
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({ "user_input": "test", "models": ["m"], "samples": 50 })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("samples=50"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_400s_when_total_units_blow_cap() {
    // 4 models × 3 samples = 12 > MAX_CELLS_PER_SYNC_ONLINE (10).
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "test",
            "models": ["m1", "m2", "m3", "m4"],
            "samples": 3,
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("12 units"),
        "body: {body}"
    );
}

// ── LLM-as-judge — validation paths ──────────────────────────────────────

#[tokio::test]
async fn start_eval_run_400s_when_judge_without_models() {
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-J", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-J",
            "judge": { "model_id": "some-judge" },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("judge"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_when_min_judge_score_has_no_live_judge() {
    let app = build_test_app().await;
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-JUDGE-REQ",
            "spec": {
                "fixtures": [{
                    "id": "needs-judge",
                    "user_input": "grade this qualitatively",
                    "provider_script": [
                        {"kind": "chat_response", "content": "ok"}
                    ],
                    "expect": { "min_judge_score": 0.7 }
                }]
            }
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({ "dataset_id": "DS-JUDGE-REQ" })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("mode=\"live\""),
        "body: {body}"
    );

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-JUDGE-REQ",
            "mode": "live",
            "models": ["missing-model"],
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("provide `judge`"),
        "body: {body}"
    );

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-JUDGE-REQ",
            "mode": "live",
            "models": ["missing-model"],
            "judge": { "model_id": "missing-judge" },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("judge.rubric"),
        "body: {body}"
    );

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-JUDGE-REQ",
            "mode": "live",
            "models": ["missing-model"],
            "judge": { "model_id": "missing-judge", "rubric": "   " },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("judge.rubric"),
        "body: {body}"
    );
}

#[tokio::test]
async fn start_eval_run_400s_on_historical_invalid_min_judge_score() {
    let app = build_test_app().await;
    let mut fixture = sample_fixture("bad-threshold");
    fixture.expect.min_judge_score = Some(-0.2);
    seed_dataset_record(
        &app,
        "DS-CORRUPT-JUDGE-THRESHOLD",
        DatasetSpec {
            description: String::new(),
            fixtures: vec![fixture],
        },
    )
    .await;

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-CORRUPT-JUDGE-THRESHOLD",
            "mode": "live",
            "models": ["missing-model"],
            "judge": { "model_id": "missing-judge", "rubric": "grade correctness" },
        })),
    )
    .await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
    let err = body["error"].as_str().unwrap_or("");
    assert!(err.contains("min_judge_score"), "body: {body}");
    assert!(err.contains("[0.0, 1.0]"), "body: {body}");
}

#[tokio::test]
async fn start_eval_run_404s_on_unknown_judge_model() {
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-J2", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-J2",
            "models": ["replay-model"],
            "judge": { "model_id": "missing-judge" },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("missing-judge"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_400s_when_min_judge_score_has_no_judge() {
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "test",
            "models": ["missing-model"],
            "persist": false,
            "expectations": { "min_judge_score": 0.8 },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("provide `judge`"),
        "body: {body}"
    );

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "test",
            "models": ["missing-model"],
            "persist": false,
            "expectations": { "min_judge_score": 0.8 },
            "judge": { "model_id": "missing-judge" },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("judge.rubric"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_400s_on_invalid_min_judge_score() {
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "test",
            "models": ["missing-model"],
            "persist": false,
            "expectations": { "min_judge_score": 1.2 },
            "judge": { "model_id": "missing-judge", "rubric": "grade correctness" },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    let err = body["error"].as_str().unwrap_or("");
    assert!(err.contains("min_judge_score"), "body: {body}");
    assert!(err.contains("[0.0, 1.0]"), "body: {body}");
}

#[tokio::test]
async fn online_eval_404s_on_unknown_judge_model() {
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "test",
            "models": ["m"],
            "judge": { "model_id": "missing-judge" },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    let err = body["error"].as_str().unwrap_or("");
    assert!(
        err.contains("missing-judge") || err.contains("m"),
        "body: {body}"
    );
}

// ── Import from prod traces (POST /v1/eval/datasets/:id/import-traces) ──

#[tokio::test]
async fn import_traces_appends_curatable_traces_and_skips_existing() {
    let app = build_test_app().await;
    // Seed two traces with content capture + write indices so list()
    // returns them.
    use awaken_ext_observability::trace_store::RunSummary;
    use std::time::{Duration, UNIX_EPOCH};
    for (id, started) in [
        ("01HXIMP0000000000000000001", 1_700_000_100),
        ("01HXIMP0000000000000000002", 1_700_000_200),
    ] {
        app.trace_store
            .append(
                id,
                &MetricsEvent::Inference(captured_inference_span(id, "ok", true)),
            )
            .unwrap();
        let summary = RunSummary {
            run_id: id.into(),
            agent_id: "default".into(),
            started_at: UNIX_EPOCH + Duration::from_secs(started),
            ended_at: None,
            prompt_ids: vec![],
            experiment_id: None,
            variant_name: None,
            final_status: None,
            judge_score: None,
        };
        app.trace_store.write_index_for_run(id, &summary).unwrap();
    }

    // Empty dataset to receive imported fixtures.
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-IMP", "spec": {} })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    let rev = body["meta"]["revision"].as_u64().unwrap();

    // First import — two new fixtures land.
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-IMP/import-traces",
        Some(json!({
            "expected_revision": rev,
            "expected": { "final_answer_contains": ["ok"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    assert_eq!(body["imported_count"], 2);
    assert_eq!(body["skipped_count"], 0);
    let new_rev = body["dataset_revision"].as_u64().unwrap();
    let (_, dataset) = request(&app.router, "GET", "/v1/eval/datasets/DS-IMP", None).await;
    let fixtures = dataset["spec"]["fixtures"].as_array().unwrap();
    assert_eq!(fixtures.len(), 2);
    assert_eq!(fixtures[0]["expect"]["final_answer_contains"][0], "ok");

    let removed = app
        .trace_store
        .prune(
            UNIX_EPOCH + Duration::from_secs(4_000_000_000),
            &std::collections::HashSet::new(),
        )
        .unwrap();
    assert_eq!(removed, 0, "imported source traces must be pinned");

    // Second import with same traces — all skipped (no clobber), no
    // revision bump.
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-IMP/import-traces",
        Some(json!({
            "expected_revision": new_rev,
            "expected": { "final_answer_contains": ["ok"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["imported_count"], 0);
    assert_eq!(body["skipped_count"], 2);
    assert_eq!(body["dataset_revision"], new_rev);
}

#[tokio::test]
async fn import_traces_imports_live_only_fixture_when_provider_script_is_unsupported() {
    let app = build_test_app().await;
    use awaken_ext_observability::trace_store::RunSummary;
    use std::time::{Duration, UNIX_EPOCH};

    let id = "01HXIMP0000000000000000003";
    app.trace_store
        .append(
            id,
            &MetricsEvent::Inference(unsupported_provider_script_span(id)),
        )
        .unwrap();
    app.trace_store
        .write_index_for_run(
            id,
            &RunSummary {
                run_id: id.into(),
                agent_id: "default".into(),
                started_at: UNIX_EPOCH + Duration::from_secs(1_700_000_250),
                ended_at: None,
                prompt_ids: vec![],
                experiment_id: None,
                variant_name: None,
                final_status: None,
                judge_score: None,
            },
        )
        .unwrap();

    let (_, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-IMP-LIVE", "spec": {} })),
    )
    .await;
    let rev = body["meta"]["revision"].as_u64().unwrap();

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-IMP-LIVE/import-traces",
        Some(json!({
            "expected_revision": rev,
            "expected": { "final_answer_contains": ["answer"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    assert_eq!(body["imported_count"], 1);

    let (_, dataset) = request(&app.router, "GET", "/v1/eval/datasets/DS-IMP-LIVE", None).await;
    let fixture = &dataset["spec"]["fixtures"][0];
    assert_eq!(fixture["user_input"], "auto prompt");
    assert!(fixture["provider_script_error"].is_string());
    assert!(fixture["provider_script"].is_null());
}

#[tokio::test]
async fn import_traces_409s_on_stale_revision() {
    let app = build_test_app().await;
    let (_, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-IMP2", "spec": {} })),
    )
    .await;
    let rev = body["meta"]["revision"].as_u64().unwrap();
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-IMP2/import-traces",
        Some(json!({
            "expected_revision": rev + 99,
            "expected": { "final_answer_contains": ["ok"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CONFLICT);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("revision conflict"),
        "body: {body}"
    );
}

#[tokio::test]
async fn import_traces_cas_failure_does_not_pin_trace() {
    let app =
        build_test_app_with_config_store(Arc::new(CasConflictConfigStore::new("DS-IMP-CAS"))).await;
    let run_id = "01HXIMP0000000000000000CAS";
    seed_indexed_trace(
        app.trace_store.as_ref(),
        run_id,
        "the answer is 42",
        true,
        1_700_000_400,
    );
    let (_, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-IMP-CAS", "spec": {} })),
    )
    .await;
    let rev = body["meta"]["revision"].as_u64().unwrap();

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-IMP-CAS/import-traces",
        Some(json!({
            "expected_revision": rev,
            "expected": { "final_answer_contains": ["42"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CONFLICT);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("revision conflict"),
        "body: {body}"
    );
    assert_eq!(
        prune_all_unreferenced_traces(app.trace_store.as_ref()),
        1,
        "failed dataset CAS must not create trace retention references"
    );
}

#[tokio::test]
async fn import_traces_400s_when_trace_lacks_user_and_skip_disabled() {
    let app = build_test_app().await;
    use awaken_ext_observability::trace_store::RunSummary;
    use std::time::{Duration, UNIX_EPOCH};
    let id = "01HXIMP0000000000000000099";
    app.trace_store
        .append(
            id,
            &MetricsEvent::Inference(captured_inference_span(id, "ok", false)),
        )
        .unwrap();
    let summary = RunSummary {
        run_id: id.into(),
        agent_id: "default".into(),
        started_at: UNIX_EPOCH + Duration::from_secs(1_700_000_300),
        ended_at: None,
        prompt_ids: vec![],
        experiment_id: None,
        variant_name: None,
        final_status: None,
        judge_score: None,
    };
    app.trace_store.write_index_for_run(id, &summary).unwrap();

    let (_, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-IMP3", "spec": {} })),
    )
    .await;
    let rev = body["meta"]["revision"].as_u64().unwrap();

    // Default (skip_uncuratable=false) surfaces the missing user_input as 400.
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-IMP3/import-traces",
        Some(json!({
            "expected_revision": rev,
            "expected": { "final_answer_contains": ["ok"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("request_messages"),
        "body: {body}"
    );

    // With skip flag set, the same call returns 200 / imported=0.
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-IMP3/import-traces",
        Some(json!({
            "expected_revision": rev,
            "skip_uncuratable": true,
            "expected": { "final_answer_contains": ["ok"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["imported_count"], 0);
    assert_eq!(body["skipped_count"], 1);
}

// ── pass@k / pass^k aggregation (?aggregate=samples) ────────────────────

#[tokio::test]
async fn get_run_with_aggregate_samples_returns_pass_at_k_rollup() {
    let app = build_test_app().await;
    // 3 items for the same (fixture, cell) — 2 pass + 1 fail.
    let mut run = baseline_run("AGG-R");
    run.execution_mode = EvalRunExecutionMode::Live;
    run.items.clear();
    for (i, passed) in [(0u32, true), (1u32, false), (2u32, true)] {
        let mut report = item("alpha", passed, "x").report;
        report.passed = passed;
        run.items.push(EvalRunItem {
            fixture_id: "alpha".into(),
            cell: Some(awaken_eval::MatrixCell {
                model_id: Some("m1".into()),
            }),
            report,
            trace_run_id: None,
            sample_index: Some(i),
        });
    }
    app.eval_run_store.write(&run).unwrap();
    let (status, body) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/AGG-R?aggregate=samples",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let aggs = body["aggregates"].as_array().unwrap();
    assert_eq!(aggs.len(), 1);
    let g = &aggs[0];
    assert_eq!(g["samples"], 3);
    assert_eq!(g["passed"], 2);
    assert_eq!(g["pass_at_k"], true);
    assert_eq!(g["pass_pow_k"], false);
}

#[tokio::test]
async fn get_run_default_omits_aggregates() {
    let app = build_test_app().await;
    let run = baseline_run("AGG-R2");
    app.eval_run_store.write(&run).unwrap();
    let (status, body) = request(&app.router, "GET", "/v1/eval/runs/AGG-R2", None).await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.get("aggregates").is_none(),
        "default GET must not include aggregates field"
    );
}

#[tokio::test]
async fn get_run_rejects_unknown_aggregate_value() {
    // Unknown `?aggregate=` value is rejected by axum's Query
    // deserializer (the field is a typed enum, not a freeform string),
    // so the response is 400 with the framework's plain-text error
    // body — we just assert the status here.
    let app = build_test_app().await;
    let run = baseline_run("AGG-R3");
    app.eval_run_store.write(&run).unwrap();
    let (status, _) = request(
        &app.router,
        "GET",
        "/v1/eval/runs/AGG-R3?aggregate=tokens",
        None,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

// ── Dialogue importer (POST /v1/eval/datasets/:id/import-dialogue) ──────

#[tokio::test]
async fn import_dialogue_stitches_runs_into_multiturn_fixture() {
    let app = build_test_app().await;
    // Seed two captured runs to act as the two dialogue turns.
    for (id, text) in [
        ("01HXDLG0000000000000000001", "first answer"),
        ("01HXDLG0000000000000000002", "second answer"),
    ] {
        app.trace_store
            .append(
                id,
                &MetricsEvent::Inference(captured_inference_span(id, text, true)),
            )
            .unwrap();
    }
    // Empty dataset to receive the stitched dialogue.
    let (_, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-DLG", "spec": {} })),
    )
    .await;
    let rev = body["meta"]["revision"].as_u64().unwrap();

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-DLG/import-dialogue",
        Some(json!({
            "expected_revision": rev,
            "run_ids": [
                "01HXDLG0000000000000000001",
                "01HXDLG0000000000000000002",
            ],
            "fixture_id": "two-turn-dialogue",
            "expected": { "final_answer_contains": ["second"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    assert_eq!(body["fixture_id"], "two-turn-dialogue");

    // Verify the stitched fixture has 1 turn 0 + 1 continued turn.
    let (_, body) = request(&app.router, "GET", "/v1/eval/datasets/DS-DLG", None).await;
    let fx = &body["spec"]["fixtures"][0];
    assert_eq!(fx["id"], "two-turn-dialogue");
    assert_eq!(fx["user_input"], "auto prompt");
    let continued = fx["continued_turns"].as_array().unwrap();
    assert_eq!(continued.len(), 1, "second run becomes one continued turn");
    assert_eq!(continued[0]["user_input"], "auto prompt");
    assert_eq!(fx["expect"]["final_answer_contains"][0], "second");

    let removed = app
        .trace_store
        .prune(
            UNIX_EPOCH + std::time::Duration::from_secs(4_000_000_000),
            &std::collections::HashSet::new(),
        )
        .unwrap();
    assert_eq!(removed, 0, "dialogue source traces must be pinned");
}

#[tokio::test]
async fn import_dialogue_cas_failure_does_not_pin_trace() {
    let app =
        build_test_app_with_config_store(Arc::new(CasConflictConfigStore::new("DS-DLG-CAS"))).await;
    let run_id = "01HXDLG0000000000000000CAS";
    app.trace_store
        .append(
            run_id,
            &MetricsEvent::Inference(captured_inference_span(run_id, "answer", true)),
        )
        .unwrap();
    let (_, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-DLG-CAS", "spec": {} })),
    )
    .await;
    let rev = body["meta"]["revision"].as_u64().unwrap();

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-DLG-CAS/import-dialogue",
        Some(json!({
            "expected_revision": rev,
            "run_ids": [run_id],
            "fixture_id": "dialogue",
            "expected": { "final_answer_contains": ["answer"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CONFLICT);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("revision conflict"),
        "body: {body}"
    );
    assert_eq!(
        prune_all_unreferenced_traces(app.trace_store.as_ref()),
        1,
        "failed dataset CAS must not create trace retention references"
    );
}

#[tokio::test]
async fn import_dialogue_400s_on_thread_id_mismatch() {
    // Two runs from different conversations would otherwise stitch into
    // a "dialogue" whose continuation is unrelated to the prior turn —
    // the resulting fixture would silently misrepresent the eval task.
    let app = build_test_app().await;
    for (id, thread) in [
        ("01HXDLG0000000000000000010", "thread-A"),
        ("01HXDLG0000000000000000011", "thread-B"),
    ] {
        let mut span = captured_inference_span(id, "answer", true);
        span.context.thread_id = thread.into();
        app.trace_store
            .append(id, &MetricsEvent::Inference(span))
            .unwrap();
    }
    let (_, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-DLG-MIX", "spec": {} })),
    )
    .await;
    let rev = body["meta"]["revision"].as_u64().unwrap();
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-DLG-MIX/import-dialogue",
        Some(json!({
            "expected_revision": rev,
            "run_ids": [
                "01HXDLG0000000000000000010",
                "01HXDLG0000000000000000011",
            ],
            "fixture_id": "mixed-threads",
            "expected": { "final_answer_contains": ["answer"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("thread_id="),
        "body: {body}"
    );
}

#[tokio::test]
async fn import_dialogue_400s_on_empty_run_ids() {
    let app = build_test_app().await;
    let (_, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-DLG2", "spec": {} })),
    )
    .await;
    let rev = body["meta"]["revision"].as_u64().unwrap();
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-DLG2/import-dialogue",
        Some(json!({
            "expected_revision": rev,
            "run_ids": [],
            "expected": { "final_answer_contains": ["answer"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"].as_str().unwrap_or("").contains("non-empty"),
        "body: {body}"
    );
}

#[tokio::test]
async fn import_dialogue_409s_on_duplicate_fixture_id() {
    let app = build_test_app().await;
    let run_id = "01HXDLG0000000000000000099";
    app.trace_store
        .append(
            run_id,
            &MetricsEvent::Inference(captured_inference_span(run_id, "hi", true)),
        )
        .unwrap();
    // Dataset that already has a fixture with the would-be name.
    let (_, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({
            "id": "DS-DLG3",
            "spec": { "fixtures": [sample_fixture("already-here")] }
        })),
    )
    .await;
    let rev = body["meta"]["revision"].as_u64().unwrap();

    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets/DS-DLG3/import-dialogue",
        Some(json!({
            "expected_revision": rev,
            "run_ids": [run_id],
            "fixture_id": "already-here",
            "expected": { "final_answer_contains": ["hi"] },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CONFLICT);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("already-here"),
        "body: {body}"
    );
}

// ── Judge revise loop validation (revise_max_retries cap) ───────────────

#[tokio::test]
async fn start_eval_run_400s_when_revise_max_retries_above_cap() {
    let app = build_test_app().await;
    let fixtures = vec![sample_fixture("f1")];
    let (status, _) = request(
        &app.router,
        "POST",
        "/v1/eval/datasets",
        Some(json!({ "id": "DS-RV", "spec": { "fixtures": fixtures } })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/runs",
        Some(json!({
            "dataset_id": "DS-RV",
            "models": ["m1"],
            "judge": {
                "model_id": "judge-model",
                "revise_max_retries": 99,
            },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("revise_max_retries=99"),
        "body: {body}"
    );
}

#[tokio::test]
async fn online_eval_400s_when_revise_max_retries_above_cap() {
    let app = build_test_app().await;
    let (status, body) = request(
        &app.router,
        "POST",
        "/v1/eval/online",
        Some(json!({
            "user_input": "hi",
            "models": ["m"],
            "judge": {
                "model_id": "judge-model",
                "revise_max_retries": 50,
            },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body["error"]
            .as_str()
            .unwrap_or("")
            .contains("revise_max_retries=50"),
        "body: {body}"
    );
}

// ── Auth ──────────────────────────────────────────────────────────────────

#[tokio::test]
async fn eval_routes_require_admin_bearer() {
    let app = build_test_app().await;
    // Same `request` helper but skip the Authorization header.
    let req = Request::builder()
        .method("GET")
        .uri("/v1/eval/datasets")
        .body(Body::empty())
        .unwrap();
    let resp = app.router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

// ── Helpers for the diff test ─────────────────────────────────────────────

fn baseline_run(id: &str) -> EvalRun {
    EvalRun {
        id: id.into(),
        dataset_id: "DS-DIFF".into(),
        dataset_revision: 1,
        execution_mode: EvalRunExecutionMode::Scripted,
        items: vec![item("alpha", true, "good answer")],
        started_at_secs: 1_700_000_000,
        ended_at_secs: 1_700_000_001,
    }
}

fn new_run_with_drift(id: &str) -> EvalRun {
    // Same fixture id, different final_text → drift (both still pass).
    EvalRun {
        id: id.into(),
        dataset_id: "DS-DIFF".into(),
        dataset_revision: 1,
        execution_mode: EvalRunExecutionMode::Scripted,
        items: vec![item("alpha", true, "different answer")],
        started_at_secs: 1_700_000_100,
        ended_at_secs: 1_700_000_101,
    }
}

fn item(fixture_id: &str, passed: bool, final_text: &str) -> EvalRunItem {
    use awaken_eval::ReplayReport;
    EvalRunItem {
        fixture_id: fixture_id.into(),
        cell: None,
        report: ReplayReport {
            fixture_id: fixture_id.into(),
            passed,
            failures: vec![],
            final_text: final_text.into(),
            inference_count: 1,
            tool_count: 0,
            tool_failures: 0,
            total_input_tokens: 1,
            total_output_tokens: 1,
            total_tokens: 2,
            session_duration_ms: 1,
            elapsed_ms: 0,
            tool_calls_by_agent: vec![],
            error_type: None,
            inference_error_count: 0,
            runtime_failure: None,
            revision_count: 0,
            judge_score: None,
            judge_reasoning: None,
            cost_usd: None,
        },
        trace_run_id: None,
        sample_index: None,
    }
}