algocline-app 0.44.2

algocline application layer — execution orchestration, package management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
//! Integration-style tests for the `pkg_*` methods on `AppService`.

use crate::service::list_opts::ListOpts;
use crate::service::lockfile::{load_lockfile, LockFile, LockPackage};
use crate::service::source::PackageSource;
use crate::service::test_support::{
    make_app_service, make_app_service_at, make_app_service_at_with_search_paths,
    make_app_service_with_search_paths,
};

/// Build a `ListOpts` for tests. All fields default to `None`; override
/// individual fields with struct-update syntax.
fn opts() -> ListOpts {
    ListOpts {
        limit: None,
        sort: None,
        filter: None,
        fields: None,
        verbose: None,
    }
}

/// Build a filter `HashMap` from a `serde_json::json!({...})` value.
/// Panics if the value is not a JSON object.
fn filter_map(v: serde_json::Value) -> std::collections::HashMap<String, serde_json::Value> {
    v.as_object()
        .expect("filter must be a JSON object")
        .iter()
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect()
}

fn make_lock_with_pkg(name: &str) -> LockFile {
    LockFile {
        version: 1,
        packages: vec![LockPackage {
            name: name.to_string(),
            version: None,
            source: PackageSource::Installed,
        }],
    }
}

/// Test helper: invoke `pkg_list` with the default summary preset.
///
/// Use this when the test only asserts on summary-preset fields
/// (`name`, `scope`, `version`, `active`, `resolved_source_path`,
/// `resolved_source_kind`).
async fn pkg_list_summary(
    svc: &crate::service::AppService,
    project_root: Option<String>,
) -> String {
    svc.pkg_list(project_root, opts()).await.unwrap()
}

/// Test helper: invoke `pkg_list` with `verbose="full"`.
///
/// Use this when the test asserts on full-preset-only fields
/// (`source_type`, `installed_at`, `install_source`, `override_paths`,
/// `overrides`, `linked`, `link_target`, `broken`, `path`, `source`,
/// `meta`, `error`, `updated_at`).
async fn pkg_list_full(svc: &crate::service::AppService, project_root: Option<String>) -> String {
    svc.pkg_list(
        project_root,
        ListOpts {
            verbose: Some("full".to_string()),
            ..opts()
        },
    )
    .await
    .unwrap()
}

// ── pkg_list tests ───────────────────────────────────────────

#[tokio::test]
async fn pkg_list_with_project() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    // Create alc.toml declaring the project-local package.
    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\nmy_local_pkg = \"*\"\n",
    )
    .unwrap();

    // Create a project-local package.
    let pkg_dir = project_root.join("my_local_pkg");
    std::fs::create_dir_all(&pkg_dir).unwrap();
    std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

    // Write alc.lock with a Path entry for the package.
    let lock = LockFile {
        version: 1,
        packages: vec![LockPackage {
            name: "my_local_pkg".to_string(),
            version: None,
            source: PackageSource::Path {
                path: "my_local_pkg".to_string(),
            },
        }],
    };
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();

    let svc = make_app_service().await;
    let result = svc
        .pkg_list(
            Some(project_root.to_string_lossy().to_string()),
            ListOpts {
                verbose: Some("full".to_string()),
                ..opts()
            },
        )
        .await
        .unwrap();

    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    // Should have the project-local package.
    let project_pkg = packages
        .iter()
        .find(|p| p["name"] == "my_local_pkg")
        .expect("my_local_pkg not found in pkg_list output");

    assert_eq!(project_pkg["scope"], "project");
    assert_eq!(project_pkg["source_type"], "path");
    assert_eq!(project_pkg["active"], true);

    // project_root and lockfile_path must be present.
    assert!(json["project_root"].is_string());
    assert!(json["lockfile_path"].is_string());
}

#[tokio::test]
async fn pkg_list_no_project_root() {
    let svc = make_app_service().await;

    // Should succeed even without project_root (no crash).
    let result = pkg_list_summary(&svc, None).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    assert!(json["packages"].is_array());
}

// ── ST2: ListOpts wiring tests ───────────────────────────────
//
// These exercise the new list-tool pipeline (filter / sort / truncate /
// project_fields) introduced in ST2. They rely on a small synthetic
// fixture: a project root with N declared packages, each with its own
// vendor directory, registered via `alc.toml` + `alc.lock` (path
// entries). This keeps every entry deterministic and timezone-free.

/// Build a project_root with the given (`name`, `installed_at`) pairs.
///
/// Each package is created as a `path` entry in alc.toml + alc.lock.
/// `installed_at` is recorded into `alc.local.toml` under a stub
/// `manifest`-like field — but the `pkg_list` codepath populates
/// `installed_at` only from `installed.json` (manifest), which is
/// unrelated to project-local entries. So in these synthetic tests
/// `installed_at` is always `None` for project entries; we instead
/// exercise sort / filter on `name`, `scope`, and `active`.
async fn build_project_with_pkgs(
    project_root: &std::path::Path,
    names: &[&str],
) -> crate::service::AppService {
    let mut alc_toml = String::from("[packages]\n");
    let mut lock_pkgs = Vec::new();
    for name in names {
        alc_toml.push_str(&format!("{name} = {{ path = \"{name}\" }}\n"));
        let pkg_dir = project_root.join(name);
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();
        lock_pkgs.push(LockPackage {
            name: (*name).to_string(),
            version: None,
            source: PackageSource::Path {
                path: (*name).to_string(),
            },
        });
    }
    std::fs::write(project_root.join("alc.toml"), alc_toml).unwrap();
    let lock = LockFile {
        version: 1,
        packages: lock_pkgs,
    };
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();
    make_app_service().await
}

/// Default summary preset must NOT include `install_source`.
#[tokio::test]
async fn pkg_list_summary_excludes_install_source() {
    let tmp = tempfile::tempdir().unwrap();
    let svc = build_project_with_pkgs(tmp.path(), &["alpha"]).await;
    let result = pkg_list_summary(&svc, Some(tmp.path().to_string_lossy().to_string())).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();
    let pkg = packages.iter().find(|p| p["name"] == "alpha").unwrap();
    let map = pkg.as_object().unwrap();
    assert!(
        !map.contains_key("install_source"),
        "install_source must be absent from summary preset, got: {map:?}"
    );
}

/// Summary preset includes `resolved_source_path` (the primary "where is
/// this package on disk" signal).
#[tokio::test]
async fn pkg_list_summary_includes_resolved_source_path() {
    let tmp = tempfile::tempdir().unwrap();
    let svc = build_project_with_pkgs(tmp.path(), &["alpha"]).await;
    let result = pkg_list_summary(&svc, Some(tmp.path().to_string_lossy().to_string())).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();
    let pkg = packages.iter().find(|p| p["name"] == "alpha").unwrap();
    assert!(
        pkg["resolved_source_path"].is_string(),
        "resolved_source_path must appear under summary preset"
    );
}

/// `verbose=full` brings back the extended fields: `path` is in the full
/// preset and is populated for project `path` entries.
#[tokio::test]
async fn pkg_list_verbose_full_includes_install_source() {
    let tmp = tempfile::tempdir().unwrap();
    let svc = build_project_with_pkgs(tmp.path(), &["alpha"]).await;
    // For project-local `path` entries `install_source` is None — the
    // field is only populated from installed.json (global packages).
    // Use `path` as the proxy "full-only" field that *is* set for these
    // synthetic entries.
    let result = pkg_list_full(&svc, Some(tmp.path().to_string_lossy().to_string())).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();
    let pkg = packages.iter().find(|p| p["name"] == "alpha").unwrap();
    let map = pkg.as_object().unwrap();
    assert!(
        map.contains_key("path"),
        "path must reappear under verbose=full, got: {map:?}"
    );
    assert!(
        map.contains_key("source_type"),
        "source_type must reappear under verbose=full, got: {map:?}"
    );
}

/// When both `fields` and `verbose` are supplied, `fields` wins.
#[tokio::test]
async fn pkg_list_fields_beats_verbose() {
    let tmp = tempfile::tempdir().unwrap();
    let svc = build_project_with_pkgs(tmp.path(), &["alpha"]).await;
    let result = svc
        .pkg_list(
            Some(tmp.path().to_string_lossy().to_string()),
            ListOpts {
                fields: Some(vec!["name".to_string()]),
                verbose: Some("full".to_string()),
                ..opts()
            },
        )
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();
    let pkg = packages.iter().find(|p| p["name"] == "alpha").unwrap();
    let map = pkg.as_object().unwrap();
    assert_eq!(map.len(), 1, "exact projection: only 'name' should survive");
    assert!(map.contains_key("name"));
}

