algocline 0.30.0

LLM amplification engine — MCP server with Lua scripting
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
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
//! E2E tests for the algocline MCP server.
//!
//! Uses rmcp client to spawn the `alc` binary as a child process,
//! communicate via stdio MCP protocol, and validate responses with
//! insta snapshots.

use std::borrow::Cow;
use std::io::Write;

use rmcp::{
    model::{
        ArgumentInfo, CallToolRequestParams, CompleteRequestParams, ReadResourceRequestParams,
        Reference, ResourceReference,
    },
    transport::TokioChildProcess,
    ServiceExt,
};
use serde_json::{json, Map, Value};

use algocline_app::PRESET_CATALOG_VERSION;

// ─── Helpers ─────────────────────────────────────────────────────

/// Build `CallToolRequestParams` from a tool name and a JSON value.
fn call_params(name: &str, args: Value) -> CallToolRequestParams {
    let arguments = match args {
        Value::Object(map) => Some(map),
        _ => None,
    };
    let mut p = CallToolRequestParams::default();
    p.name = Cow::Owned(name.to_string());
    p.arguments = arguments;
    p
}

/// Build `CallToolRequestParams` with no arguments.
fn call_params_empty(name: &str) -> CallToolRequestParams {
    let mut p = CallToolRequestParams::default();
    p.name = Cow::Owned(name.to_string());
    p.arguments = Some(Map::new());
    p
}

/// Connect to the `alc` binary as an MCP client.
async fn connect() -> rmcp::service::RunningService<rmcp::RoleClient, ()> {
    let bin = std::env::var("CARGO_BIN_EXE_alc")
        .unwrap_or_else(|_| format!("{}/target/debug/alc", env!("CARGO_MANIFEST_DIR")));
    let transport = TokioChildProcess::new(tokio::process::Command::new(bin))
        .expect("failed to spawn alc server");
    ().serve(transport)
        .await
        .expect("failed to initialize MCP session")
}

/// Extract the first text content from a CallToolResult.
fn extract_text(result: &rmcp::model::CallToolResult) -> &str {
    result
        .content
        .first()
        .and_then(|c| c.raw.as_text())
        .map(|t| t.text.as_str())
        .unwrap_or("")
}

