algocline 0.25.1

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
//! 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::CallToolRequestParams, 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,
    };
    CallToolRequestParams {
        name: Cow::Owned(name.to_string()),
        arguments,
        meta: None,
        task: None,
    }
}

/// Build `CallToolRequestParams` with no arguments.
fn call_params_empty(name: &str) -> CallToolRequestParams {
    CallToolRequestParams {
        name: Cow::Owned(name.to_string()),
        arguments: Some(Map::new()),
        meta: None,
        task: None,
    }
}

/// 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))
}

/// 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");
}

/// `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");
}

/// Typed-error case: requesting the `context7` projection without a
/// `config_path` must surface as a handler-level error (MCP caller sees
/// `is_error=true` + text mentioning `config_path`).
#[tokio::test]
async fn test_alc_hub_gendoc_missing_config() {
    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 gets past its "read index"
    // step and can reach the projection-config validation.
    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 missing config_path, got is_error={is_error:?}, text: {text}"
            );
            assert!(
                text.contains("config_path"),
                "expected error text to mention config_path, 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");
}

#[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 context7
    // projection requires config_path.
    let outcome = client
        .call_tool(call_params(
            "alc_hub_dist",
            json!({
                "source_dir": source_dir,
                "output_path": output_path,
                "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 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");

    // Helper: recursively copy a directory tree.
    fn copy_dir_all(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_dir_all(&entry.path(), &dst.join(entry.file_name()))?;
            } else {
                std::fs::copy(entry.path(), dst.join(entry.file_name()))?;
            }
        }
        Ok(())
    }

    copy_dir_all(&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");

    fn copy_dir_all(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_dir_all(&entry.path(), &dst.join(entry.file_name()))?;
            } else {
                std::fs::copy(entry.path(), dst.join(entry.file_name()))?;
            }
        }
        Ok(())
    }

    copy_dir_all(&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");

    fn copy_dir_all(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_dir_all(&entry.path(), &dst.join(entry.file_name()))?;
            } else {
                std::fs::copy(entry.path(), dst.join(entry.file_name()))?;
            }
        }
        Ok(())
    }

    copy_dir_all(&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");
}

/// 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");
}