/// Default sort `-active,-installed_at` puts `active=true` entries first.
///
/// Synthetic setup: declare two project packages and one variant pkg that
/// shadows one of them. The shadowed project entry becomes
/// `active=false`, the variant + the unshadowed project are
/// `active=true`. With default sort (`-active`), all `active=true`
/// entries must come before any `active=false` entry.
#[tokio::test]
async fn pkg_list_sort_active_desc_installed_at() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    // Two project packages.
    let svc = build_project_with_pkgs(project_root, &["alpha", "beta"]).await;

    // Variant pkg shadowing `alpha` so the project alpha entry becomes
    // active=false.
    let variant_dir = tmp.path().join("variant_src").join("alpha");
    std::fs::create_dir_all(&variant_dir).unwrap();
    std::fs::write(variant_dir.join("init.lua"), "return {}").unwrap();
    std::fs::write(
        project_root.join("alc.local.toml"),
        format!(
            "[packages]\nalpha = {{ path = \"{}\" }}\n",
            variant_dir.display()
        ),
    )
    .unwrap();

    let result = pkg_list_summary(&svc, Some(project_root.to_string_lossy().to_string())).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    // Walk the array and check no active=false comes before any active=true.
    let mut seen_inactive = false;
    for pkg in packages {
        let active = pkg["active"].as_bool().unwrap_or(false);
        if !active {
            seen_inactive = true;
        } else if seen_inactive {
            panic!(
                "default sort should put active=true before active=false; \
                 saw active=true after active=false in {packages:?}"
            );
        }
    }
}

/// `filter={"scope":"global"}` excludes project entries.
#[tokio::test]
async fn pkg_list_filter_by_scope() {
    let tmp = tempfile::tempdir().unwrap();
    let svc = build_project_with_pkgs(tmp.path(), &["alpha", "beta"]).await;
    let filter = serde_json::json!({"scope": "global"});
    let result = svc
        .pkg_list(
            Some(tmp.path().to_string_lossy().to_string()),
            ListOpts {
                filter: Some(filter_map(filter)),
                ..opts()
            },
        )
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();
    for pkg in packages {
        assert_ne!(
            pkg["scope"], "project",
            "filter scope=global must exclude project entries, got: {pkg:?}"
        );
    }
}

/// `filter={"active":true}` excludes inactive entries.
#[tokio::test]
async fn pkg_list_filter_by_active_true() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();
    let svc = build_project_with_pkgs(project_root, &["alpha"]).await;

    // Variant shadowing alpha so the project alpha becomes inactive.
    let variant_dir = tmp.path().join("variant_src").join("alpha");
    std::fs::create_dir_all(&variant_dir).unwrap();
    std::fs::write(variant_dir.join("init.lua"), "return {}").unwrap();
    std::fs::write(
        project_root.join("alc.local.toml"),
        format!(
            "[packages]\nalpha = {{ path = \"{}\" }}\n",
            variant_dir.display()
        ),
    )
    .unwrap();

    let filter = serde_json::json!({"active": true});
    let result = svc
        .pkg_list(
            Some(project_root.to_string_lossy().to_string()),
            ListOpts {
                filter: Some(filter_map(filter)),
                ..opts()
            },
        )
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();
    for pkg in packages {
        assert_eq!(
            pkg["active"], true,
            "filter active=true must exclude inactive entries, got: {pkg:?}"
        );
    }
}

/// `limit=5` truncates the `packages` array to at most 5 entries.
#[tokio::test]
async fn pkg_list_limit_truncates() {
    let tmp = tempfile::tempdir().unwrap();
    let svc = build_project_with_pkgs(
        tmp.path(),
        &[
            "pkg_a", "pkg_b", "pkg_c", "pkg_d", "pkg_e", "pkg_f", "pkg_g",
        ],
    )
    .await;
    let result = svc
        .pkg_list(
            Some(tmp.path().to_string_lossy().to_string()),
            ListOpts {
                limit: Some(5),
                ..opts()
            },
        )
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();
    assert!(
        packages.len() <= 5,
        "limit=5 must truncate the array, got {} entries",
        packages.len()
    );
}

/// `limit=N` truncates `packages` but `search_paths` / `project_root` /
/// `lockfile_path` top-level keys remain present.
#[tokio::test]
async fn pkg_list_limit_preserves_top_level_shape() {
    let tmp = tempfile::tempdir().unwrap();
    let svc = build_project_with_pkgs(tmp.path(), &["pkg_a", "pkg_b", "pkg_c"]).await;
    let result = svc
        .pkg_list(
            Some(tmp.path().to_string_lossy().to_string()),
            ListOpts {
                limit: Some(1),
                ..opts()
            },
        )
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    assert!(
        json["search_paths"].is_array(),
        "search_paths must remain after limit truncation"
    );
    assert!(
        json["project_root"].is_string(),
        "project_root must remain after limit truncation"
    );
    assert!(
        json["lockfile_path"].is_string(),
        "lockfile_path must remain after limit truncation"
    );
    let packages = json["packages"].as_array().unwrap();
    assert!(packages.len() <= 1);
}

/// Unknown field names in `fields` are silently skipped (JSON:API
/// sparse fieldsets convention).
#[tokio::test]
async fn pkg_list_unknown_field_silently_skipped() {
    let tmp = tempfile::tempdir().unwrap();
    let svc = build_project_with_pkgs(tmp.path(), &["alpha"]).await;
    let result = svc
        .pkg_list(
            Some(tmp.path().to_string_lossy().to_string()),
            ListOpts {
                fields: Some(vec!["name".to_string(), "bogus_field".to_string()]),
                ..opts()
            },
        )
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();
    let pkg = packages.iter().find(|p| p["name"] == "alpha").unwrap();
    let map = pkg.as_object().unwrap();
    assert!(map.contains_key("name"));
    assert!(
        !map.contains_key("bogus_field"),
        "unknown field must be silently skipped, got: {map:?}"
    );
    assert_eq!(
        map.len(),
        1,
        "only known fields should appear, got: {map:?}"
    );
}

/// Invalid sort string (empty / dash-only) must produce an error
/// before any IO is done. Defends the `parse_sort` short-circuit.
#[tokio::test]
async fn pkg_list_invalid_sort_returns_error() {
    let tmp = tempfile::tempdir().unwrap();
    let svc = build_project_with_pkgs(tmp.path(), &["alpha"]).await;
    let result = svc
        .pkg_list(
            Some(tmp.path().to_string_lossy().to_string()),
            ListOpts {
                sort: Some("-".to_string()),
                ..opts()
            },
        )
        .await;
    assert!(
        result.is_err(),
        "bare '-' sort string must be rejected, got: {result:?}"
    );
}

/// Invalid `verbose` value must produce an error before IO.
#[tokio::test]
async fn pkg_list_invalid_verbose_returns_error() {
    let tmp = tempfile::tempdir().unwrap();
    let svc = build_project_with_pkgs(tmp.path(), &["alpha"]).await;
    let result = svc
        .pkg_list(
            Some(tmp.path().to_string_lossy().to_string()),
            ListOpts {
                verbose: Some("fat".to_string()),
                ..opts()
            },
        )
        .await;
    assert!(
        result.is_err(),
        "verbose='fat' must be rejected, got: {result:?}"
    );
}

// ── pkg_remove tests ─────────────────────────────────────────

#[tokio::test]
async fn pkg_remove_project_scope() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    // Create alc.toml declaring the package to remove.
    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\nmy_local_pkg = \"*\"\n",
    )
    .unwrap();

    // Create the physical directory (should remain after removal).
    let pkg_dir = project_root.join("my_local_pkg");
    std::fs::create_dir_all(&pkg_dir).unwrap();
    std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

    // Write alc.lock with the package.
    let lock = LockFile {
        version: 1,
        packages: vec![LockPackage {
            name: "my_local_pkg".to_string(),
            version: None,
            source: PackageSource::Path {
                path: "my_local_pkg".to_string(),
            },
        }],
    };
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();

    let svc = make_app_service().await;
    let result = svc
        .pkg_remove(
            "my_local_pkg",
            Some(project_root.to_string_lossy().to_string()),
            None, // version
            None, // scope → default "project"
        )
        .await
        .unwrap();

    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    assert_eq!(json["removed"], "my_local_pkg");
    // New response has alc_toml and alc_lock fields (no scope field).
    assert!(json["alc_toml"].is_string());
    assert!(json["alc_lock"].is_string());

    // Physical directory must still exist.
    assert!(pkg_dir.exists(), "physical directory was deleted");

    // alc.lock must no longer contain the entry.
    let lock_after = load_lockfile(project_root).unwrap().unwrap();
    assert!(
        lock_after.packages.is_empty(),
        "alc.lock still contains the entry"
    );
}