/// Redact UUIDs (session IDs) from text.
fn redact_uuids(text: &str) -> String {
    let re = regex::Regex::new(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
        .expect("invalid regex");
    re.replace_all(text, "<UUID>").to_string()
}

/// Redact absolute paths from text (home directory portion).
fn redact_paths(text: &str) -> String {
    if let Some(home) = dirs::home_dir() {
        text.replace(home.to_str().unwrap_or(""), "<HOME>")
    } else {
        text.to_string()
    }
}

/// Apply all redactions.
fn redact(text: &str) -> String {
    redact_paths(&redact_uuids(text))
}

/// Connect with a specific ALC_HOME directory.
///
/// Also sets `ALC_PACKAGES_PATH` to `{alc_home}/packages` so that the server's
/// package search path is scoped to the tmp directory. Without this, `pkg_list`
/// would scan `~/.algocline/packages/` instead of the test fixture.
async fn connect_with_alc_home(
    alc_home: &std::path::Path,
) -> rmcp::service::RunningService<rmcp::RoleClient, ()> {
    let bin = std::env::var("CARGO_BIN_EXE_alc")
        .unwrap_or_else(|_| format!("{}/target/debug/alc", env!("CARGO_MANIFEST_DIR")));
    let packages_path = alc_home.join("packages");
    let mut cmd = tokio::process::Command::new(bin);
    cmd.env("ALC_HOME", alc_home)
        .env("ALC_PACKAGES_PATH", &packages_path);
    let transport = TokioChildProcess::new(cmd).expect("failed to spawn alc server");
    ().serve(transport)
        .await
        .expect("failed to initialize MCP session")
}

/// Read a resource by URI, returning the result.
async fn read_resource(
    client: &rmcp::service::RunningService<rmcp::RoleClient, ()>,
    uri: &str,
) -> Result<rmcp::model::ReadResourceResult, rmcp::service::ServiceError> {
    client
        .read_resource(ReadResourceRequestParams::new(uri.to_string()))
        .await
}

/// Extract text from a `ResourceContents` variant.
fn resource_text(contents: &rmcp::model::ResourceContents) -> (&str, &str) {
    match contents {
        rmcp::model::ResourceContents::TextResourceContents { uri, text, .. } => {
            (uri.as_str(), text.as_str())
        }
        rmcp::model::ResourceContents::BlobResourceContents { uri, .. } => {
            panic!("expected TextResourceContents, got BlobResourceContents for URI {uri}")
        }
    }
}

/// Call a tool, extract text, parse as JSON.
async fn call_json(
    client: &rmcp::service::RunningService<rmcp::RoleClient, ()>,
    name: &str,
    args: Value,
) -> Value {
    let result = client
        .call_tool(call_params(name, args))
        .await
        .expect("call_tool failed");
    let text = extract_text(&result);
    serde_json::from_str(text).unwrap_or_else(|e| panic!("JSON parse failed: {e}\nraw: {text}"))
}

// ─── Tests ───────────────────────────────────────────────────────

#[tokio::test]
async fn test_list_tools() {
    let client = connect().await;

    let tools = client
        .list_all_tools()
        .await
        .expect("list_all_tools failed");
    let mut names: Vec<&str> = tools.iter().map(|t| t.name.as_ref()).collect();
    names.sort();

    insta::assert_json_snapshot!("list_tools", names);

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_info() {
    let client = connect().await;

    let result = client
        .call_tool(call_params_empty("alc_info"))
        .await
        .expect("call_tool failed");
    let text = extract_text(&result);
    let redacted = redact(text);

    insta::assert_snapshot!("alc_info", redacted);

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_status_empty() {
    let client = connect().await;

    let result = client
        .call_tool(call_params_empty("alc_status"))
        .await
        .expect("call_tool failed");
    let text = extract_text(&result);

    insta::assert_snapshot!("alc_status_empty", text);

    client.cancel().await.expect("cancel failed");
}

// ─── alc_status pending_filter E2E ────────────────────────────
//
// Covers the MCP surface of the pending_filter parameter introduced
// in feat(status). Empty-registry paths exercise the resolve dispatch
// (preset / object / bad shape) without needing a paused session; the
// paused-session test hits the actual projection pipeline.

#[tokio::test]
async fn test_alc_status_preset_meta_empty_registry() {
    let client = connect().await;

    let resp = call_json(&client, "alc_status", json!({ "pending_filter": "meta" })).await;
    assert_eq!(resp["active_sessions"], 0);
    assert_eq!(resp["sessions"].as_array().unwrap().len(), 0);

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_status_preset_preview_and_full_empty_registry() {
    let client = connect().await;

    for preset in ["preview", "full"] {
        let resp = call_json(&client, "alc_status", json!({ "pending_filter": preset })).await;
        assert_eq!(
            resp["active_sessions"], 0,
            "preset '{preset}' should return empty-registry shape"
        );
    }

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_status_unknown_preset_errors() {
    let client = connect().await;

    let result = client
        .call_tool(call_params(
            "alc_status",
            json!({ "pending_filter": "bogus" }),
        ))
        .await
        .expect("call_tool failed");
    let text = extract_text(&result);

    assert!(
        text.contains("unknown pending_filter preset"),
        "expected typed error, got: {text}"
    );
    assert!(
        text.contains("bogus"),
        "error should echo the bad preset name, got: {text}"
    );

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_status_bad_shape_errors() {
    let client = connect().await;

    // bool is neither a preset string nor a filter object
    let result = client
        .call_tool(call_params("alc_status", json!({ "pending_filter": true })))
        .await
        .expect("call_tool failed");
    let text = extract_text(&result);

    assert!(
        text.contains("pending_filter must be a preset name"),
        "expected shape error, got: {text}"
    );
    assert!(
        text.contains("bool"),
        "error should name the bad type, got: {text}"
    );

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_status_custom_object_filter() {
    let client = connect().await;

    // Empty registry still exercises the object dispatch branch.
    let resp = call_json(
        &client,
        "alc_status",
        json!({
            "pending_filter": {
                "query_id": true,
                "prompt": { "mode": "preview", "chars": 50 }
            }
        }),
    )
    .await;
    assert_eq!(resp["active_sessions"], 0);

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_status_paused_session_projection() {
    let client = connect().await;

    // 1. Start a session that will pause on alc.llm()
    let resp = call_json(
        &client,
        "alc_run",
        json!({ "code": "return alc.llm('What is 2+2?')" }),
    )
    .await;
    assert_eq!(resp["status"], "needs_response");
    let session_id = resp["session_id"].as_str().expect("session_id").to_string();

    // 2. Query status with preset=meta and a specific session_id
    let resp = call_json(
        &client,
        "alc_status",
        json!({
            "session_id": session_id,
            "pending_filter": "meta",
        }),
    )
    .await;

    assert_eq!(resp["pending_queries"], 1, "should report 1 pending query");
    let pending = resp["pending"]
        .as_array()
        .expect("pending array should be emitted when filter is set");
    assert_eq!(pending.len(), 1);
    // meta preset: query_id + max_tokens only
    assert!(
        pending[0]["query_id"].is_string(),
        "query_id must be present"
    );
    assert!(
        pending[0]["max_tokens"].is_number(),
        "max_tokens must be present"
    );
    assert!(
        pending[0].get("prompt").is_none(),
        "meta preset must not project prompt"
    );
    assert!(
        pending[0].get("prompt_preview").is_none(),
        "meta preset must not project prompt_preview"
    );

    // 3. Preview preset should add prompt_preview field
    let resp = call_json(
        &client,
        "alc_status",
        json!({
            "session_id": session_id,
            "pending_filter": "preview",
        }),
    )
    .await;
    let pending = resp["pending"].as_array().expect("pending array");
    assert!(
        pending[0]["prompt_preview"].is_string(),
        "preview preset must project prompt_preview"
    );

    // 4. Clean up — resume the session so the process does not hold it
    let _ = call_json(
        &client,
        "alc_continue",
        json!({ "session_id": session_id, "response": "4" }),
    )
    .await;

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_run_pure_lua() {
    let client = connect().await;

    let result = client
        .call_tool(call_params("alc_run", json!({ "code": "return 1 + 2" })))
        .await
        .expect("call_tool failed");
    let text = extract_text(&result);
    // Parse the JSON response to check the result value
    let parsed: Value = serde_json::from_str(text).expect("response should be JSON");

    assert_eq!(parsed["status"], "completed");
    assert_eq!(parsed["result"], 3);

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_run_lua_error() {
    let client = connect().await;

    let result = client
        .call_tool(call_params(
            "alc_run",
            json!({ "code": "error('intentional test error')" }),
        ))
        .await
        .expect("call_tool failed");
    let text = extract_text(&result);

    // The error message should contain our intentional error
    assert!(
        text.contains("intentional test error"),
        "expected error message in response, got: {text}"
    );

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_continue_invalid_session() {
    let client = connect().await;

    let result = client
        .call_tool(call_params(
            "alc_continue",
            json!({
                "session_id": "00000000-0000-0000-0000-000000000000",
                "response": "test"
            }),
        ))
        .await
        .expect("call_tool failed");
    let text = extract_text(&result);

    // Should indicate the session was not found
    assert!(
        text.to_lowercase().contains("not found")
            || text.to_lowercase().contains("no session")
            || text.to_lowercase().contains("unknown"),
        "expected 'not found' error, got: {text}"
    );

    client.cancel().await.expect("cancel failed");
}

// ─── LLM round-trip tests ───────────────────────────────────────

#[tokio::test]
async fn test_alc_llm_single_roundtrip() {
    let client = connect().await;

    // 1. Run code that calls alc.llm()
    let resp = call_json(
        &client,
        "alc_run",
        json!({ "code": "return alc.llm('What is 2+2?')" }),
    )
    .await;
    assert_eq!(resp["status"], "needs_response");
    let session_id = resp["session_id"].as_str().expect("session_id missing");
    assert!(resp["prompt"].as_str().is_some(), "prompt missing");
    assert!(
        resp.get("query_id").is_some(),
        "query_id missing in response"
    );

    // 2. Continue with response (no explicit query_id — tests auto-resolve)
    let resp = call_json(
        &client,
        "alc_continue",
        json!({ "session_id": session_id, "response": "4" }),
    )
    .await;
    assert_eq!(resp["status"], "completed");
    assert_eq!(resp["result"], "4");

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_llm_batch_roundtrip() {
    let client = connect().await;

    // 1. Run code that calls alc.llm_batch()
    let code = r#"
        local results = alc.llm_batch({
            { prompt = "Say A" },
            { prompt = "Say B" },
        })
        return results
    "#;
    let resp = call_json(&client, "alc_run", json!({ "code": code })).await;
    assert_eq!(resp["status"], "needs_response");
    let session_id = resp["session_id"].as_str().expect("session_id missing");
    let queries = resp["queries"].as_array().expect("queries array missing");
    assert_eq!(queries.len(), 2);

    let q0_id = queries[0]["id"].as_str().expect("q-0 id missing");
    let q1_id = queries[1]["id"].as_str().expect("q-1 id missing");

    // 2. Feed responses via batch
    let resp = call_json(
        &client,
        "alc_continue",
        json!({
            "session_id": session_id,
            "responses": [
                { "query_id": q0_id, "response": "Alpha" },
                { "query_id": q1_id, "response": "Beta" },
            ]
        }),
    )
    .await;
    assert_eq!(resp["status"], "completed");
    let result = resp["result"].as_array().expect("result should be array");
    assert_eq!(result.len(), 2);
    assert_eq!(result[0], "Alpha");
    assert_eq!(result[1], "Beta");

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_cache_hit_miss() {
    let client = connect().await;

    // Code: call alc.cache twice with same prompt, return cache_info
    let code = r#"
        local r1 = alc.cache("cached prompt")
        local r2 = alc.cache("cached prompt")
        local info = alc.cache_info()
        return { r1 = r1, r2 = r2, info = info }
    "#;

    // 1. First call pauses (cache miss)
    let resp = call_json(&client, "alc_run", json!({ "code": code })).await;
    assert_eq!(resp["status"], "needs_response");
    let session_id = resp["session_id"].as_str().expect("session_id missing");

    // 2. Continue — cache miss resolved, second call hits cache
    let resp = call_json(
        &client,
        "alc_continue",
        json!({ "session_id": session_id, "response": "cached_value" }),
    )
    .await;
    assert_eq!(resp["status"], "completed");
    let result = &resp["result"];
    assert_eq!(result["r1"], "cached_value");
    assert_eq!(
        result["r2"], "cached_value",
        "cache hit should return same value"
    );
    assert_eq!(result["info"]["hits"], 1);
    assert_eq!(result["info"]["misses"], 1);
    assert_eq!(result["info"]["entries"], 1);

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_parallel_roundtrip() {
    let client = connect().await;

    // alc.parallel sends items as llm_batch
    let code = r#"
        local items = {"apple", "banana"}
        local results = alc.parallel(items, function(item, i)
            return "Describe " .. item
        end)
        return results
    "#;

    // 1. Pauses with batch queries
    let resp = call_json(&client, "alc_run", json!({ "code": code })).await;
    assert_eq!(resp["status"], "needs_response");
    let session_id = resp["session_id"].as_str().expect("session_id missing");
    let queries = resp["queries"].as_array().expect("queries missing");
    assert_eq!(queries.len(), 2);

    let q0_id = queries[0]["id"].as_str().expect("id missing");
    let q1_id = queries[1]["id"].as_str().expect("id missing");

    // 2. Feed batch
    let resp = call_json(
        &client,
        "alc_continue",
        json!({
            "session_id": session_id,
            "responses": [
                { "query_id": q0_id, "response": "A red fruit" },
                { "query_id": q1_id, "response": "A yellow fruit" },
            ]
        }),
    )
    .await;
    assert_eq!(resp["status"], "completed");
    let result = resp["result"].as_array().expect("result array");
    assert_eq!(result[0], "A red fruit");
    assert_eq!(result[1], "A yellow fruit");

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_fork_roundtrip() {
    let client = connect().await;

    // 1. Create temp packages and install them
    let tmp_dir = tempfile::tempdir().expect("failed to create tempdir");

    let pkg_a_dir = tmp_dir.path().join("e2e_fork_a");
    std::fs::create_dir_all(&pkg_a_dir).expect("mkdir");
    let mut f = std::fs::File::create(pkg_a_dir.join("init.lua")).expect("create init.lua");
    write!(
        f,
        r#"local M = {{}}
M.meta = {{ name = "e2e_fork_a", version = "0.1.0", description = "E2E fork A" }}
function M.run(ctx)
    return alc.llm("Fork A: " .. (ctx.task or ""))
end
return M"#
    )
    .expect("write init.lua");

    let pkg_b_dir = tmp_dir.path().join("e2e_fork_b");
    std::fs::create_dir_all(&pkg_b_dir).expect("mkdir");
    let mut f = std::fs::File::create(pkg_b_dir.join("init.lua")).expect("create init.lua");
    write!(
        f,
        r#"local M = {{}}
M.meta = {{ name = "e2e_fork_b", version = "0.1.0", description = "E2E fork B" }}
function M.run(ctx)
    return alc.llm("Fork B: " .. (ctx.task or ""))
end
return M"#
    )
    .expect("write init.lua");

    // Install via MCP
    call_json(
        &client,
        "alc_pkg_install",
        json!({ "url": pkg_a_dir.to_string_lossy() }),
    )
    .await;
    call_json(
        &client,
        "alc_pkg_install",
        json!({ "url": pkg_b_dir.to_string_lossy() }),
    )
    .await;

    // 2. Run alc.fork
    let code = r#"
        local results = alc.fork({"e2e_fork_a", "e2e_fork_b"}, ctx)
        return results
    "#;
    let resp = call_json(
        &client,
        "alc_run",
        json!({ "code": code, "ctx": { "task": "test" } }),
    )
    .await;
    assert_eq!(resp["status"], "needs_response");
    let session_id = resp["session_id"]
        .as_str()
        .expect("session_id missing")
        .to_string();

    // Fork yields one query at a time (or batched) — collect all
    // The multiplexer may batch queries from multiple child VMs
    let mut completed = false;
    let mut final_resp = resp;
    let mut iterations = 0;
    const MAX_ITERATIONS: usize = 20;
    while !completed {
        iterations += 1;
        assert!(
            iterations <= MAX_ITERATIONS,
            "fork test exceeded {MAX_ITERATIONS} iterations — possible infinite loop"
        );
        if final_resp["status"] == "needs_response" {
            let session = final_resp["session_id"]
                .as_str()
                .unwrap_or(&session_id)
                .to_string();

            if let Some(queries) = final_resp["queries"].as_array() {
                // Batch: respond to all queries
                let responses: Vec<Value> = queries
                    .iter()
                    .map(|q| {
                        let qid = q["id"].as_str().expect("query id");
                        let prompt = q["prompt"].as_str().unwrap_or("");
                        let answer = if prompt.contains("Fork A") {
                            "Answer A"
                        } else {
                            "Answer B"
                        };
                        json!({ "query_id": qid, "response": answer })
                    })
                    .collect();
                final_resp = call_json(
                    &client,
                    "alc_continue",
                    json!({ "session_id": session, "responses": responses }),
                )
                .await;
            } else {
                // Single query
                let prompt = final_resp["prompt"].as_str().unwrap_or("");
                let answer = if prompt.contains("Fork A") {
                    "Answer A"
                } else {
                    "Answer B"
                };
                final_resp = call_json(
                    &client,
                    "alc_continue",
                    json!({ "session_id": session, "response": answer }),
                )
                .await;
            }
        } else {
            completed = true;
        }
    }

    assert_eq!(final_resp["status"], "completed");
    let result = final_resp["result"]
        .as_array()
        .expect("result should be array");
    assert_eq!(result.len(), 2);

    // Verify both strategies returned results
    let strategy_a = &result[0];
    assert_eq!(strategy_a["strategy"], "e2e_fork_a");
    assert_eq!(strategy_a["ok"], true);
    assert_eq!(strategy_a["result"], "Answer A");

    let strategy_b = &result[1];
    assert_eq!(strategy_b["strategy"], "e2e_fork_b");
    assert_eq!(strategy_b["ok"], true);
    assert_eq!(strategy_b["result"], "Answer B");

    // 3. Cleanup packages (physical delete from cache — pkg_remove no longer does this)
    if let Some(home) = dirs::home_dir() {
        let pkg_cache = home.join(".algocline").join("packages");
        let _ = std::fs::remove_dir_all(pkg_cache.join("e2e_fork_a"));
        let _ = std::fs::remove_dir_all(pkg_cache.join("e2e_fork_b"));
    }

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_pkg_install_returns_types_path() {
    let client = connect().await;

    // Create a temporary package
    let tmp_dir = tempfile::tempdir().expect("tempdir");
    let pkg_dir = tmp_dir.path().join("e2e_types_test");
    std::fs::create_dir_all(&pkg_dir).expect("mkdir");
    std::fs::write(
        pkg_dir.join("init.lua"),
        r#"local M = {}
M.meta = { name = "e2e_types_test", version = "0.1.0" }
function M.run(ctx) return "ok" end
return M"#,
    )
    .expect("write init.lua");

    // Install and check response
    let resp = call_json(
        &client,
        "alc_pkg_install",
        json!({ "url": pkg_dir.to_string_lossy() }),
    )
    .await;

    assert_eq!(resp["installed"], json!(["e2e_types_test"]));
    assert!(
        resp["types_path"].is_string(),
        "types_path should be present in pkg_install response"
    );
    let types_path = resp["types_path"].as_str().unwrap();
    assert!(
        types_path.ends_with("types/alc.d.lua"),
        "types_path should end with types/alc.d.lua, got: {types_path}"
    );

    // Cleanup (physical delete from cache — pkg_remove no longer does this)
    if let Some(home) = dirs::home_dir() {
        let pkg_cache = home.join(".algocline").join("packages");
        let _ = std::fs::remove_dir_all(pkg_cache.join("e2e_types_test"));
    }
    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_pkg_install_returns_alc_shapes_types_path() {
    let client = connect().await;

    // Create a temporary package
    let tmp_dir = tempfile::tempdir().expect("tempdir");
    let pkg_dir = tmp_dir.path().join("e2e_alc_shapes_types_test");
    std::fs::create_dir_all(&pkg_dir).expect("mkdir");
    std::fs::write(
        pkg_dir.join("init.lua"),
        r#"local M = {}
M.meta = { name = "e2e_alc_shapes_types_test", version = "0.1.0" }
function M.run(ctx) return "ok" end
return M"#,
    )
    .expect("write init.lua");

    // Install and check response
    let resp = call_json(
        &client,
        "alc_pkg_install",
        json!({ "url": pkg_dir.to_string_lossy() }),
    )
    .await;

    assert_eq!(resp["installed"], json!(["e2e_alc_shapes_types_test"]));

    // alc_shapes_types_path is present when alc init has been run (types/alc_shapes.d.lua exists)
    if resp["alc_shapes_types_path"].is_string() {
        let alc_shapes_path = resp["alc_shapes_types_path"].as_str().unwrap();
        assert!(
            alc_shapes_path.ends_with("types/alc_shapes.d.lua"),
            "alc_shapes_types_path should end with types/alc_shapes.d.lua, got: {alc_shapes_path}"
        );
    }
    // alc_shapes_types_path is null when alc init has not distributed the file yet —
    // that is the expected behaviour (Option<String> → JSON null).

    // Regression guard: existing types_path field is unaffected
    if resp["types_path"].is_string() {
        let types_path = resp["types_path"].as_str().unwrap();
        assert!(
            types_path.ends_with("types/alc.d.lua"),
            "types_path should end with types/alc.d.lua, got: {types_path}"
        );
    }

    // Cleanup (physical delete from cache — pkg_remove no longer does this)
    if let Some(home) = dirs::home_dir() {
        let pkg_cache = home.join(".algocline").join("packages");
        let _ = std::fs::remove_dir_all(pkg_cache.join("e2e_alc_shapes_types_test"));
    }
    client.cancel().await.expect("cancel failed");
}

/// `alc_pkg_remove` with `scope = "global"` deletes the entry from the
/// global manifest `~/.algocline/installed.json` while leaving the cached
/// directory `~/.algocline/packages/{name}/` intact. Regression against
/// the "no tool path to clean up orphan `installed.json` entries" gap
/// that motivated the scope reintroduction (CHANGELOG).
#[tokio::test]
async fn test_pkg_remove_scope_global_cleans_manifest_not_files() {
    let client = connect().await;

    // Install a unique package so we don't collide with real user state.
    let tmp_dir = tempfile::tempdir().expect("tempdir");
    let pkg_name = "e2e_remove_global";
    let pkg_dir = tmp_dir.path().join(pkg_name);
    std::fs::create_dir_all(&pkg_dir).expect("mkdir");
    std::fs::write(
        pkg_dir.join("init.lua"),
        r#"local M = {}
M.meta = { name = "e2e_remove_global", version = "0.1.0" }
function M.run(ctx) return "ok" end
return M"#,
    )
    .expect("write init.lua");

    call_json(
        &client,
        "alc_pkg_install",
        json!({ "url": pkg_dir.to_string_lossy() }),
    )
    .await;

    let home = dirs::home_dir().expect("home");
    let manifest_path = home.join(".algocline").join("installed.json");
    let cache_dir = home.join(".algocline").join("packages").join(pkg_name);

    // Precondition: manifest has the entry, cache dir exists.
    let before: Value =
        serde_json::from_str(&std::fs::read_to_string(&manifest_path).expect("manifest read"))
            .expect("manifest JSON");
    assert!(
        before["packages"][pkg_name].is_object(),
        "precondition: manifest must contain '{pkg_name}' before remove"
    );
    assert!(cache_dir.exists(), "precondition: cache dir must exist");

    // scope=global removal.
    let resp = call_json(
        &client,
        "alc_pkg_remove",
        json!({ "name": pkg_name, "scope": "global" }),
    )
    .await;
    assert_eq!(resp["removed"], pkg_name);
    assert_eq!(resp["scope"], "global");

    // Postcondition: manifest no longer has the entry, cache dir still exists.
    let after: Value =
        serde_json::from_str(&std::fs::read_to_string(&manifest_path).expect("manifest read"))
            .expect("manifest JSON");
    assert!(
        after["packages"][pkg_name].is_null(),
        "manifest still contains '{pkg_name}' after scope=global remove"
    );
    assert!(
        cache_dir.exists(),
        "scope=global must not delete ~/.algocline/packages/{pkg_name}/"
    );

    // Cleanup the cache dir (scope=global deliberately leaves it).
    let _ = std::fs::remove_dir_all(&cache_dir);
    client.cancel().await.expect("cancel failed");
}

/// Variant scope link → require: `alc_pkg_link --scope=variant` writes
/// `alc.local.toml` and the next `alc_run` (with the same `project_root`)
/// must be able to `require()` the variant pkg by its declared name.
///
/// Regression for the `VariantPkg` resolver: see
/// `crates/algocline-engine/src/variant_pkg.rs`.
#[tokio::test]
async fn test_variant_scope_link_then_run_require() {
    let client = connect().await;

    // 1. Create a temp project root with empty alc.toml so resolve_project_root succeeds.
    let tmp = tempfile::tempdir().expect("failed to create tempdir");
    let project_root = tmp.path();
    std::fs::write(project_root.join("alc.toml"), "[packages]\n").expect("write alc.toml");

    // 2. Create a temp pkg dir living OUTSIDE the project root (typical worktree workflow).
    let pkg_dir = tmp.path().join("variant_src").join("e2e_variant_pkg");
    std::fs::create_dir_all(&pkg_dir).expect("mkdir pkg_dir");
    std::fs::write(
        pkg_dir.join("init.lua"),
        r#"return { value = "from-variant" }"#,
    )
    .expect("write init.lua");

    // 3. Link as variant scope → writes alc.local.toml.
    let link_resp = call_json(
        &client,
        "alc_pkg_link",
        json!({
            "path": pkg_dir.to_string_lossy(),
            "scope": "variant",
            "project_root": project_root.to_string_lossy(),
        }),
    )
    .await;
    assert!(
        link_resp.get("error").is_none(),
        "alc_pkg_link should succeed, got: {link_resp}"
    );
    assert!(
        project_root.join("alc.local.toml").exists(),
        "alc.local.toml should have been created"
    );

    // 4. Run `require("e2e_variant_pkg")` — must resolve through VariantPkg resolver.
    let run_resp = call_json(
        &client,
        "alc_run",
        json!({
            "code": r#"return require("e2e_variant_pkg").value"#,
            "project_root": project_root.to_string_lossy(),
        }),
    )
    .await;

    assert_eq!(
        run_resp["status"], "completed",
        "alc_run should complete, got: {run_resp}"
    );
    assert_eq!(
        run_resp["result"], "from-variant",
        "variant pkg should be resolved and return its sentinel value"
    );

    // 5. alc_pkg_list should surface the variant entry.
    let list_resp = call_json(
        &client,
        "alc_pkg_list",
        json!({ "project_root": project_root.to_string_lossy() }),
    )
    .await;
    let packages = list_resp["packages"]
        .as_array()
        .expect("packages array missing");
    let entry = packages
        .iter()
        .find(|p| p["name"] == "e2e_variant_pkg")
        .expect("e2e_variant_pkg not found in alc_pkg_list");
    assert_eq!(entry["scope"], "variant");
    assert_eq!(entry["active"], true);
    assert_eq!(entry["resolved_source_kind"], "variant");

    client.cancel().await.expect("cancel failed");
}

/// Install → remove dest dir → repair: full round-trip through MCP.
/// Covers the (B) installed-dir-missing class of `alc_pkg_repair`.
#[tokio::test]
async fn test_pkg_repair_reinstalls_deleted_dir() {
    let client = connect().await;

    // Source pkg dir outside HOME.
    let tmp = tempfile::tempdir().expect("tempdir");
    let source = tmp.path().join("e2e_repair_pkg");
    std::fs::create_dir_all(&source).expect("mkdir");
    std::fs::write(
        source.join("init.lua"),
        r#"local M = {}
M.meta = { name = "e2e_repair_pkg", version = "0.1.0" }
function M.run(ctx) return "ok" end
return M"#,
    )
    .expect("write init.lua");

    // Install.
    call_json(
        &client,
        "alc_pkg_install",
        json!({ "url": source.to_string_lossy() }),
    )
    .await;

    // Simulate breakage: remove the installed dest.
    let dest = dirs::home_dir()
        .expect("home")
        .join(".algocline")
        .join("packages")
        .join("e2e_repair_pkg");
    assert!(dest.exists(), "dest should exist after install");
    std::fs::remove_dir_all(&dest).expect("rm dest");
    assert!(!dest.exists());

    // Repair.
    let resp = call_json(
        &client,
        "alc_pkg_repair",
        json!({ "name": "e2e_repair_pkg" }),
    )
    .await;

    let repaired = resp["repaired"].as_array().expect("repaired array missing");
    assert_eq!(repaired.len(), 1, "one repair expected, got: {resp}");
    assert_eq!(repaired[0]["name"], "e2e_repair_pkg");
    assert_eq!(repaired[0]["kind"], "installed_missing");
    assert!(dest.exists(), "dest should be restored after repair");

    // Cleanup.
    let _ = std::fs::remove_dir_all(&dest);
    client.cancel().await.expect("cancel failed");
}

/// Install → remove dest dir → doctor: diagnose without side effects.
/// Verifies the (B) installed_missing bucket is populated AND that the dest
/// directory is NOT resurrected (this is the doctor-vs-repair distinction).
#[tokio::test]
async fn test_pkg_doctor_reports_installed_missing() {
    let client = connect().await;

    // Source pkg dir outside HOME.
    let tmp = tempfile::tempdir().expect("tempdir");
    let source = tmp.path().join("e2e_doctor_pkg");
    std::fs::create_dir_all(&source).expect("mkdir");
    std::fs::write(
        source.join("init.lua"),
        r#"local M = {}
M.meta = { name = "e2e_doctor_pkg", version = "0.1.0" }
function M.run(ctx) return "ok" end
return M"#,
    )
    .expect("write init.lua");

    // Install.
    call_json(
        &client,
        "alc_pkg_install",
        json!({ "url": source.to_string_lossy() }),
    )
    .await;

    // Simulate breakage: remove the installed dest.
    let dest = dirs::home_dir()
        .expect("home")
        .join(".algocline")
        .join("packages")
        .join("e2e_doctor_pkg");
    assert!(dest.exists(), "dest should exist after install");
    std::fs::remove_dir_all(&dest).expect("rm dest");
    assert!(!dest.exists());

    // Doctor (read-only diagnose).
    let resp = call_json(
        &client,
        "alc_pkg_doctor",
        json!({ "name": "e2e_doctor_pkg" }),
    )
    .await;

    let installed_missing = resp["installed_missing"]
        .as_array()
        .expect("installed_missing array missing");
    let entry = installed_missing
        .iter()
        .find(|e| e["name"] == "e2e_doctor_pkg")
        .unwrap_or_else(|| panic!("e2e_doctor_pkg not found in installed_missing, got: {resp}"));
    assert_eq!(entry["kind"], "installed_missing");

    // THE doctor-vs-repair distinction: dest must NOT be resurrected.
    assert!(
        !dest.exists(),
        "dest must not be resurrected by doctor (read-only)"
    );

    // Cleanup: doctor didn't create anything; remove the manifest entry via repair
    // to keep installed.json clean for subsequent runs.
    let _ = call_json(
        &client,
        "alc_pkg_repair",
        json!({ "name": "e2e_doctor_pkg" }),
    )
    .await;
    let _ = std::fs::remove_dir_all(&dest);
    client.cancel().await.expect("cancel failed");
}

/// Unknown pkg name → Err with a "not found in installed.json" message.
#[tokio::test]
async fn test_pkg_doctor_unknown_pkg_errors() {
    let client = connect().await;

    let result = client
        .call_tool(call_params(
            "alc_pkg_doctor",
            json!({ "name": "nonexistent_xyz_pkg" }),
        ))
        .await
        .expect("call_tool failed");
    let text = extract_text(&result);

    assert!(
        text.contains("not found in installed.json"),
        "expected unknown-pkg error message, got: {text}"
    );

    client.cancel().await.expect("cancel failed");
}

/// Shape violation: `name` must be a string (or omitted), not a number.
///
/// The param deserialization fails at the MCP protocol layer (before the
/// handler runs), so we expect `call_tool` itself to return `Err` with an
/// invalid-type message — distinct from handler-level typed errors which
/// surface as `CallToolResult { is_error: true, ... }`.
#[tokio::test]
async fn test_pkg_doctor_shape_error() {
    let client = connect().await;

    let outcome = client
        .call_tool(call_params("alc_pkg_doctor", json!({ "name": 123 })))
        .await;

    match outcome {
        Ok(result) => {
            let is_error = result.is_error.unwrap_or(false);
            let text = extract_text(&result);
            let has_type_error = text.contains("invalid type")
                || text.contains("expected a string")
                || text.contains("expected string");
            assert!(
                is_error || has_type_error,
                "expected shape error (is_error=true or type-mismatch text), got is_error={is_error:?}, text: {text}"
            );
        }
        Err(e) => {
            let msg = format!("{e}");
            assert!(
                msg.contains("invalid type") && msg.contains("string"),
                "expected invalid-type error from param deserialization, got: {msg}"
            );
        }
    }

    client.cancel().await.expect("cancel failed");
}

// ─── Hub tools (alc_hub_reindex / alc_hub_gendoc / alc_hub_dist) ────

/// Create a minimal hub fixture directory containing a single fake package
/// whose `init.lua` has a `meta` table. Shared by hub_reindex / hub_gendoc
/// / hub_dist tests — each test owns its own tempdir so runs are parallel-
/// safe.
fn setup_hub_fixture() -> tempfile::TempDir {
    let tmp = tempfile::tempdir().expect("tempdir");

    let pkg_dir = tmp.path().join("fake_pkg");
    std::fs::create_dir_all(&pkg_dir).expect("mkdir fake_pkg");
    std::fs::write(
        pkg_dir.join("init.lua"),
        r#"local M = {}
M.meta = {
  name = "fake_pkg",
  version = "0.1.0",
  category = "test",
  description = "fake package used by e2e tests",
}
M.spec = {}
return M
"#,
    )
    .expect("write init.lua");

    // Optional TOML config (not used unless projections include
    // context7/devin). Kept around so tests can opt into config-
    // requiring projections without re-writing the fixture.
    std::fs::write(
        tmp.path().join("configs.toml"),
        r#"[context7]
projectTitle = "test"
description = "test"
rules = []

[devin]
project_name = "test"
"#,
    )
    .expect("write configs.toml");

    tmp
}

#[tokio::test]
async fn test_alc_hub_reindex_ok() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    let resp = call_json(
        &client,
        "alc_hub_reindex",
        json!({
            "source_dir": source_dir,
            "output_path": output_path,
        }),
    )
    .await;

    let pkg_count = resp
        .get("package_count")
        .and_then(|v| v.as_u64())
        .unwrap_or_else(|| panic!("expected package_count u64 in response: {resp}"));
    assert!(
        pkg_count > 0,
        "expected at least one package in reindex output, got {pkg_count}: {resp}"
    );

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_hub_gendoc_ok() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    // gendoc requires an existing hub_index.json in source_dir.
    let _ = call_json(
        &client,
        "alc_hub_reindex",
        json!({
            "source_dir": source_dir.clone(),
            "output_path": output_path,
        }),
    )
    .await;

    let out_dir_path = tmp.path().join("docs");
    let out_dir = out_dir_path.to_str().expect("utf-8 path").to_string();

    let resp = call_json(
        &client,
        "alc_hub_gendoc",
        json!({
            "source_dir": source_dir,
            "out_dir": out_dir,
        }),
    )
    .await;

    assert!(
        resp.get("source_dir").is_some(),
        "expected source_dir in gendoc response, got: {resp}"
    );

    let narrative = out_dir_path.join("narrative").join("fake_pkg.md");
    assert!(
        narrative.exists(),
        "expected narrative/fake_pkg.md to be generated at {} (gendoc resp: {resp})",
        narrative.display()
    );

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_hub_gendoc_with_toml_config_context7() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let config_path = tmp
        .path()
        .join("configs.toml")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    // gendoc requires an existing hub_index.json in source_dir.
    let _ = call_json(
        &client,
        "alc_hub_reindex",
        json!({
            "source_dir": source_dir.clone(),
            "output_path": output_path,
        }),
    )
    .await;

    let _resp = call_json(
        &client,
        "alc_hub_gendoc",
        json!({
            "source_dir": source_dir.clone(),
            "projections": ["context7"],
            "config_path": config_path,
        }),
    )
    .await;

    let context7_json = tmp.path().join("context7.json");
    assert!(
        context7_json.exists(),
        "expected context7 projection to be generated at {}",
        context7_json.display()
    );

    client.cancel().await.expect("cancel failed");
}

/// Core-defaults case: requesting `context7`/`devin` projections without a
/// `config_path` and without an `alc.toml` must succeed using core-embedded
/// default rules and repo notes (no `is_error`).
#[tokio::test]
async fn test_alc_hub_gendoc_core_defaults_without_alc_toml() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    // Need a hub_index.json first so gendoc reaches the projection step.
    let _ = call_json(
        &client,
        "alc_hub_reindex",
        json!({
            "source_dir": source_dir.clone(),
            "output_path": output_path,
        }),
    )
    .await;

    // No config_path, no alc.toml in fixture → core defaults only.
    let resp = call_json(
        &client,
        "alc_hub_gendoc",
        json!({
            "source_dir": source_dir.clone(),
            "projections": ["context7", "devin"],
        }),
    )
    .await;

    // Both projection output files must be generated.
    let context7_json = tmp.path().join("context7.json");
    let devin_wiki = tmp.path().join(".devin").join("wiki.json");
    assert!(
        context7_json.exists(),
        "expected context7.json from core defaults, got resp: {resp}"
    );
    assert!(
        devin_wiki.exists(),
        "expected .devin/wiki.json from core defaults, got resp: {resp}"
    );

    // Verify projectTitle and description are non-null in context7.json (core defaults).
    // The context7 Lua projection emits these when present in the injected config table.
    let c7_text = std::fs::read_to_string(&context7_json).expect("read context7.json");
    let c7: serde_json::Value = serde_json::from_str(&c7_text).expect("parse context7.json");
    assert!(
        c7.get("projectTitle").and_then(|v| v.as_str()).is_some(),
        "expected projectTitle to be a non-null string in context7.json, got: {c7_text}"
    );
    assert!(
        c7.get("description").and_then(|v| v.as_str()).is_some(),
        "expected description to be a non-null string in context7.json, got: {c7_text}"
    );

    // The devin wiki schema only contains repo_notes / pages (no project_name or description
    // at the top level per docs.devin.ai schema). Verify repo_notes is populated.
    let dv_text = std::fs::read_to_string(&devin_wiki).expect("read wiki.json");
    let dv: serde_json::Value = serde_json::from_str(&dv_text).expect("parse wiki.json");
    assert!(
        dv.get("repo_notes").and_then(|v| v.as_array()).is_some(),
        "expected repo_notes array in wiki.json, got: {dv_text}"
    );

    client.cancel().await.expect("cancel failed");
}

/// Happy-path: `alc_hub_gendoc` with `alc.toml` containing `[hub.context7]`
/// and `[hub.devin]` sections and no explicit `config_path` must generate both
/// `context7.json` and `.devin/wiki.json`.
#[tokio::test]
async fn test_alc_hub_gendoc_with_alc_toml_hub_sections() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    // Write alc.toml with [hub.context7] / [hub.devin] sections.
    std::fs::write(
        tmp.path().join("alc.toml"),
        r#"[hub]
name = "e2e-test-project"

[hub.context7]
description = "E2E test project description"
extra_rules = ["Always write tests"]

[hub.devin]
extra_repo_notes = ["Use Rust for performance-critical paths"]
"#,
    )
    .expect("write alc.toml");

    // gendoc requires an existing hub_index.json.
    let _ = call_json(
        &client,
        "alc_hub_reindex",
        json!({
            "source_dir": source_dir.clone(),
            "output_path": output_path,
        }),
    )
    .await;

    let resp = call_json(
        &client,
        "alc_hub_gendoc",
        json!({
            "source_dir": source_dir.clone(),
            "projections": ["context7", "devin"],
        }),
    )
    .await;

    let context7_json = tmp.path().join("context7.json");
    let devin_wiki = tmp.path().join(".devin").join("wiki.json");
    assert!(
        context7_json.exists(),
        "expected context7.json with alc.toml hub sections, got resp: {resp}"
    );
    assert!(
        devin_wiki.exists(),
        "expected .devin/wiki.json with alc.toml hub sections, got resp: {resp}"
    );

    // Verify projectTitle and description are wired from alc.toml in context7.json.
    let c7_text = std::fs::read_to_string(&context7_json).expect("read context7.json");
    let c7: serde_json::Value = serde_json::from_str(&c7_text).expect("parse context7.json");
    assert_eq!(
        c7.get("projectTitle").and_then(|v| v.as_str()),
        Some("e2e-test-project"),
        "expected projectTitle = 'e2e-test-project' from [hub].name, got: {c7_text}"
    );
    assert_eq!(
        c7.get("description").and_then(|v| v.as_str()),
        Some("E2E test project description"),
        "expected description from [hub.context7].description, got: {c7_text}"
    );

    // The devin wiki schema only contains repo_notes / pages (no project_name or description
    // at the top level per docs.devin.ai schema). Verify repo_notes is populated.
    let dv_text = std::fs::read_to_string(&devin_wiki).expect("read wiki.json");
    let dv: serde_json::Value = serde_json::from_str(&dv_text).expect("parse wiki.json");
    assert!(
        dv.get("repo_notes").and_then(|v| v.as_array()).is_some(),
        "expected repo_notes array in wiki.json, got: {dv_text}"
    );

    client.cancel().await.expect("cancel failed");
}

/// Error-path: `alc_hub_gendoc` with a `.lua` `config_path` must return
/// `is_error=true` with a message stating that `.lua` is no longer supported.
#[tokio::test]
async fn test_alc_hub_gendoc_rejects_lua_config_path() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    // Write a (valid) Lua file — the error must fire on extension alone,
    // before any file I/O.
    let lua_path = tmp.path().join("config.lua");
    std::fs::write(&lua_path, "return {}").expect("write config.lua");
    let config_path = lua_path.to_str().expect("utf-8 path").to_string();

    let _ = call_json(
        &client,
        "alc_hub_reindex",
        json!({
            "source_dir": source_dir.clone(),
            "output_path": output_path,
        }),
    )
    .await;

    let outcome = client
        .call_tool(call_params(
            "alc_hub_gendoc",
            json!({
                "source_dir": source_dir,
                "projections": ["context7"],
                "config_path": config_path,
            }),
        ))
        .await;

    match outcome {
        Ok(result) => {
            let is_error = result.is_error.unwrap_or(false);
            let text = extract_text(&result);
            assert!(
                is_error,
                "expected is_error=true for .lua config_path, got is_error={is_error:?}, text: {text}"
            );
            assert!(
                text.contains("'.lua' is no longer supported"),
                "expected '.lua' is no longer supported in error text, got: {text}"
            );
        }
        Err(e) => panic!("unexpected call_tool Err: {e}"),
    }

    client.cancel().await.expect("cancel failed");
}

/// Error-path: `alc_hub_gendoc` with `alc.toml` containing both `rules_file`
/// and `rules_override` must return `is_error=true` with a message stating
/// the fields are mutually exclusive.
#[tokio::test]
async fn test_alc_hub_gendoc_rejects_mutually_exclusive_rules() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    // Write rules file and alc.toml with both rules_file + rules_override set.
    std::fs::write(tmp.path().join("rules.txt"), "Rule one\n").expect("write rules.txt");
    std::fs::write(
        tmp.path().join("alc.toml"),
        r#"[hub.context7]
rules_file = "rules.txt"
rules_override = ["Conflict rule"]
"#,
    )
    .expect("write alc.toml");

    let _ = call_json(
        &client,
        "alc_hub_reindex",
        json!({
            "source_dir": source_dir.clone(),
            "output_path": output_path,
        }),
    )
    .await;

    let outcome = client
        .call_tool(call_params(
            "alc_hub_gendoc",
            json!({
                "source_dir": source_dir,
                "projections": ["context7"],
            }),
        ))
        .await;

    match outcome {
        Ok(result) => {
            let is_error = result.is_error.unwrap_or(false);
            let text = extract_text(&result);
            assert!(
                is_error,
                "expected is_error=true for mutually-exclusive rules, got is_error={is_error:?}, text: {text}"
            );
            assert!(
                text.contains("mutually exclusive"),
                "expected 'mutually exclusive' in error text, got: {text}"
            );
        }
        Err(e) => panic!("unexpected call_tool Err: {e}"),
    }

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_hub_gendoc_unknown_projection_rejected() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    // Need a hub_index.json first so projection validation is evaluated
    // in the normal gendoc flow.
    let _ = call_json(
        &client,
        "alc_hub_reindex",
        json!({
            "source_dir": source_dir.clone(),
            "output_path": output_path,
        }),
    )
    .await;

    let outcome = client
        .call_tool(call_params(
            "alc_hub_gendoc",
            json!({
                "source_dir": source_dir,
                "projections": ["unknown_projection"],
            }),
        ))
        .await;

    match outcome {
        Ok(result) => {
            let is_error = result.is_error.unwrap_or(false);
            let text = extract_text(&result);
            assert!(
                is_error,
                "expected is_error=true for unknown projection, got is_error={is_error:?}, text: {text}"
            );
            assert!(
                text.contains("unknown projection"),
                "expected unknown projection error text, got: {text}"
            );
        }
        Err(e) => panic!("unexpected call_tool Err: {e}"),
    }

    client.cancel().await.expect("cancel failed");
}

/// narrative projection: `projections=["narrative"]` must be accepted and
/// generate `docs/narrative/{pkg}.md`.
///
/// Note: narrative/{pkg}.md files are unconditionally emitted by the embedded
/// gen_docs.lua when lint_only=false regardless of which other projections are
/// requested — this test confirms the Rust allowlist gate passes "narrative"
/// through (approach A: no --narrative argv is pushed to gen_docs.lua).
#[tokio::test]
async fn test_alc_hub_gendoc_narrative_projection_generates_per_pkg_md() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir_path = tmp.path().join("docs_narrative");
    let out_dir = out_dir_path.to_str().expect("utf-8 path").to_string();

    let _ = call_json(
        &client,
        "alc_hub_reindex",
        json!({
            "source_dir": source_dir.clone(),
            "output_path": output_path,
        }),
    )
    .await;

    let resp = call_json(
        &client,
        "alc_hub_gendoc",
        json!({
            "source_dir": source_dir,
            "out_dir": out_dir,
            "projections": ["narrative"],
        }),
    )
    .await;

    let narrative = out_dir_path.join("narrative").join("fake_pkg.md");
    assert!(
        narrative.exists(),
        "expected narrative/fake_pkg.md at {} (resp: {resp})",
        narrative.display()
    );
    let len = std::fs::metadata(&narrative).expect("metadata").len();
    assert!(
        len > 0,
        "expected non-empty narrative/fake_pkg.md at {} (resp: {resp})",
        narrative.display()
    );

    client.cancel().await.expect("cancel failed");
}

/// llms projection: `projections=["llms"]` must be accepted and generate
/// `docs/llms.txt` + `docs/llms-full.txt`.
///
/// Note: llms.txt and llms-full.txt are unconditionally emitted by the embedded
/// gen_docs.lua when lint_only=false — this test confirms the Rust allowlist
/// gate passes "llms" through (approach A: no --llms argv is pushed to
/// gen_docs.lua).
#[tokio::test]
async fn test_alc_hub_gendoc_llms_projection_generates_llms_txt() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir_path = tmp.path().join("docs_llms");
    let out_dir = out_dir_path.to_str().expect("utf-8 path").to_string();

    let _ = call_json(
        &client,
        "alc_hub_reindex",
        json!({
            "source_dir": source_dir.clone(),
            "output_path": output_path,
        }),
    )
    .await;

    let resp = call_json(
        &client,
        "alc_hub_gendoc",
        json!({
            "source_dir": source_dir,
            "out_dir": out_dir,
            "projections": ["llms"],
        }),
    )
    .await;

    let llms_txt = out_dir_path.join("llms.txt");
    assert!(
        llms_txt.exists(),
        "expected llms.txt at {} (resp: {resp})",
        llms_txt.display()
    );
    let len = std::fs::metadata(&llms_txt).expect("metadata").len();
    assert!(
        len > 0,
        "expected non-empty llms.txt at {} (resp: {resp})",
        llms_txt.display()
    );

    let llms_full_txt = out_dir_path.join("llms-full.txt");
    assert!(
        llms_full_txt.exists(),
        "expected llms-full.txt at {} (resp: {resp})",
        llms_full_txt.display()
    );
    let len_full = std::fs::metadata(&llms_full_txt).expect("metadata").len();
    assert!(
        len_full > 0,
        "expected non-empty llms-full.txt at {} (resp: {resp})",
        llms_full_txt.display()
    );

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_hub_dist_ok() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir = tmp
        .path()
        .join("docs")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    let resp = call_json(
        &client,
        "alc_hub_dist",
        json!({
            "source_dir": source_dir,
            "output_path": output_path,
            "out_dir": out_dir,
        }),
    )
    .await;

    assert_eq!(
        resp.get("preset_catalog_version").and_then(|v| v.as_str()),
        Some(PRESET_CATALOG_VERSION),
        "expected preset_catalog_version in dist response, got: {resp}"
    );
    assert!(
        resp.get("preset").is_none(),
        "expected no preset object when preset omitted, got: {resp}"
    );

    let reindex = resp
        .get("reindex")
        .unwrap_or_else(|| panic!("expected reindex field, got: {resp}"));
    let pkg_count = reindex
        .get("package_count")
        .and_then(|v| v.as_u64())
        .unwrap_or_else(|| panic!("expected reindex.package_count u64, got: {resp}"));
    assert!(
        pkg_count > 0,
        "expected reindex.package_count > 0, got {pkg_count}: {resp}"
    );

    let gendoc = resp
        .get("gendoc")
        .unwrap_or_else(|| panic!("expected gendoc field, got: {resp}"));
    assert!(
        gendoc.is_object(),
        "expected gendoc to be a JSON object, got: {resp}"
    );
    assert!(
        gendoc.get("stdout").is_some(),
        "dist.gendoc must include stdout field",
    );

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_info_includes_preset_catalog_version() {
    let client = connect().await;

    let resp = call_json(&client, "alc_info", json!({})).await;
    assert_eq!(
        resp.get("preset_catalog_version").and_then(|v| v.as_str()),
        Some(PRESET_CATALOG_VERSION),
        "expected preset_catalog_version in alc_info, got: {resp}"
    );

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_hub_dist_preset_publish_uses_alc_toml_override() {
    let client = connect().await;
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path();

    std::fs::write(
        root.join("alc.toml"),
        r#"[packages]

[hub.dist]

[hub.dist.presets.publish]
projections = ["context7"]
config_path = "configs.toml"
"#,
    )
    .expect("write alc.toml");

    let hub_dir = root.join("hub");
    std::fs::create_dir_all(&hub_dir).expect("mkdir hub");
    std::fs::write(
        hub_dir.join("configs.toml"),
        r#"[context7]
projectTitle = "test"
description = "test"
rules = []
"#,
    )
    .expect("write configs.toml");

    let pkg_dir = hub_dir.join("fake_pkg");
    std::fs::create_dir_all(&pkg_dir).expect("mkdir fake_pkg");
    std::fs::write(
        pkg_dir.join("init.lua"),
        r#"local M = {}
M.meta = {
  name = "fake_pkg",
  version = "0.1.0",
  category = "test",
  description = "fake package used by preset e2e",
}
M.spec = {}
return M
"#,
    )
    .expect("write init.lua");

    let source_dir = hub_dir.to_str().expect("utf-8 path").to_string();
    let project_root = root.to_str().expect("utf-8 path").to_string();
    let output_path = hub_dir
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir = hub_dir
        .join("docs")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    let resp = call_json(
        &client,
        "alc_hub_dist",
        json!({
            "source_dir": source_dir,
            "project_root": project_root,
            "output_path": output_path,
            "out_dir": out_dir,
            "preset": "publish",
        }),
    )
    .await;

    assert_eq!(
        resp.get("preset_catalog_version").and_then(|v| v.as_str()),
        Some(PRESET_CATALOG_VERSION),
        "expected preset_catalog_version in dist response, got: {resp}"
    );

    let preset = resp
        .get("preset")
        .unwrap_or_else(|| panic!("expected preset object, got: {resp}"));
    assert_eq!(preset.get("name").and_then(|v| v.as_str()), Some("publish"));

    let resolved = preset
        .get("resolved")
        .unwrap_or_else(|| panic!("expected preset.resolved, got: {preset}"));
    let projections = resolved
        .get("projections")
        .and_then(|v| v.as_array())
        .unwrap_or_else(|| panic!("expected projections array, got: {resolved}"));
    let projection_names: Vec<&str> = projections
        .iter()
        .map(|v| v.as_str().expect("projection string"))
        .collect();
    assert_eq!(projection_names, vec!["context7"]);

    let context7_json = hub_dir.join("context7.json");
    assert!(
        context7_json.exists(),
        "expected context7.json at {}",
        context7_json.display()
    );

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_hub_dist_with_toml_config_context7() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let config_path = tmp
        .path()
        .join("configs.toml")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    let _resp = call_json(
        &client,
        "alc_hub_dist",
        json!({
            "source_dir": source_dir,
            "output_path": output_path,
            "projections": ["context7"],
            "config_path": config_path,
        }),
    )
    .await;

    let context7_json = tmp.path().join("context7.json");
    assert!(
        context7_json.exists(),
        "expected context7 projection to be generated at {}",
        context7_json.display()
    );

    client.cancel().await.expect("cancel failed");
}

#[tokio::test]
async fn test_alc_hub_dist_gendoc_failure_includes_reindex_result() {
    let client = connect().await;
    let tmp = setup_hub_fixture();
    let source_dir = tmp.path().to_str().expect("utf-8 path").to_string();
    let output_path = tmp
        .path()
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    // Reindex should succeed, then gendoc should fail because an unknown
    // projection value is invalid.  This verifies that dist embeds the
    // reindex result in the gendoc failure message regardless of the
    // failure reason.
    let outcome = client
        .call_tool(call_params(
            "alc_hub_dist",
            json!({
                "source_dir": source_dir,
                "output_path": output_path,
                "projections": ["invalid_projection_xyz"],
            }),
        ))
        .await;

    match outcome {
        Ok(result) => {
            let is_error = result.is_error.unwrap_or(false);
            let text = extract_text(&result);
            assert!(
                is_error,
                "expected is_error=true when gendoc fails after reindex, got: is_error={is_error:?}, text: {text}"
            );
            assert!(
                text.contains("dist: gendoc failed"),
                "expected dist gendoc failure prefix, got: {text}"
            );
            assert!(
                text.contains("reindex result (succeeded):"),
                "expected reindex result to be embedded in error text, got: {text}"
            );
        }
        Err(e) => panic!("unexpected call_tool Err: {e}"),
    }

    client.cancel().await.expect("cancel failed");
}

/// Fixture-based E2E: `alc_hub_dist` against the in-repo
/// `tests/fixtures/hub_dist_sample/` tree that contains three packages
/// (pkg_alpha / pkg_beta / pkg_gamma) each embedding a distinct signal
/// token in its docstring.
///
/// Each package exercises a different part of the `alc_shapes` type
/// system that is now fully vendored:
///   - pkg_alpha: `T.boolean` / `T.table`  (ALPHA_SIGNAL_BOOLEAN_TABLE)
///   - pkg_beta:  `S.instrument` + `:describe`  (BETA_SIGNAL_INSTRUMENT_DESCRIBE)
///   - pkg_gamma: nested `T.shape` / `T.array_of`  (GAMMA_SIGNAL_NESTED_SHAPE)
///
/// Verifications (labelled A–G per plan):
///   A. dist response `status == "ok"` (implicit: no is_error)
///   B. `llms-full.txt` contains all three signal tokens
///   C. `narrative/{pkg_alpha,pkg_beta,pkg_gamma}.md` exist
///   D. `llms.txt` contains index lines for all three packages
///   E. Type-system signal tokens appear in the narrative files
///   F. `reindex.package_count == 3`
///   G. context7.json and .devin/wiki.json are emitted
#[tokio::test]
async fn test_alc_hub_dist_fixture() {
    let client = connect().await;

    // Copy fixture tree to a writable tempdir so gen_docs can write
    // context7.json / .devin/wiki.json back to source_dir.
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path();

    let fixture_src =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hub_dist_sample");

    copy_fixture_tree(&fixture_src, root).expect("copy fixture");

    let source_dir = root.to_str().expect("utf-8 path").to_string();
    let output_path = root
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir_path = root.join("docs");
    let out_dir = out_dir_path.to_str().expect("utf-8 path").to_string();
    let config_path = root
        .join("tools/gendoc.toml")
        .to_str()
        .expect("utf-8 path")
        .to_string();

    let resp = call_json(
        &client,
        "alc_hub_dist",
        json!({
            "source_dir":  source_dir,
            "output_path": output_path,
            "out_dir":     out_dir,
            "projections": ["hub", "context7", "devin"],
            "config_path": config_path,
        }),
    )
    .await;

    // A. Top-level response must not carry is_error; reindex + gendoc both present.
    let reindex = resp
        .get("reindex")
        .unwrap_or_else(|| panic!("expected reindex field, got: {resp}"));
    let _gendoc = resp
        .get("gendoc")
        .unwrap_or_else(|| panic!("expected gendoc field, got: {resp}"));

    // F. reindex.package_count == 3
    let pkg_count = reindex
        .get("package_count")
        .and_then(|v| v.as_u64())
        .unwrap_or_else(|| panic!("expected reindex.package_count u64, got: {resp}"));
    assert_eq!(
        pkg_count, 3,
        "expected exactly 3 packages indexed, got {pkg_count}: {resp}"
    );

    // C. narrative/*.md files must exist for all three packages.
    for pkg in &["pkg_alpha", "pkg_beta", "pkg_gamma"] {
        let narrative = out_dir_path.join("narrative").join(format!("{pkg}.md"));
        assert!(
            narrative.exists(),
            "expected narrative/{pkg}.md at {}",
            narrative.display()
        );
    }

    // B + E. llms-full.txt must contain all three signal tokens.
    let llms_full_path = out_dir_path.join("llms-full.txt");
    assert!(
        llms_full_path.exists(),
        "expected llms-full.txt at {}",
        llms_full_path.display()
    );
    let llms_full = std::fs::read_to_string(&llms_full_path).expect("read llms-full.txt");
    for token in &[
        "ALPHA_SIGNAL_BOOLEAN_TABLE",
        "BETA_SIGNAL_INSTRUMENT_DESCRIBE",
        "GAMMA_SIGNAL_NESTED_SHAPE",
    ] {
        assert!(
            llms_full.contains(token),
            "expected signal token '{token}' in llms-full.txt"
        );
    }

    // D. llms.txt must reference all three packages.
    let llms_path = out_dir_path.join("llms.txt");
    assert!(
        llms_path.exists(),
        "expected llms.txt at {}",
        llms_path.display()
    );
    let llms = std::fs::read_to_string(&llms_path).expect("read llms.txt");
    for pkg in &["pkg_alpha", "pkg_beta", "pkg_gamma"] {
        assert!(
            llms.contains(pkg),
            "expected '{pkg}' in llms.txt index, got:\n{llms}"
        );
    }

    // G. context7.json and .devin/wiki.json emitted at source_dir root.
    let context7 = root.join("context7.json");
    assert!(
        context7.exists(),
        "expected context7.json at {}",
        context7.display()
    );
    let devin_wiki = root.join(".devin/wiki.json");
    assert!(
        devin_wiki.exists(),
        "expected .devin/wiki.json at {}",
        devin_wiki.display()
    );

    client.cancel().await.expect("cancel failed");
}

/// Fixture-based E2E: `alc_hub_dist` with a mirror `alc_shapes/init.lua`
/// whose `M.VERSION` matches `EMBEDDED_ALC_SHAPES_VERSION` (0.25.1).
///
/// The mirror file is read for VERSION extraction only; actual Lua API
/// still comes from the embedded vendored copy. Dist must succeed.
#[tokio::test]
async fn test_alc_hub_dist_fixture_mirror_version_match() {
    let client = connect().await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path();

    let fixture_src = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/hub_dist_sample_version_match");

    copy_fixture_tree(&fixture_src, root).expect("copy fixture");

    let source_dir = root.to_str().expect("utf-8 path").to_string();
    let output_path = root
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir = root.join("docs").to_str().expect("utf-8 path").to_string();

    let resp = call_json(
        &client,
        "alc_hub_dist",
        json!({
            "source_dir":  source_dir,
            "output_path": output_path,
            "out_dir":     out_dir,
        }),
    )
    .await;

    // Dist must succeed: response contains reindex + gendoc fields.
    assert!(
        resp.get("reindex").is_some(),
        "expected reindex field on version-match success, got: {resp}"
    );
    assert!(
        resp.get("gendoc").is_some(),
        "expected gendoc field on version-match success, got: {resp}"
    );

    // Signal token must appear in llms-full.txt.
    let out_dir_path = root.join("docs");
    let llms_full_path = out_dir_path.join("llms-full.txt");
    assert!(
        llms_full_path.exists(),
        "expected llms-full.txt at {}",
        llms_full_path.display()
    );
    let llms_full = std::fs::read_to_string(&llms_full_path).expect("read llms-full.txt");
    assert!(
        llms_full.contains("VMATCH_SIGNAL_ALPHA"),
        "expected VMATCH_SIGNAL_ALPHA signal token in llms-full.txt"
    );

    client.cancel().await.expect("cancel failed");
}

/// Fixture-based E2E: `alc_hub_dist` with a mirror `alc_shapes/init.lua`
/// whose `M.VERSION` ("9.9.9") differs from the embedded constant.
///
/// Dist must fail early with a typed `ShapesVersionMismatch` error
/// surfaced in the MCP wire response, containing both version strings
/// and the canonical hint.
#[tokio::test]
async fn test_alc_hub_dist_fixture_mirror_version_mismatch() {
    let client = connect().await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path();

    let fixture_src = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/hub_dist_sample_version_mismatch");

    copy_fixture_tree(&fixture_src, root).expect("copy fixture");

    let source_dir = root.to_str().expect("utf-8 path").to_string();
    let output_path = root
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir = root.join("docs").to_str().expect("utf-8 path").to_string();

    let outcome = client
        .call_tool(call_params(
            "alc_hub_dist",
            json!({
                "source_dir":  source_dir,
                "output_path": output_path,
                "out_dir":     out_dir,
            }),
        ))
        .await;

    match outcome {
        Ok(result) => {
            let is_error = result.is_error.unwrap_or(false);
            let text = extract_text(&result);
            assert!(
                is_error,
                "expected is_error=true on version mismatch, got: is_error={is_error:?}, text: {text}"
            );
            // Both version strings must appear in the error text.
            assert!(
                text.contains("0.25.1"),
                "expected embedded version '0.25.1' in error text, got: {text}"
            );
            assert!(
                text.contains("9.9.9"),
                "expected mirror version '9.9.9' in error text, got: {text}"
            );
            // The canonical hint must be present.
            assert!(
                text.contains("CHANGELOG"),
                "expected CHANGELOG hint in error text, got: {text}"
            );
        }
        Err(e) => panic!("unexpected call_tool Err: {e}"),
    }

    client.cancel().await.expect("cancel failed");
}

/// Fixture-based E2E: `alc_hub_dist` with the `luacats` projection emits
/// `source_dir/types/alc_shapes.d.lua` containing LuaCATS class declarations
/// generated from the embedded `alc_shapes` SSoT.
///
/// Verifications:
///   A. dist response contains `reindex` and `gendoc` fields (no is_error)
///   B. `source_dir/types/alc_shapes.d.lua` exists after the call
///   C. File contains at least three `---@class ` lines (one per registered shape)
///   D. File contains the `AlcResultVoted` class name (from `M.voted` in alc_shapes)
#[tokio::test]
async fn test_alc_hub_dist_luacats_projection() {
    let client = connect().await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path();

    let fixture_src =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hub_dist_sample");

    copy_fixture_tree(&fixture_src, root).expect("copy fixture");

    let source_dir = root.to_str().expect("utf-8 path").to_string();
    let output_path = root
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir = root.join("docs").to_str().expect("utf-8 path").to_string();

    let resp = call_json(
        &client,
        "alc_hub_dist",
        json!({
            "source_dir":  source_dir,
            "output_path": output_path,
            "out_dir":     out_dir,
            "projections": ["luacats"],
        }),
    )
    .await;

    // A. dist response must contain reindex and gendoc fields.
    assert!(
        resp.get("reindex").is_some(),
        "expected reindex field in response, got: {resp}"
    );
    assert!(
        resp.get("gendoc").is_some(),
        "expected gendoc field in response, got: {resp}"
    );

    // B. types/alc_shapes.d.lua must exist under source_dir.
    let luacats_path = root.join("types").join("alc_shapes.d.lua");
    assert!(
        luacats_path.exists(),
        "expected types/alc_shapes.d.lua at {}",
        luacats_path.display()
    );

    let content = std::fs::read_to_string(&luacats_path).expect("read alc_shapes.d.lua");

    // C. At least three `---@class ` declarations (one per registered shape).
    let class_count = content.matches("---@class ").count();
    assert!(
        class_count >= 3,
        "expected at least 3 '---@class ' lines in alc_shapes.d.lua, got {class_count}"
    );

    // D. AlcResultVoted class must be present (from M.voted in alc_shapes/init.lua).
    assert!(
        content.contains("---@class AlcResultVoted"),
        "expected '---@class AlcResultVoted' in alc_shapes.d.lua"
    );

    client.cancel().await.expect("cancel failed");
}

/// Mid-way failure: an invalid `source_dir` causes reindex to fail. The
/// caller must see `is_error=true` with text starting `dist: reindex
/// failed:`, proving that `gendoc` was not invoked and the caller was
/// not silently given a partial success.
#[tokio::test]
async fn test_alc_hub_dist_reindex_failure() {
    let client = connect().await;

    let outcome = client
        .call_tool(call_params(
            "alc_hub_dist",
            json!({
                "source_dir": "/nonexistent/path/for/dist/test",
            }),
        ))
        .await;

    match outcome {
        Ok(result) => {
            let is_error = result.is_error.unwrap_or(false);
            let text = extract_text(&result);
            assert!(
                is_error,
                "expected is_error=true on reindex failure, got: is_error={is_error:?}, text: {text}"
            );
            assert!(
                text.contains("reindex failed"),
                "expected 'reindex failed' in error text, got: {text}"
            );
        }
        Err(e) => panic!("unexpected call_tool Err: {e}"),
    }

    client.cancel().await.expect("cancel failed");
}

// ─── pkg compat-range E2E tests ──────────────────────────────────────────────

/// Shared fixture helper: recursively copy a directory tree.
///
/// Used by every fixture-based E2E test. Previously the same function
/// was redefined nested inside four separate test bodies plus a fifth
/// `_compat` variant at module scope; consolidated here.
fn copy_fixture_tree(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dst)?;
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let ty = entry.file_type()?;
        if ty.is_dir() {
            copy_fixture_tree(&entry.path(), &dst.join(entry.file_name()))?;
        } else {
            std::fs::copy(entry.path(), dst.join(entry.file_name()))?;
        }
    }
    Ok(())
}

/// Fixture-based E2E: `alc_hub_dist` where the single package declares
/// `alc_shapes_compat = ">=0.25.0, <0.26"`, which includes embedded
/// alc_shapes 0.25.1.
///
/// Dist must succeed: response contains `reindex` and `gendoc` fields,
/// and the `gendoc.warnings` array must NOT contain any compat warning.
#[tokio::test]
async fn test_alc_hub_dist_compat_declared_in_range() {
    let client = connect().await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path();

    let fixture_src = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/hub_dist_sample_compat_declared");

    copy_fixture_tree(&fixture_src, root).expect("copy fixture");

    let source_dir = root.to_str().expect("utf-8 path").to_string();
    let output_path = root
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir = root.join("docs").to_str().expect("utf-8 path").to_string();

    let resp = call_json(
        &client,
        "alc_hub_dist",
        json!({
            "source_dir":  source_dir,
            "output_path": output_path,
            "out_dir":     out_dir,
        }),
    )
    .await;

    assert!(
        resp.get("reindex").is_some(),
        "expected reindex field on compat-declared success, got: {resp}"
    );
    assert!(
        resp.get("gendoc").is_some(),
        "expected gendoc field on compat-declared success, got: {resp}"
    );

    // Warnings array should not contain any alc_shapes_compat warning —
    // the package declared an in-range compat range.
    if let Some(gendoc) = resp.get("gendoc") {
        if let Some(warnings) = gendoc.get("warnings") {
            let warnings_str = warnings.to_string();
            assert!(
                !warnings_str.contains("alc_shapes_compat not declared"),
                "unexpected compat-undeclared warning for declared package: {warnings_str}"
            );
        }
    }

    client.cancel().await.expect("cancel failed");
}

/// Fixture-based E2E: `alc_hub_dist` where the single package declares
/// `alc_shapes_compat = ">=0.26.0, <0.27"`, which does NOT include
/// embedded alc_shapes 0.25.1.
///
/// Dist must fail with `is_error=true`. The error text must contain
/// `ShapesCompatViolation`-related substrings: the pkg_name, declared_range,
/// and actual_version.
#[tokio::test]
async fn test_alc_hub_dist_compat_declared_out_of_range() {
    let client = connect().await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path();

    let fixture_src = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/hub_dist_sample_compat_out_of_range");

    copy_fixture_tree(&fixture_src, root).expect("copy fixture");

    let source_dir = root.to_str().expect("utf-8 path").to_string();
    let output_path = root
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir = root.join("docs").to_str().expect("utf-8 path").to_string();

    let outcome = client
        .call_tool(call_params(
            "alc_hub_dist",
            json!({
                "source_dir":  source_dir,
                "output_path": output_path,
                "out_dir":     out_dir,
            }),
        ))
        .await;

    match outcome {
        Ok(result) => {
            let is_error = result.is_error.unwrap_or(false);
            let text = extract_text(&result);
            assert!(
                is_error,
                "expected is_error=true on out-of-range compat, got: is_error={is_error:?}, text: {text}"
            );
            // pkg_name must appear
            assert!(
                text.contains("pkg_alpha"),
                "expected pkg_name 'pkg_alpha' in error text, got: {text}"
            );
            // declared range must appear
            assert!(
                text.contains(">=0.26.0, <0.27"),
                "expected declared_range '>=0.26.0, <0.27' in error text, got: {text}"
            );
            // actual embedded version must appear
            assert!(
                text.contains("0.25.1"),
                "expected actual_version '0.25.1' in error text, got: {text}"
            );
        }
        Err(e) => panic!("unexpected call_tool Err: {e}"),
    }

    client.cancel().await.expect("cancel failed");
}

// ─── alc_pkg_scaffold E2E tests ──────────────────────────────────────────────

/// Basic scaffold: `my_pkg` with no optional fields.
///
/// Checks:
/// - Response has `status = "ok"`.
/// - `<tempdir>/my_pkg/init.lua` is created on disk.
/// - Content contains expected Lua skeleton markers.
#[tokio::test]
async fn test_alc_pkg_scaffold_basic() {
    let client = connect().await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let target_dir = tmp.path().to_str().expect("utf-8 path").to_string();

    let resp = call_json(
        &client,
        "alc_pkg_scaffold",
        json!({
            "name": "my_pkg",
            "target_dir": target_dir,
        }),
    )
    .await;

    assert_eq!(
        resp.get("status").and_then(|v| v.as_str()),
        Some("ok"),
        "expected status=ok, got: {resp}"
    );

    let init_lua = tmp.path().join("my_pkg").join("init.lua");
    assert!(
        init_lua.exists(),
        "expected init.lua at {}",
        init_lua.display()
    );

    let content = std::fs::read_to_string(&init_lua).expect("read init.lua");
    assert!(
        content.contains(r#"name = "my_pkg""#),
        "expected name field in content"
    );
    assert!(
        content.contains("alc_shapes_compat = \">=0.25.0, <0.26\""),
        "expected compat range in content, got excerpt: {}",
        &content[..content.len().min(400)]
    );
    assert!(
        content.contains("function M.run(ctx)"),
        "expected M.run stub"
    );
    assert!(content.contains("T.shape"), "expected T.shape reference");
    assert!(content.contains("return M"), "expected return M");

    client.cancel().await.expect("cancel failed");
}

/// Scaffold with category and description provided — both fields must appear
/// uncommented in the generated `M.meta` table.
#[tokio::test]
async fn test_alc_pkg_scaffold_with_category_and_description() {
    let client = connect().await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let target_dir = tmp.path().to_str().expect("utf-8 path").to_string();

    let resp = call_json(
        &client,
        "alc_pkg_scaffold",
        json!({
            "name": "my_pkg",
            "target_dir": target_dir,
            "category": "selection",
            "description": "test pkg",
        }),
    )
    .await;

    assert_eq!(
        resp.get("status").and_then(|v| v.as_str()),
        Some("ok"),
        "expected status=ok, got: {resp}"
    );

    let content =
        std::fs::read_to_string(tmp.path().join("my_pkg").join("init.lua")).expect("read init.lua");

    assert!(
        content.contains(r#"category = "selection""#),
        "expected uncommented category in content"
    );
    assert!(
        content.contains(r#"description = "test pkg""#),
        "expected uncommented description in content"
    );
    // Commented-out placeholder lines must NOT appear.
    assert!(
        !content.contains("-- category ="),
        "unexpected commented-out category placeholder"
    );
    assert!(
        !content.contains("-- description ="),
        "unexpected commented-out description placeholder"
    );

    client.cancel().await.expect("cancel failed");
}

/// AlreadyExists error: pre-create the init.lua then call scaffold.
///
/// The MCP response must carry `is_error = true` and the text must mention
/// "already exists".
#[tokio::test]
async fn test_alc_pkg_scaffold_already_exists() {
    let client = connect().await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let pkg_dir = tmp.path().join("my_pkg");
    std::fs::create_dir_all(&pkg_dir).expect("create dir");
    std::fs::write(pkg_dir.join("init.lua"), "-- existing").expect("write existing");

    let target_dir = tmp.path().to_str().expect("utf-8 path").to_string();

    let outcome = client
        .call_tool(call_params(
            "alc_pkg_scaffold",
            json!({
                "name": "my_pkg",
                "target_dir": target_dir,
            }),
        ))
        .await;

    match outcome {
        Ok(result) => {
            let is_error = result.is_error.unwrap_or(false);
            let text = extract_text(&result);
            assert!(
                is_error,
                "expected is_error=true for AlreadyExists, got: is_error={is_error:?}, text: {text}"
            );
            assert!(
                text.contains("already exists"),
                "expected 'already exists' in error text, got: {text}"
            );
        }
        Err(e) => panic!("unexpected call_tool Err: {e}"),
    }

    client.cancel().await.expect("cancel failed");
}

/// NameInvalid error: empty name, digit-starting name, and slash name.
///
/// Each must produce `is_error = true` with text mentioning the problematic
/// name.
#[tokio::test]
async fn test_alc_pkg_scaffold_name_invalid() {
    let client = connect().await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let target_dir = tmp.path().to_str().expect("utf-8 path").to_string();

    for bad_name in &["", "1bad", "has/slash"] {
        let outcome = client
            .call_tool(call_params(
                "alc_pkg_scaffold",
                json!({
                    "name": bad_name,
                    "target_dir": target_dir,
                }),
            ))
            .await;

        match outcome {
            Ok(result) => {
                let is_error = result.is_error.unwrap_or(false);
                let text = extract_text(&result);
                assert!(
                    is_error,
                    "expected is_error=true for name={bad_name:?}, got text: {text}"
                );
                // The error message must contain "invalid" (from NameInvalid display).
                assert!(
                    text.contains("invalid"),
                    "expected 'invalid' in error text for name={bad_name:?}, got: {text}"
                );
            }
            Err(e) => panic!("unexpected call_tool Err for name={bad_name:?}: {e}"),
        }
    }

    client.cancel().await.expect("cancel failed");
}

/// Fixture-based E2E: `alc_hub_dist` where the single package has no
/// `alc_shapes_compat` field in `M.meta`.
///
/// Dist must succeed (backward compat), and the `gendoc.warnings` array
/// must contain the `"alc_shapes_compat not declared"` substring.
#[tokio::test]
async fn test_alc_hub_dist_compat_undeclared_warns() {
    let client = connect().await;

    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path();

    let fixture_src = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/hub_dist_sample_compat_undeclared");

    copy_fixture_tree(&fixture_src, root).expect("copy fixture");

    let source_dir = root.to_str().expect("utf-8 path").to_string();
    let output_path = root
        .join("hub_index.json")
        .to_str()
        .expect("utf-8 path")
        .to_string();
    let out_dir = root.join("docs").to_str().expect("utf-8 path").to_string();

    let resp = call_json(
        &client,
        "alc_hub_dist",
        json!({
            "source_dir":  source_dir,
            "output_path": output_path,
            "out_dir":     out_dir,
        }),
    )
    .await;

    assert!(
        resp.get("reindex").is_some(),
        "expected reindex field on undeclared compat success, got: {resp}"
    );
    assert!(
        resp.get("gendoc").is_some(),
        "expected gendoc field on undeclared compat success, got: {resp}"
    );

    // The gendoc.warnings array must contain the undeclared warning.
    let gendoc = resp.get("gendoc").expect("gendoc field present");
    let warnings = gendoc.get("warnings").expect("warnings field in gendoc");
    let warnings_str = warnings.to_string();
    assert!(
        warnings_str.contains("alc_shapes_compat not declared"),
        "expected 'alc_shapes_compat not declared' in warnings, got: {warnings_str}"
    );

    client.cancel().await.expect("cancel failed");
}

// ─── MCP Resources E2E ──────────────────────────────────────────

/// `resources/list` must return exactly 3 fixed resources.
#[tokio::test]
async fn test_mcp_resources_list_returns_two_fixed() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    let result = client
        .list_resources(None)
        .await
        .expect("list_resources failed");

    assert_eq!(
        result.resources.len(),
        3,
        "expected 3 fixed resources (types x2 + hub/index), got: {:?}",
        result
            .resources
            .iter()
            .map(|r| r.raw.uri.as_str())
            .collect::<Vec<_>>()
    );

    let uris: Vec<&str> = result
        .resources
        .iter()
        .map(|r| r.raw.uri.as_str())
        .collect();
    assert!(
        uris.contains(&"alc://types/alc.d.lua"),
        "expected alc://types/alc.d.lua in fixed list"
    );
    assert!(
        uris.contains(&"alc://types/alc_shapes.d.lua"),
        "expected alc://types/alc_shapes.d.lua in fixed list"
    );
    assert!(
        uris.contains(&"alc://hub/index"),
        "expected alc://hub/index in fixed list"
    );

    // Verify that at least one fixed resource has title populated (ST-1 field extension).
    assert!(
        result.resources.iter().any(|r| r.raw.title.is_some()),
        "expected at least one fixed resource to have a title field"
    );

    client.cancel().await.expect("cancel failed");
}

/// `resources/templates/list` must return exactly 7 templates.
#[tokio::test]
async fn test_mcp_resource_templates_list_returns_seven() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    let result = client
        .list_resource_templates(None)
        .await
        .expect("list_resource_templates failed");

    assert_eq!(
        result.resource_templates.len(),
        7,
        "expected 7 resource templates, got: {:?}",
        result
            .resource_templates
            .iter()
            .map(|t| t.raw.uri_template.as_str())
            .collect::<Vec<_>>()
    );

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://hub/index` on a clean install (no sources registered) returns
/// an empty packages array.
#[tokio::test]
async fn test_mcp_resource_read_hub_index_empty() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    // Fresh tempdir with no hub_registries.json and no cache files → packages empty.
    let result = read_resource(&client, "alc://hub/index")
        .await
        .expect("read alc://hub/index failed");

    assert_eq!(result.contents.len(), 1);
    let (uri, text) = resource_text(&result.contents[0]);
    assert_eq!(uri, "alc://hub/index");

    let parsed: serde_json::Value =
        serde_json::from_str(text).expect("hub/index response must be valid JSON");
    assert_eq!(
        parsed.get("schema_version").and_then(|v| v.as_str()),
        Some("hub_index/v0"),
        "schema_version must be hub_index/v0"
    );
    let packages = parsed
        .get("packages")
        .and_then(|p| p.as_array())
        .expect("packages must be an array");
    assert!(
        packages.is_empty(),
        "clean install must return empty packages, got: {packages:?}"
    );

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://hub/unknown` returns an error (invalid path).
#[tokio::test]
async fn test_mcp_resource_read_hub_unknown_path_errors() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    let params = ReadResourceRequestParams::new("alc://hub/unknown".to_string());
    let result = client.read_resource(params).await;
    assert!(
        result.is_err(),
        "alc://hub/unknown must return an error, got: {result:?}"
    );

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://types/alc.d.lua` when the file exists.
#[tokio::test]
async fn test_mcp_resource_read_types_alc_d_lua() {
    let tmp = tempfile::tempdir().expect("tempdir");

    let types_dir = tmp.path().join("types");
    std::fs::create_dir_all(&types_dir).expect("create types dir");
    std::fs::write(
        types_dir.join("alc.d.lua"),
        "-- alc type stubs\n---@class alc\nalc = {}\n",
    )
    .expect("write alc.d.lua");

    let client = connect_with_alc_home(tmp.path()).await;

    let result = read_resource(&client, "alc://types/alc.d.lua")
        .await
        .expect("read_resource alc.d.lua failed");

    assert_eq!(result.contents.len(), 1);
    let (uri, text) = resource_text(&result.contents[0]);
    assert!(
        text.contains("alc type stubs"),
        "unexpected content: {text}"
    );
    assert_eq!(uri, "alc://types/alc.d.lua");

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://types/alc_shapes.d.lua` when the file exists.
#[tokio::test]
async fn test_mcp_resource_read_types_alc_shapes_d_lua() {
    let tmp = tempfile::tempdir().expect("tempdir");

    let types_dir = tmp.path().join("types");
    std::fs::create_dir_all(&types_dir).expect("create types dir");
    std::fs::write(
        types_dir.join("alc_shapes.d.lua"),
        "-- alc_shapes type stubs\n",
    )
    .expect("write alc_shapes.d.lua");

    let client = connect_with_alc_home(tmp.path()).await;

    let result = read_resource(&client, "alc://types/alc_shapes.d.lua")
        .await
        .expect("read_resource alc_shapes.d.lua failed");

    assert_eq!(result.contents.len(), 1);
    let (_uri, text) = resource_text(&result.contents[0]);
    assert!(text.contains("alc_shapes"), "unexpected content: {text}");

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://packages/{name}/init.lua` when the package exists.
#[tokio::test]
async fn test_mcp_resource_read_pkg_init_lua() {
    let tmp = tempfile::tempdir().expect("tempdir");

    let pkg_dir = tmp.path().join("packages").join("my_e2e_pkg");
    std::fs::create_dir_all(&pkg_dir).expect("create pkg dir");
    std::fs::write(
        pkg_dir.join("init.lua"),
        "local M = {}\nM.meta = { name = 'my_e2e_pkg', version = '0.1.0' }\nreturn M\n",
    )
    .expect("write init.lua");

    let client = connect_with_alc_home(tmp.path()).await;

    let result = read_resource(&client, "alc://packages/my_e2e_pkg/init.lua")
        .await
        .expect("read_resource pkg init.lua failed");

    assert_eq!(result.contents.len(), 1);
    let (uri, text) = resource_text(&result.contents[0]);
    assert!(text.contains("my_e2e_pkg"), "unexpected content: {text}");
    assert_eq!(uri, "alc://packages/my_e2e_pkg/init.lua");

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://packages/{name}/meta` when a package is pre-installed in ALC_HOME.
///
/// The package directory is created before starting the server so that the
/// server's startup search-path resolution includes `$ALC_HOME/packages/`.
#[tokio::test]
async fn test_mcp_resource_read_pkg_meta() {
    let home_tmp = tempfile::tempdir().expect("home tempdir");

    // Pre-create the packages directory and the package so the server startup
    // includes it in `ALC_PACKAGES_PATH` search path resolution.
    let pkg_dir = home_tmp.path().join("packages").join("my_e2e_meta_pkg");
    std::fs::create_dir_all(&pkg_dir).expect("create pkg dir");
    std::fs::write(
        pkg_dir.join("init.lua"),
        concat!(
            "local M = {}\n",
            "M.meta = { name = 'my_e2e_meta_pkg', version = '0.2.0', description = 'test' }\n",
            "return M\n"
        ),
    )
    .expect("write init.lua");

    let client = connect_with_alc_home(home_tmp.path()).await;

    let result = read_resource(&client, "alc://packages/my_e2e_meta_pkg/meta")
        .await
        .expect("read_resource pkg meta failed");

    assert_eq!(result.contents.len(), 1);
    let (_uri, text) = resource_text(&result.contents[0]);
    let meta: Value = serde_json::from_str(text)
        .unwrap_or_else(|e| panic!("meta JSON parse failed: {e}\nraw: {text}"));
    assert_eq!(meta["name"], "my_e2e_meta_pkg");

    client.cancel().await.expect("cancel failed");
}

/// Read an unknown service → `McpError` returned to the client.
#[tokio::test]
async fn test_mcp_resource_read_unknown_uri_returns_error() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    let err = read_resource(&client, "alc://unknown/resource")
        .await
        .expect_err("expected error for unknown URI");

    let msg = err.to_string();
    assert!(
        !msg.is_empty(),
        "expected non-empty error for unknown URI, got empty"
    );

    client.cancel().await.expect("cancel failed");
}

/// Read a URI with an invalid scheme → `McpError` returned to the client.
#[tokio::test]
async fn test_mcp_resource_read_invalid_scheme_returns_error() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    let err = read_resource(&client, "https://example.com/foo")
        .await
        .expect_err("expected error for invalid scheme");

    let msg = err.to_string();
    assert!(
        !msg.is_empty(),
        "expected non-empty error for invalid scheme, got empty"
    );

    client.cancel().await.expect("cancel failed");
}

/// Read a URI with a path traversal segment → `McpError` returned.
#[tokio::test]
async fn test_mcp_resource_read_traversal_uri_returns_error() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    let err = read_resource(&client, "alc://types/../etc/passwd")
        .await
        .expect_err("expected error for traversal URI");

    let msg = err.to_string();
    assert!(
        !msg.is_empty(),
        "expected non-empty error for traversal URI, got empty"
    );

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://scenarios/{name}` when the scenario exists.
#[tokio::test]
async fn test_mcp_resource_read_scenario() {
    let tmp = tempfile::tempdir().expect("tempdir");

    let scenarios_dir = tmp.path().join("scenarios");
    std::fs::create_dir_all(&scenarios_dir).expect("create scenarios dir");
    std::fs::write(
        scenarios_dir.join("my_scenario.lua"),
        "-- scenario\nlocal S = {}\nS.cases = {}\nreturn S\n",
    )
    .expect("write scenario");

    let client = connect_with_alc_home(tmp.path()).await;

    let result = read_resource(&client, "alc://scenarios/my_scenario")
        .await
        .expect("read_resource scenario failed");

    assert_eq!(result.contents.len(), 1);
    let (_uri, text) = resource_text(&result.contents[0]);
    assert!(text.contains("scenario"), "unexpected content: {text}");

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://cards/{card_id}` for a pre-written card fixture.
#[tokio::test]
async fn test_mcp_resource_read_card() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let card_id = "mypkg_20260401T000000_aabbcc";
    let card_dir = tmp.path().join("cards").join("mypkg");
    std::fs::create_dir_all(&card_dir).expect("create card dir");
    std::fs::write(
        card_dir.join(format!("{card_id}.toml")),
        concat!(
            "schema_version = \"card/v0\"\n",
            "card_id = \"mypkg_20260401T000000_aabbcc\"\n",
            "created_at = \"2026-04-01T00:00:00Z\"\n",
            "[pkg]\n",
            "name = \"mypkg\"\n",
        ),
    )
    .expect("write card toml");

    let client = connect_with_alc_home(tmp.path()).await;

    let result = read_resource(&client, &format!("alc://cards/{card_id}"))
        .await
        .expect("read_resource card failed");

    assert_eq!(result.contents.len(), 1);
    let (_uri, text) = resource_text(&result.contents[0]);
    let card: Value = serde_json::from_str(text)
        .unwrap_or_else(|e| panic!("card JSON parse failed: {e}\nraw: {text}"));
    assert_eq!(card["card_id"], card_id);

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://cards/{card_id}/samples` with pagination, verifying response shape.
#[tokio::test]
async fn test_mcp_resource_read_card_samples_pagination() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let card_id = "mypkg_20260401T000000_aabbcc";
    let card_dir = tmp.path().join("cards").join("mypkg");
    std::fs::create_dir_all(&card_dir).expect("create card dir");
    std::fs::write(
        card_dir.join(format!("{card_id}.toml")),
        concat!(
            "schema_version = \"card/v0\"\n",
            "card_id = \"mypkg_20260401T000000_aabbcc\"\n",
            "created_at = \"2026-04-01T00:00:00Z\"\n",
            "[pkg]\n",
            "name = \"mypkg\"\n",
        ),
    )
    .expect("write card toml");
    // Write a two-row sidecar JSONL so pagination is exercisable.
    let jsonl = "{\"case_idx\":0,\"score\":1.0}\n{\"case_idx\":1,\"score\":0.5}\n";
    std::fs::write(card_dir.join(format!("{card_id}.samples.jsonl")), jsonl)
        .expect("write samples jsonl");

    let client = connect_with_alc_home(tmp.path()).await;

    let result = read_resource(
        &client,
        &format!("alc://cards/{card_id}/samples?offset=0&limit=2"),
    )
    .await
    .expect("read_resource card samples failed");

    assert_eq!(result.contents.len(), 1);
    let (_uri, text) = resource_text(&result.contents[0]);
    // Verify the response is valid JSON (array or object — implementation detail).
    let body: Value = serde_json::from_str(text)
        .unwrap_or_else(|e| panic!("samples JSON parse failed: {e}\nraw: {text}"));
    assert!(
        body.is_array() || body.is_object(),
        "expected JSON array or object response, got: {text}"
    );

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://eval/{result_id}` for a pre-written eval result fixture.
#[tokio::test]
async fn test_mcp_resource_read_eval_detail() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let eval_id = "mystrategy_1745000000";
    let evals_dir = tmp.path().join("evals");
    std::fs::create_dir_all(&evals_dir).expect("create evals dir");
    std::fs::write(
        evals_dir.join(format!("{eval_id}.json")),
        r#"{"eval_id":"mystrategy_1745000000","strategy":"mystrategy","pass_rate":0.8}"#,
    )
    .expect("write eval json");

    let client = connect_with_alc_home(tmp.path()).await;

    let result = read_resource(&client, &format!("alc://eval/{eval_id}"))
        .await
        .expect("read_resource eval detail failed");

    assert_eq!(result.contents.len(), 1);
    let (_uri, text) = resource_text(&result.contents[0]);
    let eval: Value = serde_json::from_str(text)
        .unwrap_or_else(|e| panic!("eval JSON parse failed: {e}\nraw: {text}"));
    assert_eq!(eval["eval_id"], eval_id);

    client.cancel().await.expect("cancel failed");
}

/// Read `alc://logs/{session_id}` with pagination params.
///
/// Log files are resolved via `ALC_LOG_DIR` (not `ALC_HOME/logs`), so we set
/// both env vars to ensure the server's `log_view` call finds the fixture.
#[tokio::test]
async fn test_mcp_resource_read_logs_pagination() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let session_id = "ses-e2e-log-test";
    let logs_dir = tmp.path().join("logs");
    std::fs::create_dir_all(&logs_dir).expect("create logs dir");
    // Write a minimal log JSON in the transcript format the server can parse.
    std::fs::write(
        logs_dir.join(format!("{session_id}.json")),
        r#"{"session_id":"ses-e2e-log-test","rounds":[]}"#,
    )
    .expect("write log json");

    let bin = std::env::var("CARGO_BIN_EXE_alc")
        .unwrap_or_else(|_| format!("{}/target/debug/alc", env!("CARGO_MANIFEST_DIR")));
    let packages_path = tmp.path().join("packages");
    let mut cmd = tokio::process::Command::new(bin);
    cmd.env("ALC_HOME", tmp.path())
        .env("ALC_PACKAGES_PATH", &packages_path)
        .env("ALC_LOG_DIR", &logs_dir);
    let transport = TokioChildProcess::new(cmd).expect("spawn alc server");
    let client = ().serve(transport).await.expect("initialize MCP session");

    let result = read_resource(
        &client,
        &format!("alc://logs/{session_id}?limit=10&max_chars=500"),
    )
    .await
    .expect("read_resource logs failed");

    assert_eq!(result.contents.len(), 1);
    let (_uri, text) = resource_text(&result.contents[0]);
    assert!(!text.is_empty(), "expected non-empty log response");

    client.cancel().await.expect("cancel failed");
}

// ─── alc_pkg_doctor — incomplete_pkg bucket ──────────────────────

/// Happy path: multi-file package with all subs present → `healthy` bucket.
///
/// Fixture layout:
///   source/e2e_doctor_complete/
///     init.lua   (requires "e2e_doctor_complete.sub")
///     sub.lua
///
/// After install via `alc_pkg_install`, doctor should classify the package as
/// `healthy` (all required submodule files are present).
#[tokio::test]
async fn test_pkg_doctor_multifile_healthy() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    // Build source package with init.lua + sub.lua.
    let source_root = tempfile::tempdir().expect("source tempdir");
    let pkg_src = source_root.path().join("e2e_doctor_complete");
    std::fs::create_dir_all(&pkg_src).expect("mkdir pkg_src");
    std::fs::write(
        pkg_src.join("init.lua"),
        r#"local M = {}
M.meta = { name = "e2e_doctor_complete", version = "0.1.0" }
local sub = require("e2e_doctor_complete.sub")
function M.run(ctx) return sub.hello() end
return M"#,
    )
    .expect("write init.lua");
    std::fs::write(
        pkg_src.join("sub.lua"),
        r#"return { hello = function() return "hi" end }"#,
    )
    .expect("write sub.lua");

    // Install the package into the isolated ALC_HOME.
    call_json(
        &client,
        "alc_pkg_install",
        json!({ "url": pkg_src.to_string_lossy() }),
    )
    .await;

    // Doctor should report the package as healthy.
    let resp = call_json(
        &client,
        "alc_pkg_doctor",
        json!({ "name": "e2e_doctor_complete" }),
    )
    .await;

    let healthy = resp["healthy"].as_array().expect("healthy array missing");
    assert!(
        healthy.iter().any(|e| e["name"] == "e2e_doctor_complete"),
        "e2e_doctor_complete should be in healthy bucket, got: {resp}"
    );
    let incomplete = resp["incomplete_pkg"]
        .as_array()
        .expect("incomplete_pkg array missing");
    assert!(
        incomplete.is_empty(),
        "incomplete_pkg should be empty for complete package, got: {resp}"
    );

    client.cancel().await.expect("cancel failed");
}

/// Defect path: init.lua requires a sibling submodule that is missing →
/// `incomplete_pkg` bucket with the sub name and a suggestion.
///
/// Fixture layout after install + manual removal:
///   packages/e2e_doctor_incomplete/
///     init.lua   (requires "e2e_doctor_incomplete.missing_sub")
///     (missing_sub.lua intentionally removed after install)
#[tokio::test]
async fn test_pkg_doctor_incomplete_pkg_detected() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    // Build source package with init.lua + missing_sub.lua.
    let source_root = tempfile::tempdir().expect("source tempdir");
    let pkg_src = source_root.path().join("e2e_doctor_incomplete");
    std::fs::create_dir_all(&pkg_src).expect("mkdir pkg_src");
    std::fs::write(
        pkg_src.join("init.lua"),
        r#"local M = {}
M.meta = { name = "e2e_doctor_incomplete", version = "0.1.0" }
local sub = require("e2e_doctor_incomplete.missing_sub")
function M.run(ctx) return sub.run(ctx) end
return M"#,
    )
    .expect("write init.lua");
    std::fs::write(
        pkg_src.join("missing_sub.lua"),
        r#"return { run = function(ctx) return "ok" end }"#,
    )
    .expect("write missing_sub.lua");

    // Install.
    call_json(
        &client,
        "alc_pkg_install",
        json!({ "url": pkg_src.to_string_lossy() }),
    )
    .await;

    // Simulate partial deletion: remove `missing_sub.lua` from the installed dest.
    let installed_dest = tmp.path().join("packages").join("e2e_doctor_incomplete");
    assert!(
        installed_dest.exists(),
        "package should be installed at {installed_dest:?}"
    );
    std::fs::remove_file(installed_dest.join("missing_sub.lua")).expect("remove missing_sub.lua");

    // Doctor should detect the incomplete package.
    let resp = call_json(
        &client,
        "alc_pkg_doctor",
        json!({ "name": "e2e_doctor_incomplete" }),
    )
    .await;

    let incomplete = resp["incomplete_pkg"]
        .as_array()
        .expect("incomplete_pkg array missing");
    let entry = incomplete
        .iter()
        .find(|e| e["name"] == "e2e_doctor_incomplete")
        .unwrap_or_else(|| {
            panic!("e2e_doctor_incomplete not in incomplete_pkg bucket, got: {resp}")
        });

    assert_eq!(entry["kind"], "incomplete_pkg", "kind field: {entry}");

    let missing = entry["missing_subs"]
        .as_array()
        .expect("missing_subs array missing");
    assert!(
        missing.iter().any(|s| s == "missing_sub"),
        "missing_subs should contain 'missing_sub', got: {missing:?}"
    );

    let suggestion = entry["suggestion"].as_str().unwrap_or("");
    assert!(
        !suggestion.is_empty(),
        "suggestion should not be empty: {entry}"
    );

    // healthy and installed_missing must NOT contain this package.
    let healthy = resp["healthy"].as_array().expect("healthy array");
    assert!(
        !healthy.iter().any(|e| e["name"] == "e2e_doctor_incomplete"),
        "incomplete pkg must not appear in healthy: {resp}"
    );

    client.cancel().await.expect("cancel failed");
}

// ─── state lost-update / Lua print safety ────────────────────────

/// Verify that concurrent `alc.state.set` calls on the same key do not
/// produce a lost update.
///
/// Two `alc_run` requests are issued in parallel via the same MCP
/// connection.  Each Lua snippet reads the current value of key `"c"`,
/// adds 1, and writes it back.  Without the per-namespace `Mutex`
/// introduced in `JsonFileStore`, one of the two writes would be
/// dropped when both reads observe the same initial value.
///
/// After both calls complete the key must equal 2.
#[tokio::test]
async fn test_state_no_lost_update_under_concurrent_writes() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    // Use a dedicated namespace via ctx._ns so the test is hermetic.
    // alc.state.incr is used here because its read-modify-write is fully
    // serialised by the per-namespace Mutex inside JsonFileStore.  A plain
    // get/set pair would require the Lua code to also run atomically, which
    // cannot be guaranteed across two independent MCP sessions — the sessions
    // themselves run concurrently but the Lua RMW within each is not atomic
    // unless backed by an atomic backend primitive.
    //
    // This test verifies that two concurrent incr(delta=1) calls on the same
    // key never produce a lost update: the final value must be exactly 2.
    let ns = "e2e_concurrent_state";
    let code = r#"return alc.state.incr("c", 1, 0)"#;

    // Fire both requests in parallel, both targeting the same namespace.
    let (r1, r2) = tokio::join!(
        call_json(
            &client,
            "alc_run",
            json!({ "code": code, "ctx": { "_ns": ns } })
        ),
        call_json(
            &client,
            "alc_run",
            json!({ "code": code, "ctx": { "_ns": ns } })
        ),
    );
    assert_eq!(r1["status"], "completed", "run 1 failed: {r1}");
    assert_eq!(r2["status"], "completed", "run 2 failed: {r2}");

    // Each call returns the value after its own increment.  The two returned
    // values must be {1, 2} (in any order) — never {1, 1} which would indicate
    // a lost update.
    let v1 = r1["result"]
        .as_f64()
        .unwrap_or_else(|| panic!("r1 result not a number: {r1}")) as u64;
    let v2 = r2["result"]
        .as_f64()
        .unwrap_or_else(|| panic!("r2 result not a number: {r2}")) as u64;
    let mut pair = [v1, v2];
    pair.sort();
    assert_eq!(
        pair,
        [1, 2],
        "expected incr results to be {{1, 2}} (no lost update), got {v1} and {v2}"
    );

    client.cancel().await.expect("cancel failed");
}

/// Verify that Lua `print(...)` does not corrupt the rmcp transport.
///
/// A user strategy calling `print("dbg")` should emit log output without
/// touching stdout.  The MCP connection must remain functional after the
/// call, i.e. a follow-up request to the same client must succeed.
#[tokio::test]
async fn test_lua_print_does_not_corrupt_transport() {
    let client = connect().await;

    // Run Lua that calls print() — this would corrupt the JSON-RPC transport
    // if print still wrote to stdout.
    let resp = call_json(
        &client,
        "alc_run",
        json!({ "code": r#"print("dbg: hello from lua"); return 42"# }),
    )
    .await;
    assert_eq!(
        resp["status"], "completed",
        "alc_run with print failed: {resp}"
    );
    assert_eq!(resp["result"], 42);

    // The transport must still be functional — issue a follow-up request.
    let resp2 = call_json(&client, "alc_run", json!({ "code": "return 99" })).await;
    assert_eq!(
        resp2["status"], "completed",
        "follow-up call failed: {resp2}"
    );
    assert_eq!(resp2["result"], 99);

    client.cancel().await.expect("cancel failed");
}

// ─── MCP completion/complete E2E ────────────────────────────────

/// Happy-path: `completion/complete` for `alc://packages/{name}/init.lua`
/// with an empty prefix and no packages installed returns a structurally
/// valid `CompleteResult` with `completion.values` as an array.
///
/// This test exercises the full MCP wire path:
///   client → `completion/complete` request → `ServerHandler::complete` →
///   `ResourceCatalog::complete_resource_arg` → `EngineApi::pkg_list` →
///   JSON → `CompleteResult { completion: CompletionInfo }`.
///
/// When the `packages/` directory is empty (isolated `ALC_HOME`), the
/// result must be `values: []` — not an error.  That confirms the handler
/// is wired and the wire shape is correct.
#[tokio::test]
async fn test_mcp_resources_complete_packages_empty_home() {
    let tmp = tempfile::tempdir().expect("tempdir");
    // Ensure packages dir exists so the server does not error on scan.
    std::fs::create_dir_all(tmp.path().join("packages")).expect("mkdir packages");

    let client = connect_with_alc_home(tmp.path()).await;

    let params = CompleteRequestParams::new(
        Reference::Resource(ResourceReference {
            uri: "alc://packages/{name}/init.lua".to_string(),
        }),
        ArgumentInfo {
            name: "name".to_string(),
            value: "".to_string(),
        },
    );

    let result = client
        .complete(params)
        .await
        .expect("completion/complete failed");

    // Wire shape: completion.values must be a Vec (possibly empty).
    assert!(
        result.completion.values.len() <= 100,
        "values length must not exceed cap=100, got {}",
        result.completion.values.len()
    );
    // All values must be non-empty strings.
    for v in &result.completion.values {
        assert!(!v.is_empty(), "completion value must not be empty string");
    }
    // When values is empty, has_more must not be true.
    if result.completion.values.is_empty() {
        assert_ne!(
            result.completion.has_more,
            Some(true),
            "has_more must not be true when values is empty"
        );
    }

    client.cancel().await.expect("cancel failed");
}

/// When a package is pre-installed in `ALC_HOME/packages/`, the completion
/// result for `alc://packages/{name}/init.lua` must include it in `values`.
///
/// This confirms the EngineApi → JSON → completion dispatch chain returns
/// real data end-to-end across the MCP wire.
#[tokio::test]
async fn test_mcp_resources_complete_packages_returns_installed_name() {
    let tmp = tempfile::tempdir().expect("tempdir");

    // Pre-install a package so pkg_list returns it.
    let pkg_dir = tmp.path().join("packages").join("e2e_complete_test_pkg");
    std::fs::create_dir_all(&pkg_dir).expect("mkdir pkg");
    std::fs::write(
        pkg_dir.join("init.lua"),
        concat!(
            "local M = {}\n",
            "M.meta = { name = 'e2e_complete_test_pkg', version = '0.1.0' }\n",
            "return M\n",
        ),
    )
    .expect("write init.lua");

    let client = connect_with_alc_home(tmp.path()).await;

    let params = CompleteRequestParams::new(
        Reference::Resource(ResourceReference {
            uri: "alc://packages/{name}/init.lua".to_string(),
        }),
        ArgumentInfo {
            name: "name".to_string(),
            value: "".to_string(),
        },
    );

    let result = client
        .complete(params)
        .await
        .expect("completion/complete failed");

    assert!(
        result
            .completion
            .values
            .iter()
            .any(|v| v == "e2e_complete_test_pkg"),
        "expected 'e2e_complete_test_pkg' in completion values, got: {:?}",
        result.completion.values
    );
    // total must be Some and ≥ 1 when values are present.
    assert!(
        result.completion.total.unwrap_or(0) >= 1,
        "expected total >= 1 when at least one package is installed"
    );

    client.cancel().await.expect("cancel failed");
}

/// Prefix filtering: when the prefix `"e2e_c"` is provided, only packages
/// whose names start with that prefix must appear in the completion values.
///
/// This verifies that `complete_resource_arg` passes the prefix down and
/// filters correctly.
#[tokio::test]
async fn test_mcp_resources_complete_packages_prefix_filter() {
    let tmp = tempfile::tempdir().expect("tempdir");

    // Install two packages: one matching the prefix, one not.
    for name in &["e2e_c_alpha", "other_pkg"] {
        let dir = tmp.path().join("packages").join(name);
        std::fs::create_dir_all(&dir).expect("mkdir");
        std::fs::write(
            dir.join("init.lua"),
            format!(
                "local M = {{}}\nM.meta = {{ name = '{}', version = '0.1.0' }}\nreturn M\n",
                name
            ),
        )
        .expect("write init.lua");
    }

    let client = connect_with_alc_home(tmp.path()).await;

    let params = CompleteRequestParams::new(
        Reference::Resource(ResourceReference {
            uri: "alc://packages/{name}/init.lua".to_string(),
        }),
        ArgumentInfo {
            name: "name".to_string(),
            value: "e2e_c".to_string(),
        },
    );

    let result = client
        .complete(params)
        .await
        .expect("completion/complete failed");

    // e2e_c_alpha starts with "e2e_c" → must appear.
    assert!(
        result.completion.values.iter().any(|v| v == "e2e_c_alpha"),
        "expected 'e2e_c_alpha' in completion values for prefix 'e2e_c', got: {:?}",
        result.completion.values
    );
    // other_pkg does NOT start with "e2e_c" → must not appear.
    assert!(
        !result.completion.values.iter().any(|v| v == "other_pkg"),
        "unexpected 'other_pkg' in filtered completion values: {:?}",
        result.completion.values
    );

    client.cancel().await.expect("cancel failed");
}

/// E2E: `alc://hub/index` with a corrupt cache file emits a `warnings` array.
///
/// Sets up an isolated `ALC_HOME` with:
/// - A `hub_registries.json` pointing to two source URLs.
/// - A valid `hub_cache/{key}.json` for the first URL (contains "good_pkg").
/// - An invalid JSON `hub_cache/{key}.json` for the second URL (corrupt).
///
/// Reading `alc://hub/index` must:
/// - Return valid JSON with `packages` containing entries from the valid source.
/// - Include a `warnings` array mentioning the corrupt source URL.
#[tokio::test]
async fn test_alc_hub_index_aggregate_warnings_emitted_on_corrupt_cache() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let alc_home = tmp.path();

    let url_good = "https://good.example.com/index.json";
    let url_bad = "https://bad-corrupt.example.com/index.json";

    // FNV-1a cache key (matches hub.rs::cache_key)
    fn fnv1a_hex(url: &str) -> String {
        let mut h: u64 = 0xcbf2_9ce4_8422_2325u64;
        for b in url.as_bytes() {
            h ^= *b as u64;
            h = h.wrapping_mul(0x0100_0000_01b3u64);
        }
        format!("{h:016x}")
    }

    let hub_cache_dir = alc_home.join("hub_cache");
    std::fs::create_dir_all(&hub_cache_dir).expect("mkdir hub_cache");

    // Write a valid cache for the good URL.
    // IndexEntry uses #[serde(flatten)] on entity, so pkg fields are top-level.
    let good_index = serde_json::json!({
        "schema_version": "hub_index/v0",
        "updated_at": "2026-01-01T00:00:00Z",
        "packages": [{
            "name": "good_pkg",
            "version": "0.1.0",
            "source": { "type": "unknown" },
            "card_count": 0
        }]
    });
    std::fs::write(
        hub_cache_dir.join(format!("{}.json", fnv1a_hex(url_good))),
        serde_json::to_string(&good_index).expect("serialize"),
    )
    .expect("write good cache");

    // Write corrupt JSON for the bad URL.
    std::fs::write(
        hub_cache_dir.join(format!("{}.json", fnv1a_hex(url_bad))),
        b"{{{{ definitely not valid json",
    )
    .expect("write corrupt cache");

    // Register both URLs in hub_registries.json.
    let reg_json = serde_json::json!({
        "registries": [
            { "source": url_good, "origin": "pkg_install", "added_at": "2026-01-01T00:00:00Z" },
            { "source": url_bad,  "origin": "pkg_install", "added_at": "2026-01-01T00:00:00Z" }
        ]
    });
    std::fs::write(
        alc_home.join("hub_registries.json"),
        serde_json::to_string(&reg_json).expect("serialize"),
    )
    .expect("write hub_registries");

    let client = connect_with_alc_home(alc_home).await;
    let result = read_resource(&client, "alc://hub/index")
        .await
        .expect("read alc://hub/index failed");

    assert_eq!(result.contents.len(), 1);
    let (uri, text) = resource_text(&result.contents[0]);
    assert_eq!(uri, "alc://hub/index");

    let body: Value = serde_json::from_str(text)
        .unwrap_or_else(|e| panic!("hub/index JSON parse failed: {e}\nraw: {text}"));

    // packages must contain entries from the valid source.
    // IndexEntry uses #[serde(flatten)] so package fields are at top level.
    let packages = body["packages"].as_array().expect("packages must be array");
    let has_good_pkg = packages
        .iter()
        .any(|p| p["name"].as_str() == Some("good_pkg"));
    assert!(
        has_good_pkg,
        "expected good_pkg from valid source, got packages: {packages:?}"
    );

    // warnings must be non-empty and mention the corrupt URL.
    let warnings = body["warnings"].as_array().expect("warnings must be array");
    assert!(
        !warnings.is_empty(),
        "expected non-empty warnings array, got: {body}"
    );
    let bad_url_mentioned = warnings.iter().any(|w| {
        w.as_str()
            .map(|s| s.contains("bad-corrupt.example.com"))
            .unwrap_or(false)
    });
    assert!(
        bad_url_mentioned,
        "expected warning to mention the corrupt URL, got warnings: {warnings:?}"
    );

    client.cancel().await.expect("cancel failed");
}

/// E2E: `completion/complete` for a resource template arg name that the server
/// does not provide candidates for must return a non-error response with
/// `values: []`, `total: 0`, and `has_more: false`.
///
/// Uses `alc://logs/{session_id}` with arg `session_id` — the handler
/// explicitly returns empty for the `logs` domain (no session-list API).
#[tokio::test]
async fn test_mcp_resources_complete_returns_empty_for_unsupported_arg_name() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    let params = CompleteRequestParams::new(
        Reference::Resource(ResourceReference {
            uri: "alc://logs/{session_id}".to_string(),
        }),
        ArgumentInfo {
            name: "session_id".to_string(),
            value: "".to_string(),
        },
    );

    let result = client
        .complete(params)
        .await
        .expect("completion/complete for logs domain must not error");

    assert!(
        result.completion.values.is_empty(),
        "expected empty values for logs domain (no session-list API), got: {:?}",
        result.completion.values
    );
    assert_eq!(
        result.completion.total,
        Some(0),
        "expected total=0 for empty completion, got: {:?}",
        result.completion.total
    );
    assert_ne!(
        result.completion.has_more,
        Some(true),
        "has_more must not be true when values is empty"
    );

    client.cancel().await.expect("cancel failed");
}

/// `ref/prompt` reference must return an empty completion result without error.
///
/// The handler's `Reference::Prompt` branch returns `CompletionInfo::default()`
/// (empty values, no total/has_more).  This confirms the branch is reachable
/// end-to-end without panic or MCP error.
#[tokio::test]
async fn test_mcp_resources_complete_prompt_ref_returns_empty() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let client = connect_with_alc_home(tmp.path()).await;

    let params = CompleteRequestParams::new(
        Reference::for_prompt("nonexistent_prompt"),
        ArgumentInfo {
            name: "arg".to_string(),
            value: "".to_string(),
        },
    );

    let result = client
        .complete(params)
        .await
        .expect("completion/complete for prompt ref must not error");

    assert!(
        result.completion.values.is_empty(),
        "expected empty values for prompt ref, got: {:?}",
        result.completion.values
    );

    client.cancel().await.expect("cancel failed");
}