#[tokio::test]
async fn pkg_remove_project_scope_not_found_returns_error() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    // Create alc.toml with a different package (not the target).
    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\nother_pkg = \"*\"\n",
    )
    .unwrap();

    // Write an alc.lock without the target package.
    let lock = make_lock_with_pkg("other_pkg");
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();

    let svc = make_app_service().await;
    let result = svc
        .pkg_remove(
            "nonexistent_pkg",
            Some(project_root.to_string_lossy().to_string()),
            None, // version
            None, // scope → default "project"
        )
        .await;

    assert!(result.is_err());
    assert!(result.unwrap_err().contains("not found in alc.lock"));
}

// ── pkg_remove scope=global / all tests ─────────────────────

/// `scope = "global"` removes the entry from `~/.algocline/installed.json`
/// but leaves `~/.algocline/packages/{name}/` untouched. No `project_root`
/// needed.
#[tokio::test]
async fn pkg_remove_global_scope_removes_manifest_entry() {
    use crate::service::manifest::{load_manifest, record_install};

    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();
    let app_dir = crate::service::test_support::test_app_dir(home);

    record_install(
        &app_dir,
        "ghost_pkg",
        Some("0.1.0"),
        crate::service::source::PackageSource::Path {
            path: "/tmp/ghost_source".to_string(),
        },
    )
    .unwrap();
    assert!(load_manifest(&app_dir)
        .unwrap()
        .packages
        .contains_key("ghost_pkg"));

    let svc = make_app_service_at(home.to_path_buf()).await;
    let result = svc
        .pkg_remove(
            "ghost_pkg",
            None, // project_root — ignored for global scope
            None, // version
            Some("global".to_string()),
        )
        .await
        .unwrap();

    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    assert_eq!(json["removed"], "ghost_pkg");
    assert_eq!(json["scope"], "global");
    assert!(json["installed_json"].is_string());

    assert!(
        !load_manifest(&app_dir)
            .unwrap()
            .packages
            .contains_key("ghost_pkg"),
        "global manifest still contains the entry"
    );
}

/// `scope = "global"` errors when the name is not in the manifest so callers
/// cannot silently no-op on a typo. Mirrors the `alc.lock` authoritative
/// check in `scope = "project"`.
#[tokio::test]
async fn pkg_remove_global_scope_not_found_returns_error() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    let svc = make_app_service_at(home.to_path_buf()).await;
    let result = svc
        .pkg_remove("never_installed", None, None, Some("global".to_string()))
        .await;

    let err = result.expect_err("expected Err");
    assert!(
        err.contains("not found in global manifest"),
        "unexpected error: {err}"
    );
}

/// `scope = "global"` must not `rm -rf ~/.algocline/packages/{name}/`.
/// Symmetric with the project scope's "physical files preserved" policy.
#[tokio::test]
async fn pkg_remove_global_scope_preserves_physical_dir() {
    use crate::service::manifest::record_install;

    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();
    let pkg_dir = home.join("packages").join("kept");
    std::fs::create_dir_all(&pkg_dir).unwrap();
    std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

    let app_dir = crate::service::test_support::test_app_dir(home);
    record_install(
        &app_dir,
        "kept",
        Some("0.1.0"),
        crate::service::source::PackageSource::Path {
            path: "/tmp/kept_source".to_string(),
        },
    )
    .unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;
    svc.pkg_remove("kept", None, None, Some("global".to_string()))
        .await
        .unwrap();

    assert!(
        pkg_dir.exists(),
        "global scope must not delete ~/.algocline/packages/{{name}}/"
    );
    assert!(
        pkg_dir.join("init.lua").exists(),
        "init.lua should still be present"
    );
}

/// `scope = "all"` is lenient: removes from whichever scope has the entry.
/// When only the global manifest has it (project scope legitimately absent
/// because the project never declared the package), the call still succeeds
/// and reports `project_removed = false`.
#[tokio::test]
async fn pkg_remove_all_scope_is_lenient_when_only_global_has_entry() {
    use crate::service::manifest::{load_manifest, record_install};

    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();
    let app_dir = crate::service::test_support::test_app_dir(home);
    record_install(
        &app_dir,
        "orphan",
        None,
        crate::service::source::PackageSource::Path {
            path: "/tmp/orphan_source".to_string(),
        },
    )
    .unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;
    // No project_root supplied — project scope will fail to resolve.
    let result = svc
        .pkg_remove("orphan", None, None, Some("all".to_string()))
        .await
        .unwrap();

    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    assert_eq!(json["removed"], "orphan");
    assert_eq!(json["scope"], "all");
    assert_eq!(json["global_removed"], true);
    assert_eq!(json["project_removed"], false);
    assert!(
        !load_manifest(&app_dir)
            .unwrap()
            .packages
            .contains_key("orphan"),
        "global manifest still contains the entry"
    );
}

/// `scope = "all"` errors only when neither scope has the entry. Both
/// scope-specific error strings are surfaced so the caller can diagnose.
#[tokio::test]
async fn pkg_remove_all_scope_errors_when_neither_scope_has_entry() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    let svc = make_app_service_at(home.to_path_buf()).await;
    let err = svc
        .pkg_remove("never_anywhere", None, None, Some("all".to_string()))
        .await
        .expect_err("expected Err");

    assert!(err.contains("not found in any scope"), "unexpected: {err}");
    assert!(err.contains("project:"), "missing project context: {err}");
    assert!(err.contains("global:"), "missing global context: {err}");
}

/// Unknown `scope` values are rejected rather than silently defaulting.
#[tokio::test]
async fn pkg_remove_invalid_scope_errors() {
    let svc = make_app_service().await;
    let err = svc
        .pkg_remove("x", None, None, Some("packages".to_string()))
        .await
        .expect_err("expected Err");
    assert!(
        err.contains("invalid scope") && err.contains("packages"),
        "unexpected: {err}"
    );
}

// ── resolved_source_path / resolved_source_kind / override_paths tests ────

/// Case 1: project `path` entry — `resolved_source_path` is the canonicalized
/// absolute path of the package directory; `resolved_source_kind = "local_path"`.
#[tokio::test]
async fn pkg_list_project_path_entry_has_resolved_source() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    // Create a vendor package directory inside the project.
    let pkg_dir = project_root.join("my_vendor_pkg");
    std::fs::create_dir_all(&pkg_dir).unwrap();
    std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

    // alc.toml with path dependency.
    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\nmy_vendor_pkg = { path = \"my_vendor_pkg\" }\n",
    )
    .unwrap();

    // alc.lock with Path source.
    let lock = LockFile {
        version: 1,
        packages: vec![LockPackage {
            name: "my_vendor_pkg".to_string(),
            version: None,
            source: PackageSource::Path {
                path: "my_vendor_pkg".to_string(),
            },
        }],
    };
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();

    let svc = make_app_service().await;
    let result = pkg_list_summary(&svc, Some(project_root.to_string_lossy().to_string())).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let pkg = packages
        .iter()
        .find(|p| p["name"] == "my_vendor_pkg")
        .expect("my_vendor_pkg not found");

    let expected_canonical = std::fs::canonicalize(&pkg_dir)
        .unwrap()
        .display()
        .to_string();

    assert_eq!(
        pkg["resolved_source_path"].as_str().unwrap(),
        expected_canonical,
        "resolved_source_path should be canonicalized path"
    );
    assert_eq!(pkg["resolved_source_kind"], "local_path");
}

/// Case 2: project `path` entry where the vendor directory is itself a symlink —
/// `resolved_source_path` follows the symlink to the real target.
#[tokio::test]
async fn pkg_list_project_path_with_symlink_vendor_follows_target() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    // Create a real package directory somewhere else.
    let real_pkg = tmp.path().join("real_pkg_dir");
    std::fs::create_dir_all(&real_pkg).unwrap();
    std::fs::write(real_pkg.join("init.lua"), "return {}").unwrap();

    // Create a symlink inside the project pointing to the real dir.
    let symlink_in_project = project_root.join("sym_vendor_pkg");
    std::os::unix::fs::symlink(&real_pkg, &symlink_in_project).unwrap();

    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\nsym_vendor_pkg = { path = \"sym_vendor_pkg\" }\n",
    )
    .unwrap();

    let lock = LockFile {
        version: 1,
        packages: vec![LockPackage {
            name: "sym_vendor_pkg".to_string(),
            version: None,
            source: PackageSource::Path {
                path: "sym_vendor_pkg".to_string(),
            },
        }],
    };
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();

    let svc = make_app_service().await;
    let result = pkg_list_summary(&svc, Some(project_root.to_string_lossy().to_string())).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let pkg = packages
        .iter()
        .find(|p| p["name"] == "sym_vendor_pkg")
        .expect("sym_vendor_pkg not found");

    // canonicalize follows the symlink to real_pkg.
    let expected_canonical = std::fs::canonicalize(&real_pkg)
        .unwrap()
        .display()
        .to_string();

    assert_eq!(
        pkg["resolved_source_path"].as_str().unwrap(),
        expected_canonical,
        "resolved_source_path should resolve through symlink to real target"
    );
    assert_eq!(pkg["resolved_source_kind"], "local_path");
}

/// Case 3: project `installed` entry — `resolved_source_path` is
/// `{packages_dir()}/{name}` canonicalized; `resolved_source_kind = "installed"`.
#[tokio::test]
async fn pkg_list_project_installed_entry_has_resolved_source() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();
    let packages_dir = home.join("packages");
    let pkg_dir = packages_dir.join("installed_pkg");
    std::fs::create_dir_all(&pkg_dir).unwrap();
    std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\ninstalled_pkg = \"*\"\n",
    )
    .unwrap();

    let lock = LockFile {
        version: 1,
        packages: vec![LockPackage {
            name: "installed_pkg".to_string(),
            version: None,
            source: PackageSource::Installed,
        }],
    };
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;
    let result = pkg_list_summary(&svc, Some(project_root.to_string_lossy().to_string())).await;
    let expected_canonical = std::fs::canonicalize(&pkg_dir)
        .unwrap()
        .display()
        .to_string();
    drop(tmp);

    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let pkg = packages
        .iter()
        .find(|p| p["name"] == "installed_pkg")
        .expect("installed_pkg not found");

    assert_eq!(
        pkg["resolved_source_path"].as_str().unwrap(),
        expected_canonical,
        "resolved_source_path should be packages_dir/<name> canonicalized"
    );
    assert_eq!(pkg["resolved_source_kind"], "installed");
}

/// Case 4 (light): project `installed` entry where `packages_dir/{name}` is itself
/// a symlink (linked package). The resolved path follows through to the real target.
#[tokio::test]
async fn pkg_list_project_installed_resolves_through_linked_pkg() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();
    let packages_dir = home.join("packages");
    std::fs::create_dir_all(&packages_dir).unwrap();

    // The "real" development directory (what the symlink points to).
    let real_dev_dir = home.join("dev").join("linked_pkg_real");
    std::fs::create_dir_all(&real_dev_dir).unwrap();
    std::fs::write(real_dev_dir.join("init.lua"), "return {}").unwrap();

    // Symlink in packages_dir pointing to the dev dir.
    let symlink_path = packages_dir.join("linked_pkg");
    std::os::unix::fs::symlink(&real_dev_dir, &symlink_path).unwrap();

    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\nlinked_pkg = \"*\"\n",
    )
    .unwrap();

    let lock = LockFile {
        version: 1,
        packages: vec![LockPackage {
            name: "linked_pkg".to_string(),
            version: None,
            source: PackageSource::Installed,
        }],
    };
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;
    let result = pkg_list_summary(&svc, Some(project_root.to_string_lossy().to_string())).await;
    // canonicalize follows the symlink to the real dev dir.
    let expected_canonical = std::fs::canonicalize(&real_dev_dir)
        .unwrap()
        .display()
        .to_string();
    drop(tmp);

    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let pkg = packages
        .iter()
        .find(|p| p["name"] == "linked_pkg")
        .expect("linked_pkg not found");

    assert_eq!(
        pkg["resolved_source_path"].as_str().unwrap(),
        expected_canonical,
        "resolved_source_path should follow symlink in packages_dir to real target"
    );
    assert_eq!(pkg["resolved_source_kind"], "installed");
}

/// Case 5: global regular (non-symlink) package —
/// `resolved_source_path = canonicalize({search_path}/{name})`,
/// `resolved_source_kind = "installed"` (no manifest entry → "installed").
#[tokio::test]
async fn pkg_list_global_regular_pkg_has_resolved_source() {
    let tmp = tempfile::tempdir().unwrap();
    let search_dir = tmp.path().join("pkgs");
    std::fs::create_dir_all(&search_dir).unwrap();

    let pkg_dir = search_dir.join("regular_pkg");
    std::fs::create_dir_all(&pkg_dir).unwrap();
    std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

    let search_path = crate::service::resolve::SearchPath {
        path: search_dir.clone(),
        source: crate::service::resolve::SearchPathSource::Env,
    };
    let svc = make_app_service_with_search_paths(vec![search_path]).await;
    let result = pkg_list_summary(&svc, None).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let pkg = packages
        .iter()
        .find(|p| p["name"] == "regular_pkg")
        .expect("regular_pkg not found");

    let expected_canonical = std::fs::canonicalize(&pkg_dir)
        .unwrap()
        .display()
        .to_string();

    assert_eq!(
        pkg["resolved_source_path"].as_str().unwrap(),
        expected_canonical
    );
    assert_eq!(pkg["resolved_source_kind"], "installed");
}

/// Case 6: global linked (symlink) package —
/// `resolved_source_path` is the canonicalized symlink target;
/// `resolved_source_kind = "linked"`.
#[tokio::test]
async fn pkg_list_global_linked_pkg_resolves_to_link_target() {
    let tmp = tempfile::tempdir().unwrap();
    let search_dir = tmp.path().join("pkgs");
    std::fs::create_dir_all(&search_dir).unwrap();

    // Real package directory (dev workspace).
    let real_dir = tmp.path().join("my_dev_pkg");
    std::fs::create_dir_all(&real_dir).unwrap();
    std::fs::write(real_dir.join("init.lua"), "return {}").unwrap();

    // Symlink in the search_dir pointing to real_dir.
    let link_path = search_dir.join("linked_global_pkg");
    std::os::unix::fs::symlink(&real_dir, &link_path).unwrap();

    let search_path = crate::service::resolve::SearchPath {
        path: search_dir,
        source: crate::service::resolve::SearchPathSource::Env,
    };
    let svc = make_app_service_with_search_paths(vec![search_path]).await;
    let result = pkg_list_full(&svc, None).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let pkg = packages
        .iter()
        .find(|p| p["name"] == "linked_global_pkg")
        .expect("linked_global_pkg not found");

    let expected_canonical = std::fs::canonicalize(&real_dir)
        .unwrap()
        .display()
        .to_string();

    assert_eq!(
        pkg["resolved_source_path"].as_str().unwrap(),
        expected_canonical,
        "resolved_source_path should point to real target"
    );
    assert_eq!(pkg["resolved_source_kind"], "linked");
    assert_eq!(pkg["linked"], true);
}

/// Case 7: global linked package with a dangling (broken) symlink —
/// `resolved_source_path` must be absent; `resolved_source_kind = "linked"`;
/// `broken = true`.
#[tokio::test]
async fn pkg_list_global_linked_broken_omits_resolved_source() {
    let tmp = tempfile::tempdir().unwrap();
    let search_dir = tmp.path().join("pkgs");
    std::fs::create_dir_all(&search_dir).unwrap();

    // Create a symlink pointing to a nonexistent path.
    let nonexistent_target = tmp.path().join("this_does_not_exist");
    let link_path = search_dir.join("broken_pkg");
    std::os::unix::fs::symlink(&nonexistent_target, &link_path).unwrap();

    let search_path = crate::service::resolve::SearchPath {
        path: search_dir,
        source: crate::service::resolve::SearchPathSource::Env,
    };
    let svc = make_app_service_with_search_paths(vec![search_path]).await;
    let result = pkg_list_full(&svc, None).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let pkg = packages
        .iter()
        .find(|p| p["name"] == "broken_pkg")
        .expect("broken_pkg not found");

    assert!(
        pkg.get("resolved_source_path").is_none() || pkg["resolved_source_path"].is_null(),
        "resolved_source_path must be absent for broken symlink"
    );
    assert_eq!(pkg["resolved_source_kind"], "linked");
    assert_eq!(pkg["broken"], true);
}

/// Case 8: two global search paths contain a package with the same name —
/// `override_paths` on the active entry lists the shadowed path(s) in
/// search-path order.
#[tokio::test]
async fn pkg_list_override_paths_global_shadow() {
    let tmp = tempfile::tempdir().unwrap();
    let search_dir1 = tmp.path().join("pkgs1");
    let search_dir2 = tmp.path().join("pkgs2");
    std::fs::create_dir_all(&search_dir1).unwrap();
    std::fs::create_dir_all(&search_dir2).unwrap();

    // Same package name in both search paths.
    for dir in [&search_dir1, &search_dir2] {
        let pkg_dir = dir.join("dup_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();
    }

    let svc = make_app_service_with_search_paths(vec![
        crate::service::resolve::SearchPath {
            path: search_dir1.clone(),
            source: crate::service::resolve::SearchPathSource::Env,
        },
        crate::service::resolve::SearchPath {
            path: search_dir2.clone(),
            source: crate::service::resolve::SearchPathSource::Env,
        },
    ])
    .await;

    let result = pkg_list_full(&svc, None).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    // Active entry is the one from search_dir1 (first wins).
    let active_pkg = packages
        .iter()
        .find(|p| p["name"] == "dup_pkg" && p["active"] == true)
        .expect("active dup_pkg not found");

    let override_paths = active_pkg["override_paths"]
        .as_array()
        .expect("override_paths should be an array on active entry");

    assert_eq!(
        override_paths.len(),
        1,
        "should have exactly one shadowed entry"
    );

    let expected_shadow = std::fs::canonicalize(search_dir2.join("dup_pkg"))
        .unwrap()
        .display()
        .to_string();

    assert_eq!(
        override_paths[0].as_str().unwrap(),
        expected_shadow,
        "override_paths[0] should be the canonicalized path in search_dir2"
    );
}

/// Case 9: project entry shadows a global entry —
/// the project entry's `override_paths` contains the global package path;
/// the inactive global entry has no `override_paths`.
#[tokio::test]
async fn pkg_list_override_paths_project_shadows_global() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();
    let search_dir = tmp.path().join("global_pkgs");
    std::fs::create_dir_all(&search_dir).unwrap();

    // Global package directory.
    let global_pkg_dir = search_dir.join("shared_pkg");
    std::fs::create_dir_all(&global_pkg_dir).unwrap();
    std::fs::write(global_pkg_dir.join("init.lua"), "return {}").unwrap();

    // Project vendor package directory.
    let local_pkg_dir = project_root.join("shared_pkg");
    std::fs::create_dir_all(&local_pkg_dir).unwrap();
    std::fs::write(local_pkg_dir.join("init.lua"), "return {}").unwrap();

    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\nshared_pkg = { path = \"shared_pkg\" }\n",
    )
    .unwrap();

    let lock = LockFile {
        version: 1,
        packages: vec![LockPackage {
            name: "shared_pkg".to_string(),
            version: None,
            source: PackageSource::Path {
                path: "shared_pkg".to_string(),
            },
        }],
    };
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();

    let svc = make_app_service_with_search_paths(vec![crate::service::resolve::SearchPath {
        path: search_dir.clone(),
        source: crate::service::resolve::SearchPathSource::Env,
    }])
    .await;

    let result = pkg_list_full(&svc, Some(project_root.to_string_lossy().to_string())).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    // Project entry (active, scope = "project") must have override_paths with the global path.
    let project_entry = packages
        .iter()
        .find(|p| p["name"] == "shared_pkg" && p["scope"] == "project")
        .expect("project shared_pkg not found");

    let override_paths = project_entry["override_paths"]
        .as_array()
        .expect("project entry should have override_paths listing shadowed global");

    let expected_global_canonical = std::fs::canonicalize(&global_pkg_dir)
        .unwrap()
        .display()
        .to_string();

    assert!(
        override_paths
            .iter()
            .any(|p| p.as_str().unwrap() == expected_global_canonical),
        "project override_paths should include the global pkg canonical path"
    );

    // Inactive global entry must NOT have override_paths.
    let global_entry = packages
        .iter()
        .find(|p| p["name"] == "shared_pkg" && p["scope"] == "global")
        .expect("global shared_pkg not found");

    assert_eq!(
        global_entry["active"], false,
        "global entry should be inactive"
    );
    let global_map = global_entry
        .as_object()
        .expect("global entry must be object");
    assert!(
        !global_map.contains_key("override_paths"),
        "inactive global entry must not have override_paths, got: {:?}",
        global_map.get("override_paths")
    );
}

/// Regression: a project `installed` entry must not list its own backing
/// directory (`packages_dir/{name}`) in `override_paths` just because the
/// global search paths include `packages_dir`. The entry's own
/// `resolved_source_path` canonicalizes to the same location, so that
/// occurrence is not a genuine shadow and must be filtered out.
#[tokio::test]
async fn pkg_list_project_installed_does_not_self_shadow() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();
    let packages_dir = home.join("packages");
    let pkg_dir = packages_dir.join("self_shadow_pkg");
    std::fs::create_dir_all(&pkg_dir).unwrap();
    std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\nself_shadow_pkg = \"*\"\n",
    )
    .unwrap();

    let lock = LockFile {
        version: 1,
        packages: vec![LockPackage {
            name: "self_shadow_pkg".to_string(),
            version: None,
            source: PackageSource::Installed,
        }],
    };
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();

    // Include packages_dir as a search path — this is the real production
    // topology (see `resolve_lib_paths` in src/main.rs).
    let svc = make_app_service_at_with_search_paths(
        home.to_path_buf(),
        vec![crate::service::resolve::SearchPath {
            path: packages_dir.clone(),
            source: crate::service::resolve::SearchPathSource::Default,
        }],
    )
    .await;

    let result = pkg_list_full(&svc, Some(project_root.to_string_lossy().to_string())).await;
    drop(tmp);

    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let project_entry = packages
        .iter()
        .find(|p| p["name"] == "self_shadow_pkg" && p["scope"] == "project")
        .expect("project self_shadow_pkg not found");

    let entry_map = project_entry
        .as_object()
        .expect("project entry must be object");

    assert!(
        !entry_map.contains_key("override_paths"),
        "project `installed` entry must not list its own backing dir as override_paths, got: {:?}",
        entry_map.get("override_paths")
    );
}

/// A global package that exists on disk but is NOT registered in
/// `installed.json` must NOT emit a `source_type` field.
///
/// Previously the code wrote `source_type: "global"` (an invalid enum
/// value) as a placeholder. After the typed DTO rewrite, absent manifest
/// entries leave `source_type` out of the output entirely.
#[tokio::test]
async fn pkg_list_global_unregistered_has_no_source_type() {
    let tmp = tempfile::tempdir().unwrap();
    let search_dir = tmp.path().join("pkgs");
    std::fs::create_dir_all(&search_dir).unwrap();

    // Create a package directory with init.lua — but do NOT write
    // installed.json (simulating a hand-copied / ALC_PACKAGES_PATH package).
    let pkg_dir = search_dir.join("hand_copied_pkg");
    std::fs::create_dir_all(&pkg_dir).unwrap();
    std::fs::write(
        pkg_dir.join("init.lua"),
        "return { meta = { name = 'hand_copied_pkg' } }",
    )
    .unwrap();

    let search_path = crate::service::resolve::SearchPath {
        path: search_dir,
        source: crate::service::resolve::SearchPathSource::Env,
    };
    let svc = make_app_service_with_search_paths(vec![search_path]).await;
    let result = pkg_list_full(&svc, None).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let pkg = packages
        .iter()
        .find(|p| p["name"] == "hand_copied_pkg")
        .expect("hand_copied_pkg not found in pkg_list output");

    // source_type must be absent (not "global" or any other invalid value).
    let pkg_map = pkg
        .as_object()
        .expect("package entry must be a JSON object");
    assert!(
        !pkg_map.contains_key("source_type"),
        "source_type should be absent for unregistered package, got: {:?}",
        pkg_map.get("source_type")
    );
    assert_eq!(pkg["scope"], "global");
    assert_eq!(pkg["active"], true);

    // resolved_source_path must still be populated even without manifest
    // registration — filesystem access is independent of installed.json.
    let expected_canonical = std::fs::canonicalize(&pkg_dir)
        .unwrap()
        .display()
        .to_string();
    assert_eq!(
        pkg["resolved_source_path"].as_str().unwrap(),
        expected_canonical,
        "resolved_source_path should be populated regardless of manifest state"
    );
    // Unregistered packages default to "installed" kind (not "bundled").
    assert_eq!(
        pkg["resolved_source_kind"], "installed",
        "unregistered global package should default to installed kind"
    );
}

// ── variant scope (alc.local.toml) ───────────────────────────

/// `alc.local.toml` declares a variant pkg → it appears in `pkg_list` with
/// `scope: "variant"`, `resolved_source_kind: "variant"`, `active: true`,
/// and `path` set to the absolute pkg dir.
#[tokio::test]
async fn pkg_list_variant_pkg_appears_with_variant_scope() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    // Variant pkg lives outside the project root (typical worktree workflow).
    let pkg_dir = tmp.path().join("variant_src").join("my_variant_pkg");
    std::fs::create_dir_all(&pkg_dir).unwrap();
    std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

    std::fs::write(
        project_root.join("alc.local.toml"),
        format!(
            "[packages]\nmy_variant_pkg = {{ path = \"{}\" }}\n",
            pkg_dir.display()
        ),
    )
    .unwrap();

    let svc = make_app_service().await;
    let result = pkg_list_full(&svc, Some(project_root.to_string_lossy().to_string())).await;

    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let entry = packages
        .iter()
        .find(|p| p["name"] == "my_variant_pkg")
        .expect("my_variant_pkg not found in pkg_list output");

    assert_eq!(entry["scope"], "variant");
    assert_eq!(entry["active"], true);
    assert_eq!(entry["source_type"], "path");
    assert_eq!(entry["resolved_source_kind"], "variant");

    let expected_canonical = std::fs::canonicalize(&pkg_dir)
        .unwrap()
        .display()
        .to_string();
    assert_eq!(
        entry["resolved_source_path"].as_str().unwrap(),
        expected_canonical,
        "resolved_source_path should canonicalize to the variant pkg dir"
    );
    assert_eq!(
        entry["path"].as_str().unwrap(),
        pkg_dir.display().to_string(),
        "path should be the absolute pkg_dir as declared in alc.local.toml"
    );
}

/// A variant pkg shadowing a same-name global package: the variant entry
/// is `active: true`, the global one is demoted to `active: false`.
#[tokio::test]
async fn pkg_list_variant_shadows_global() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();
    let global_dir = tmp.path().join("global_pkgs");
    std::fs::create_dir_all(&global_dir).unwrap();

    // Global pkg of the same name.
    let global_pkg = global_dir.join("shared");
    std::fs::create_dir_all(&global_pkg).unwrap();
    std::fs::write(global_pkg.join("init.lua"), "return {}").unwrap();

    // Variant pkg.
    let variant_pkg = tmp.path().join("variant_src").join("shared");
    std::fs::create_dir_all(&variant_pkg).unwrap();
    std::fs::write(variant_pkg.join("init.lua"), "return {}").unwrap();

    std::fs::write(
        project_root.join("alc.local.toml"),
        format!(
            "[packages]\nshared = {{ path = \"{}\" }}\n",
            variant_pkg.display()
        ),
    )
    .unwrap();

    let svc = make_app_service_with_search_paths(vec![crate::service::resolve::SearchPath {
        path: global_dir.clone(),
        source: crate::service::resolve::SearchPathSource::Env,
    }])
    .await;

    let result = pkg_list_summary(&svc, Some(project_root.to_string_lossy().to_string())).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let variant_entry = packages
        .iter()
        .find(|p| p["name"] == "shared" && p["scope"] == "variant")
        .expect("variant 'shared' entry not found");
    assert_eq!(variant_entry["active"], true);

    let global_entry = packages
        .iter()
        .find(|p| p["name"] == "shared" && p["scope"] == "global")
        .expect("global 'shared' entry not found");
    assert_eq!(
        global_entry["active"], false,
        "global entry must be demoted when shadowed by variant"
    );
}

/// A variant pkg with the same name as an `alc.toml`-declared project pkg:
/// the variant entry wins (`active: true`), the project entry is demoted.
#[tokio::test]
async fn pkg_list_variant_shadows_project() {
    let tmp = tempfile::tempdir().unwrap();
    let project_root = tmp.path();

    // Project pkg via alc.toml + alc.lock (path entry).
    let project_pkg = project_root.join("shared");
    std::fs::create_dir_all(&project_pkg).unwrap();
    std::fs::write(project_pkg.join("init.lua"), "return {}").unwrap();
    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\nshared = { path = \"shared\" }\n",
    )
    .unwrap();
    let lock = LockFile {
        version: 1,
        packages: vec![LockPackage {
            name: "shared".to_string(),
            version: None,
            source: PackageSource::Path {
                path: "shared".to_string(),
            },
        }],
    };
    crate::service::lockfile::save_lockfile(project_root, &lock).unwrap();

    // Variant override.
    let variant_pkg = tmp.path().join("variant_src").join("shared");
    std::fs::create_dir_all(&variant_pkg).unwrap();
    std::fs::write(variant_pkg.join("init.lua"), "return {}").unwrap();
    std::fs::write(
        project_root.join("alc.local.toml"),
        format!(
            "[packages]\nshared = {{ path = \"{}\" }}\n",
            variant_pkg.display()
        ),
    )
    .unwrap();

    let svc = make_app_service().await;
    let result = pkg_list_summary(&svc, Some(project_root.to_string_lossy().to_string())).await;
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();
    let packages = json["packages"].as_array().unwrap();

    let variant_entry = packages
        .iter()
        .find(|p| p["name"] == "shared" && p["scope"] == "variant")
        .expect("variant 'shared' entry not found");
    assert_eq!(variant_entry["active"], true);

    let project_entry = packages
        .iter()
        .find(|p| p["name"] == "shared" && p["scope"] == "project")
        .expect("project 'shared' entry not found");
    assert_eq!(
        project_entry["active"], false,
        "project entry must be demoted when shadowed by variant"
    );
}

// ── pkg_repair tests ────────────────────────────────────────

/// (B) installed dir missing: pkg_install populates manifest, then we delete
/// the dest dir, then pkg_repair must restore it via reinstall.
#[tokio::test]
async fn pkg_repair_reinstalls_missing_installed_dir() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    // Build a source pkg in collection layout: <coll>/<name>/init.lua.
    let coll = home.join("src_repo");
    let source = coll.join("repair_pkg");
    std::fs::create_dir_all(&source).unwrap();
    std::fs::write(
        source.join("init.lua"),
        "return { meta = { version = '0.1.0' } }",
    )
    .unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;

    // Initial install — populates installed.json and creates dest dir (pass collection root).
    svc.pkg_install(coll.display().to_string(), None, None)
        .await
        .expect("initial install");

    let dest = home.join("packages").join("repair_pkg");
    assert!(dest.exists(), "dest must exist after install");

    // Simulate breakage: remove the dest dir.
    std::fs::remove_dir_all(&dest).unwrap();
    assert!(!dest.exists());

    // Repair — should re-run install from manifest source.
    let result = svc.pkg_repair(None, None).await.unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();

    let repaired = json["repaired"].as_array().expect("repaired array");
    assert_eq!(repaired.len(), 1, "exactly one repair, got: {json}");
    assert_eq!(repaired[0]["name"], "repair_pkg");
    assert_eq!(repaired[0]["kind"], "installed_missing");
    assert_eq!(repaired[0]["action"], "reinstall");
    assert!(dest.exists(), "dest must be restored after repair");
}

/// Healthy package — manifest entry + dest exist → Skipped.
#[tokio::test]
async fn pkg_repair_skips_healthy_pkg() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    // Collection layout: <coll>/<name>/init.lua.
    let coll = home.join("src_repo");
    let source = coll.join("healthy_pkg");
    std::fs::create_dir_all(&source).unwrap();
    std::fs::write(source.join("init.lua"), "return {}").unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;
    svc.pkg_install(coll.display().to_string(), None, None)
        .await
        .unwrap();

    let result = svc.pkg_repair(None, None).await.unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();

    assert!(
        json["repaired"].as_array().unwrap().is_empty(),
        "no repair expected"
    );
    let skipped = json["skipped"].as_array().unwrap();
    assert!(
        skipped.iter().any(|e| e["name"] == "healthy_pkg"),
        "healthy_pkg must be in skipped, got: {json}"
    );
}

/// (A) global symlink dangling — surfaced as unrepairable.
#[tokio::test]
async fn pkg_repair_reports_dangling_symlink_as_unrepairable() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    // Create the packages dir and a dangling symlink in it.
    let pkg_dir = home.join("packages");
    std::fs::create_dir_all(&pkg_dir).unwrap();

    let target = home.join("does_not_exist");
    let link = pkg_dir.join("dangling_pkg");
    std::os::unix::fs::symlink(&target, &link).unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;
    let result = svc.pkg_repair(None, None).await.unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();

    let unrepairable = json["unrepairable"].as_array().expect("unrepairable array");
    let entry = unrepairable
        .iter()
        .find(|e| e["name"] == "dangling_pkg")
        .expect("dangling_pkg must surface as unrepairable");
    assert_eq!(entry["kind"], "symlink_dangling");
    assert!(
        entry["suggestion"]
            .as_str()
            .unwrap()
            .contains("alc_pkg_unlink"),
        "suggestion should mention alc_pkg_unlink"
    );
}

/// (C) project-scope `path = ...` declared in alc.toml but the path doesn't
/// exist on disk — surfaced as unrepairable with `scope: "project"`.
#[tokio::test]
async fn pkg_repair_reports_project_path_missing_as_unrepairable() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();
    let project_root = home.join("proj");
    std::fs::create_dir_all(&project_root).unwrap();

    std::fs::write(
        project_root.join("alc.toml"),
        "[packages]\nghost = { path = \"missing_dir\" }\n",
    )
    .unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;
    let result = svc
        .pkg_repair(None, Some(project_root.to_string_lossy().to_string()))
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();

    let unrepairable = json["unrepairable"].as_array().unwrap();
    let entry = unrepairable
        .iter()
        .find(|e| e["name"] == "ghost" && e["scope"] == "project")
        .unwrap_or_else(|| panic!("ghost must surface as project path_missing, got: {json}"));
    assert_eq!(entry["kind"], "path_missing");
    assert!(entry["suggestion"].as_str().unwrap().contains("alc.toml"));
}

/// (D) variant-scope `path = ...` declared in alc.local.toml but the path
/// doesn't exist on disk — surfaced as unrepairable with `scope: "variant"`.
#[tokio::test]
async fn pkg_repair_reports_variant_path_missing_as_unrepairable() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();
    let project_root = home.join("proj");
    std::fs::create_dir_all(&project_root).unwrap();

    let absent = project_root.join("nope_pkg");
    std::fs::write(
        project_root.join("alc.local.toml"),
        format!(
            "[packages]\nnope_pkg = {{ path = \"{}\" }}\n",
            absent.display()
        ),
    )
    .unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;
    let result = svc
        .pkg_repair(None, Some(project_root.to_string_lossy().to_string()))
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();

    let unrepairable = json["unrepairable"].as_array().unwrap();
    let entry = unrepairable
        .iter()
        .find(|e| e["name"] == "nope_pkg" && e["scope"] == "variant")
        .expect("nope_pkg must surface as variant path_missing");
    assert_eq!(entry["kind"], "path_missing");
    assert!(entry["suggestion"]
        .as_str()
        .unwrap()
        .contains("alc_pkg_unlink"));
}

/// `name` filter that matches nothing → Err with informative message.
#[tokio::test]
async fn pkg_repair_unknown_name_returns_error() {
    // Tempdir-rooted AppDir isolates the test from the developer's
    // real `~/.algocline/packages/` so no probe name conflicts.
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    let svc = make_app_service_at(home.to_path_buf()).await;
    let err = svc
        .pkg_repair(Some("nonexistent_pkg".to_string()), None)
        .await
        .unwrap_err();
    assert!(
        err.contains("nonexistent_pkg"),
        "error should mention the missing name, got: {err}"
    );
}

/// LocalPath source dir vanished after manifest was written: classify as
/// Unrepairable (structural impossibility — no bytes to copy from), not
/// Failed (runtime error). Also verifies the `reason` names the missing path
/// so the operator can act on it without reading installed.json by hand.
#[tokio::test]
async fn pkg_repair_reports_localpath_source_missing_as_unrepairable() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    // Collection 1-entry layout: <coll>/<name>/init.lua.
    // Manifest records the collection root as the source path.
    let coll = home.join("gone");
    let source = coll.join("ghost_pkg");
    std::fs::create_dir_all(&source).unwrap();
    std::fs::write(source.join("init.lua"), "return {}").unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;
    svc.pkg_install(coll.display().to_string(), None, None)
        .await
        .expect("initial install");

    // Break both the installed dest AND the entire collection root so repair
    // can't auto-heal.  The manifest records the collection root path, so
    // removing it triggers the "source directory missing" pre-check.
    let dest = home.join("packages").join("ghost_pkg");
    std::fs::remove_dir_all(&dest).unwrap();
    std::fs::remove_dir_all(&coll).unwrap();

    let result = svc.pkg_repair(None, None).await.unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();

    assert!(
        json["failed"].as_array().unwrap().is_empty(),
        "missing-source must not leak into `failed`; got: {json}"
    );
    let unrepairable = json["unrepairable"].as_array().expect("unrepairable");
    let entry = unrepairable
        .iter()
        .find(|e| e["name"] == "ghost_pkg")
        .unwrap_or_else(|| panic!("ghost_pkg must appear in unrepairable, got: {json}"));
    assert_eq!(entry["kind"], "installed_missing");
    let reason = entry["reason"].as_str().unwrap();
    assert!(
        reason.contains("source directory missing"),
        "reason should mention missing source, got: {reason}"
    );
    // In collection layout the recorded source path is the collection root
    // ("gone/"), not the package sub-directory ("gone/ghost_pkg").  The
    // package identity is already verified via entry["name"] == "ghost_pkg"
    // above; here we verify that the reason cites the missing collection path.
    assert!(
        reason.contains("gone"),
        "reason should cite the collection path, got: {reason}"
    );
}

/// LocalPath source (collection root) exists but the named package's
/// `init.lua` has been removed from the source: repair classifies this as
/// Unrepairable (installed_missing) because the pre-check
/// `<source>/<name>/init.lua` must be present before a re-install attempt.
/// This test verifies the unrepairable classification fires when the source
/// init.lua disappears independently of the installed dest.
#[tokio::test]
async fn pkg_repair_reports_localpath_without_init_lua_as_unrepairable() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    // Collection 1-entry layout: <coll>/<name>/init.lua.
    // Use <coll> as the install source so the manifest records
    // PackageSource::Path { path: coll }.
    let coll = home.join("shell");
    let pkg_dir = coll.join("shell_pkg");
    std::fs::create_dir_all(&pkg_dir).unwrap();
    std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();

    let svc = make_app_service_at(home.to_path_buf()).await;
    svc.pkg_install(coll.display().to_string(), None, None)
        .await
        .expect("initial install");

    // Break the installed dest so repair considers re-install.
    let dest = home.join("packages").join("shell_pkg");
    std::fs::remove_dir_all(&dest).unwrap();

    // Also remove the source init.lua so the pre-check
    // `<coll>/shell_pkg/init.lua` fails.  The collection root still exists,
    // so this is the "no init.lua at named subdir" branch rather than the
    // "source directory missing" branch.
    std::fs::remove_file(pkg_dir.join("init.lua")).unwrap();

    let result = svc.pkg_repair(None, None).await.unwrap();
    let json: serde_json::Value = serde_json::from_str(&result).unwrap();

    assert!(
        json["failed"].as_array().unwrap().is_empty(),
        "missing-init-lua source must not leak into `failed`; got: {json}"
    );
    let entry = json["unrepairable"]
        .as_array()
        .unwrap()
        .iter()
        .find(|e| e["name"] == "shell_pkg")
        .unwrap_or_else(|| panic!("shell_pkg must appear in unrepairable, got: {json}"))
        .clone();
    assert_eq!(entry["kind"], "installed_missing");
    let reason = entry["reason"].as_str().unwrap();
    assert!(
        reason.contains("no init.lua at root"),
        "reason should cite missing init.lua, got: {reason}"
    );
}

/// Direct `pkg_install` against a non-existent path must surface a clear
/// "Source directory does not exist" error rather than the misleading
/// collection-mode "'name' parameter is only supported..." error (which
/// previously fired because a missing source has no `init.lua` at root and
/// fell through to the collection branch).
#[tokio::test]
async fn pkg_install_rejects_missing_local_source_with_clear_error() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    let svc = make_app_service_at(home.to_path_buf()).await;
    let missing = "/tmp/alc-nonexistent-source-for-test-2e8f3a";
    let err = svc
        .pkg_install(missing.to_string(), Some("anything".to_string()), None)
        .await
        .unwrap_err();
    assert!(
        err.contains("Source directory does not exist"),
        "expected explicit source-missing error, got: {err}"
    );
    assert!(
        !err.contains("'name' parameter"),
        "must not regress to collection-mode misleading error, got: {err}"
    );
}

// ─── Size regression guard (ST3) ──────────────────────────────
//
// Before the list-tool unification (pre-ST1), `alc_pkg_list` and
// `alc_hub_search` emitted 63K–68K-char single-line JSON that exceeded
// Claude Code's context window on populated environments. The summary
// preset now caps per-entry output to roughly 6 fields; at the default
// `limit=50` that should stay well under 15,000 chars. These two tests
// pin that contract so any regression toward the fat shape is caught
// immediately, regardless of preset churn.

/// FNV-1a hash — reproduces `hub::cache_key` verbatim so the test can
/// pre-populate the per-source cache without exposing the internal.
fn fnv1a_hex(url: &str) -> String {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in url.as_bytes() {
        h ^= *b as u64;
        h = h.wrapping_mul(0x0100_0000_01b3);
    }
    format!("{h:016x}")
}

/// `alc_pkg_list` default summary (`verbose="summary"`) must stay under
/// 15_000 chars with a realistically populated test environment.
///
/// Setup: write 60 synthetic installed packages under a search path
/// (each with an `init.lua`). Summary preset projects 6 fields per
/// entry; default `limit=50` caps the projected array, so the fixture
/// populates **60 packages** to exercise the default-limit worst case
/// (truncation to 50 entries). Real-world environments have ~100-150
/// installed packages but hit the same 50-entry cap — 50 entries × ~224
/// chars/entry puts the ceiling around 11 KB, so the 15_000 budget
/// leaves ~34% headroom for natural field churn.
#[tokio::test]
async fn pkg_list_default_summary_is_compact() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    let tmp = tempfile::tempdir().unwrap();
    let search_dir = tmp.path().join("pkgs");
    std::fs::create_dir_all(&search_dir).unwrap();

    // 60 > default limit (50). Guards the actual default-limit worst case:
    // real-world setups (100-150 pkgs) hit the same 50-entry truncation.
    for i in 0..60 {
        let pkg_dir = search_dir.join(format!("size_regression_pkg_{i:02}"));
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();
    }

    let search_path = crate::service::resolve::SearchPath {
        path: search_dir,
        source: crate::service::resolve::SearchPathSource::Env,
    };
    let svc = make_app_service_at_with_search_paths(home.to_path_buf(), vec![search_path]).await;
    let out = pkg_list_summary(&svc, None).await;

    assert!(
        out.len() < 15_000,
        "pkg_list default summary should stay compact (got {} chars)",
        out.len()
    );
    // Sanity: output must be valid JSON and include at least one
    // package — otherwise the budget is meaningless.
    let json: serde_json::Value = serde_json::from_str(&out).unwrap();
    assert!(
        !json["packages"].as_array().unwrap().is_empty(),
        "size test is meaningless without populated packages"
    );
}

/// `alc_hub_search` default summary (`verbose="summary"`) must stay under
/// 10_000 chars. To keep the test deterministic (and offline), the
/// per-source cache is primed with empty `HubIndex` entries for every
/// URL that `discover_index_urls` can surface under the tempdir-rooted
/// `AppDir` this test installs:
///
/// - `hub.collection_url` is unset → no Tier 0 entry.
/// - No registries / manifest → only the compiled-in `AUTO_INSTALL_SOURCES`
///   remain (1 entry), transformed by `repo_to_index_url` to raw
///   GitHub URLs.
///
/// Populating the cache for that URL with an empty `HubIndex` means
/// `fetch_one` returns early and never makes an HTTP call, so the test
/// works offline and finishes in milliseconds.
#[tokio::test]
async fn hub_search_default_summary_is_compact() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    let cache_dir = home.join("hub_cache");
    std::fs::create_dir_all(&cache_dir).unwrap();

    // Empty HubIndex JSON — matches the schema `fetch_one` deserializes.
    let empty_index = serde_json::json!({
        "schema_version": "hub_index/v0",
        "updated_at": "",
        "packages": [],
    })
    .to_string();

    // Seed cache for every URL `discover_index_urls` may surface
    // under the tempdir-rooted `AppDir`. The compiled-in seeds live
    // in `AUTO_INSTALL_SOURCES`; they are passed through
    // `repo_to_index_url` before hitting the cache layer. If this
    // list drifts the test must follow — `repo_to_index_url` is
    // verified verbatim by `hub.rs` unit tests.
    {
        let repo = "https://github.com/ynishi/algocline-bundled-packages";
        let owner_repo = repo.trim_start_matches("https://github.com/");
        let index_url =
            format!("https://raw.githubusercontent.com/{owner_repo}/main/hub_index.json");
        let cache_path = cache_dir.join(format!("{}.json", fnv1a_hex(&index_url)));
        std::fs::write(&cache_path, &empty_index).unwrap();
    }

    let svc = make_app_service_at(home.to_path_buf()).await;
    // Call the internal `AppService::hub_search` directly (same form
    // `engine_api_impl::hub_search` uses after folding MCP params into
    // `ListOpts`). Keeps the test at the app-layer boundary and avoids
    // the EngineApi trait import dance.
    let out = svc.hub_search(None, None, None, opts(), None).unwrap();

    assert!(
        out.len() < 10_000,
        "hub_search default summary should stay compact (got {} chars)",
        out.len()
    );
    // Sanity: output is valid JSON.
    let _: serde_json::Value = serde_json::from_str(&out).unwrap();
}

// ─── limit=0 → "no limit" (empty-means-all idiom) ──────────────
//
// `limit = Some(0)` means "return all entries" — the list-tool contract
// mirrors common `empty=all & some=filter` idioms. Default (`None`) still
// caps at 50. Pins the truncation branch for both tools.

/// `alc_pkg_list` with `limit = Some(0)` returns every entry (no cap).
#[tokio::test]
async fn pkg_list_limit_zero_returns_all() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    let tmp = tempfile::tempdir().unwrap();
    let search_dir = tmp.path().join("pkgs");
    std::fs::create_dir_all(&search_dir).unwrap();

    // Populate 60 packages — more than the default cap of 50 — so a
    // regression that silently applies the default limit to `Some(0)`
    // would surface as a truncated array.
    for i in 0..60 {
        let pkg_dir = search_dir.join(format!("limit_zero_pkg_{i:02}"));
        std::fs::create_dir_all(&pkg_dir).unwrap();
        std::fs::write(pkg_dir.join("init.lua"), "return {}").unwrap();
    }

    let search_path = crate::service::resolve::SearchPath {
        path: search_dir,
        source: crate::service::resolve::SearchPathSource::Env,
    };
    let svc = make_app_service_at_with_search_paths(home.to_path_buf(), vec![search_path]).await;

    let out = svc
        .pkg_list(
            None,
            ListOpts {
                limit: Some(0),
                ..opts()
            },
        )
        .await
        .unwrap();

    let json: serde_json::Value = serde_json::from_str(&out).unwrap();
    let packages = json["packages"].as_array().expect("packages array");
    assert_eq!(
        packages.len(),
        60,
        "limit=0 must return all 60 entries (got {})",
        packages.len()
    );
}

/// `alc_hub_search` with `limit = Some(0)` skips truncation — the result
/// array length equals `total`. Uses a primed empty index (same pattern
/// as `hub_search_default_summary_is_compact`) so `results` is an empty
/// array whose length equals `total`; the non-truncation branch is
/// confirmed by both sides agreeing.
#[tokio::test]
async fn hub_search_limit_zero_returns_all() {
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path();

    let cache_dir = home.join("hub_cache");
    std::fs::create_dir_all(&cache_dir).unwrap();

    let empty_index = serde_json::json!({
        "schema_version": "hub_index/v0",
        "updated_at": "",
        "packages": [],
    })
    .to_string();

    {
        let repo = "https://github.com/ynishi/algocline-bundled-packages";
        let owner_repo = repo.trim_start_matches("https://github.com/");
        let index_url =
            format!("https://raw.githubusercontent.com/{owner_repo}/main/hub_index.json");
        let cache_path = cache_dir.join(format!("{}.json", fnv1a_hex(&index_url)));
        std::fs::write(&cache_path, &empty_index).unwrap();
    }

    let svc = make_app_service_at(home.to_path_buf()).await;
    let out = svc
        .hub_search(
            None,
            None,
            None,
            ListOpts {
                limit: Some(0),
                ..opts()
            },
            None,
        )
        .unwrap();

    let json: serde_json::Value = serde_json::from_str(&out).unwrap();
    let results = json["results"].as_array().expect("results array");
    let total = json["total"].as_u64().expect("total number");
    assert_eq!(
        results.len() as u64,
        total,
        "limit=0 must not truncate: results.len={} vs total={}",
        results.len(),
        total
    );
}