sqry-cli 14.0.3

CLI for sqry - semantic code search
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
//! Index command implementation

use crate::args::Cli;
use crate::plugin_defaults::{self, PluginSelectionMode};
use crate::progress::{CliProgressReporter, CliStepProgressReporter, StepRunner};
use anyhow::{Context, Result};
use sqry_core::graph::unified::analysis::ReachabilityStrategy;
use sqry_core::graph::unified::build::BuildResult;
use sqry_core::graph::unified::build::entrypoint::{AnalysisStrategySummary, get_git_head_commit};
use sqry_core::graph::unified::persistence::{GraphStorage, load_header_from_path};
use sqry_core::json_response::IndexStatus;
use sqry_core::progress::{SharedReporter, no_op_reporter};
use std::fs;
use std::io::{BufRead, BufReader, IsTerminal, Write};
use std::path::Path;
#[cfg(feature = "jvm-classpath")]
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;

/// Thread pool creation metrics for diagnostic output.
///
/// Emitted as JSON to stdout when `SQRY_EMIT_THREAD_POOL_METRICS=1` is set.
/// Used for build diagnostics and performance monitoring.
#[derive(serde::Serialize)]
struct ThreadPoolMetrics {
    thread_pool_creations: u64,
}

#[cfg_attr(not(feature = "jvm-classpath"), allow(dead_code))]
#[derive(Clone, Copy, Debug)]
pub(crate) struct ClasspathCliOptions<'a> {
    pub enabled: bool,
    pub depth: crate::args::ClasspathDepthArg,
    pub classpath_file: Option<&'a Path>,
    pub build_system: Option<&'a str>,
    pub force_classpath: bool,
}

#[cfg(feature = "jvm-classpath")]
pub(crate) fn run_classpath_pipeline_only(
    root_path: &Path,
    classpath_opts: &ClasspathCliOptions<'_>,
) -> Result<Option<sqry_classpath::pipeline::ClasspathPipelineResult>> {
    use sqry_classpath::pipeline::{ClasspathConfig, ClasspathDepth};

    let depth = match classpath_opts.depth {
        crate::args::ClasspathDepthArg::Full => ClasspathDepth::Full,
        crate::args::ClasspathDepthArg::Shallow => ClasspathDepth::Shallow,
    };
    let config = ClasspathConfig {
        enabled: true,
        depth,
        build_system_override: classpath_opts.build_system.map(str::to_owned),
        classpath_file: classpath_opts.classpath_file.map(Path::to_path_buf),
        force: classpath_opts.force_classpath,
        timeout_secs: 60,
    };

    println!("Running JVM classpath analysis...");
    match sqry_classpath::pipeline::run_classpath_pipeline(root_path, &config) {
        Ok(result) => {
            println!(
                "  Classpath: {} JARs scanned, {} classes parsed",
                result.jars_scanned, result.classes_parsed
            );
            Ok(Some(result))
        }
        Err(sqry_classpath::ClasspathError::DetectionFailed(message))
            if classpath_opts.build_system.is_none() && classpath_opts.classpath_file.is_none() =>
        {
            eprintln!(
                "WARNING: --classpath requested, but no JVM build system was detected; \
                 skipping classpath analysis. {message}"
            );
            Ok(None)
        }
        Err(error) => Err(error).context("Classpath pipeline failed"),
    }
}

#[cfg(feature = "jvm-classpath")]
fn create_workspace_classpath_import_edges(
    graph: &mut sqry_core::graph::unified::concurrent::CodeGraph,
    classpath_result: &sqry_classpath::pipeline::ClasspathPipelineResult,
    fqn_to_nodes: &std::collections::HashMap<
        String,
        Vec<sqry_classpath::graph::emitter::ClasspathNodeRef>,
    >,
) -> (usize, usize, usize, usize) {
    use sqry_core::graph::unified::edge::EdgeKind;
    use sqry_core::graph::unified::node::NodeKind;

    let class_fqns: std::collections::HashSet<&str> = classpath_result
        .index
        .classes
        .iter()
        .map(|class_stub| class_stub.fqn.as_str())
        .collect();
    let mut package_index: std::collections::HashMap<
        String,
        Vec<&sqry_classpath::graph::emitter::ClasspathNodeRef>,
    > = std::collections::HashMap::new();
    for fqn in class_fqns {
        if let Some(node_refs) = fqn_to_nodes.get(fqn)
            && let Some((package_name, _)) = fqn.rsplit_once('.')
        {
            package_index
                .entry(package_name.to_owned())
                .or_default()
                .extend(node_refs.iter());
        }
    }

    let scoped_jars = build_scope_jar_sets(&classpath_result.provenance);
    let provenance_lookup = build_provenance_lookup(&classpath_result.provenance);
    let mut existing_imports = Vec::new();
    for (source_id, source_entry) in graph.nodes().iter() {
        // Gate 0d iter-2 fix: skip unified losers. Edges from losers
        // are remapped to winners via `NodeRemapTable`, so iterating
        // them would be a no-op, but the explicit guard makes the
        // contract explicit. See `NodeEntry::is_unified_loser`.
        if source_entry.is_unified_loser() {
            continue;
        }
        for edge in graph.edges().edges_from(source_id) {
            let EdgeKind::Imports { alias, is_wildcard } = edge.kind.clone() else {
                continue;
            };
            let Some(import_entry) = graph.nodes().get(edge.target) else {
                continue;
            };
            if import_entry.kind != NodeKind::Import || graph.files().is_external(import_entry.file)
            {
                continue;
            }
            let importer_path = graph
                .files()
                .resolve(edge.file)
                .map(|path| canonicalish_path(path.as_ref()));
            let import_name = import_entry
                .qualified_name
                .and_then(|id| graph.strings().resolve(id))
                .or_else(|| graph.strings().resolve(import_entry.name))
                .map(|value| value.to_string());
            existing_imports.push((
                source_id,
                edge.file,
                alias,
                is_wildcard,
                import_name,
                importer_path,
            ));
        }
    }

    let mut created_edges = 0usize;
    let mut skipped_member_imports = 0usize;
    let mut skipped_unscoped_imports = 0usize;
    let mut skipped_ambiguous_imports = 0usize;

    for (importer_id, file_id, alias, is_wildcard, import_name, importer_path) in existing_imports {
        let Some(import_name) = import_name else {
            continue;
        };
        if import_name.starts_with("static ") {
            skipped_member_imports += 1;
            continue;
        }

        let Some(resolved) = resolve_allowed_jars(importer_path.as_deref(), &scoped_jars) else {
            skipped_unscoped_imports += 1;
            continue;
        };

        if is_wildcard || import_name.ends_with(".*") || import_name.ends_with("._") {
            let package_name = import_name
                .strip_suffix(".*")
                .or_else(|| import_name.strip_suffix("._"))
                .unwrap_or(import_name.as_str());
            if let Some(targets) = package_index.get(package_name) {
                let filtered_targets =
                    filter_scope_targets(targets.to_vec(), &resolved.allowed_jars);
                let grouped_targets = group_targets_by_fqn(filtered_targets);
                for target_group in grouped_targets.into_values() {
                    let reduced = prefer_direct_targets(
                        target_group,
                        resolved.matched_root.as_deref(),
                        &provenance_lookup,
                    );
                    if reduced.len() > 1 {
                        skipped_ambiguous_imports += 1;
                        continue;
                    }
                    let target_id = reduced[0].node_id;
                    let _delta = graph.edges().add_edge(
                        importer_id,
                        target_id,
                        EdgeKind::Imports { alias, is_wildcard },
                        file_id,
                    );
                    created_edges += 1;
                }
            }
            continue;
        }

        if let Some(targets) = fqn_to_nodes.get(import_name.as_str()) {
            let filtered_targets =
                filter_scope_targets(targets.iter().collect(), &resolved.allowed_jars);
            let reduced = prefer_direct_targets(
                filtered_targets,
                resolved.matched_root.as_deref(),
                &provenance_lookup,
            );
            if reduced.len() > 1 {
                skipped_ambiguous_imports += 1;
                continue;
            }
            if let Some(target_ref) = reduced.first() {
                let _delta = graph.edges().add_edge(
                    importer_id,
                    target_ref.node_id,
                    EdgeKind::Imports { alias, is_wildcard },
                    file_id,
                );
                created_edges += 1;
            }
        }
    }

    (
        created_edges,
        skipped_member_imports,
        skipped_unscoped_imports,
        skipped_ambiguous_imports,
    )
}

#[cfg(feature = "jvm-classpath")]
pub(crate) fn inject_classpath_into_graph(
    graph: &mut sqry_core::graph::unified::concurrent::CodeGraph,
    classpath_result: &sqry_classpath::pipeline::ClasspathPipelineResult,
) -> Result<()> {
    let emission_result = sqry_classpath::graph::emitter::emit_into_code_graph(
        &classpath_result.index,
        graph,
        &classpath_result.provenance,
    )
    .map_err(|e| anyhow::anyhow!("Classpath emission error: {e}"))?;

    let (
        import_edges_created,
        skipped_member_imports,
        skipped_unscoped_imports,
        skipped_ambiguous_imports,
    ) = create_workspace_classpath_import_edges(
        graph,
        classpath_result,
        &emission_result.fqn_to_nodes,
    );

    graph.rebuild_indices();
    println!(
        "  Graph enriched with {} classpath types, {} import edges ({} member/static, {} unscoped, {} ambiguous imports skipped)",
        classpath_result.index.classes.len(),
        import_edges_created,
        skipped_member_imports,
        skipped_unscoped_imports,
        skipped_ambiguous_imports,
    );
    Ok(())
}

#[cfg(feature = "jvm-classpath")]
fn build_scope_jar_sets(
    provenance: &[sqry_classpath::graph::provenance::ClasspathProvenance],
) -> Vec<(PathBuf, std::collections::HashSet<PathBuf>)> {
    let mut by_root: std::collections::HashMap<PathBuf, std::collections::HashSet<PathBuf>> =
        std::collections::HashMap::new();
    for entry in provenance {
        for scope in &entry.scopes {
            by_root
                .entry(canonicalish_path(&scope.module_root))
                .or_default()
                .insert(entry.jar_path.clone());
        }
    }

    let mut scopes: Vec<_> = by_root.into_iter().collect();
    scopes.sort_by(|a, b| {
        b.0.components()
            .count()
            .cmp(&a.0.components().count())
            .then_with(|| a.0.cmp(&b.0))
    });
    scopes
}

/// Result of scope resolution for an importer path.
#[cfg(feature = "jvm-classpath")]
struct ResolvedScope {
    allowed_jars: std::collections::HashSet<PathBuf>,
    matched_root: Option<PathBuf>,
}

#[cfg(feature = "jvm-classpath")]
fn resolve_allowed_jars(
    importer_path: Option<&Path>,
    scopes: &[(PathBuf, std::collections::HashSet<PathBuf>)],
) -> Option<ResolvedScope> {
    let importer_path = importer_path?;
    for (root, jars) in scopes {
        if importer_path.starts_with(root) {
            return Some(ResolvedScope {
                allowed_jars: jars.clone(),
                matched_root: Some(root.clone()),
            });
        }
    }
    if scopes.len() == 1 {
        return Some(ResolvedScope {
            allowed_jars: scopes[0].1.clone(),
            matched_root: Some(scopes[0].0.clone()),
        });
    }
    None
}

/// Builds a lookup from JAR path to its provenance entry for O(1) directness
/// checks during import resolution.
#[cfg(feature = "jvm-classpath")]
fn build_provenance_lookup(
    provenance: &[sqry_classpath::graph::provenance::ClasspathProvenance],
) -> std::collections::HashMap<PathBuf, &sqry_classpath::graph::provenance::ClasspathProvenance> {
    provenance
        .iter()
        .map(|entry| (entry.jar_path.clone(), entry))
        .collect()
}

/// Reduces candidates by preferring direct dependencies over transitive ones
/// within the matched scope. Returns the full set unchanged if all candidates
/// share the same directness or if no provenance/scope information is available.
#[cfg(feature = "jvm-classpath")]
fn prefer_direct_targets<'a>(
    targets: Vec<&'a sqry_classpath::graph::emitter::ClasspathNodeRef>,
    matched_root: Option<&Path>,
    provenance_lookup: &std::collections::HashMap<
        PathBuf,
        &sqry_classpath::graph::provenance::ClasspathProvenance,
    >,
) -> Vec<&'a sqry_classpath::graph::emitter::ClasspathNodeRef> {
    if targets.len() <= 1 {
        return targets;
    }

    let Some(root) = matched_root else {
        return targets;
    };

    let direct: Vec<_> = targets
        .iter()
        .copied()
        .filter(|target| {
            provenance_lookup.get(&target.jar_path).is_some_and(|prov| {
                prov.scopes
                    .iter()
                    .any(|scope| scope.module_root == root && scope.is_direct)
            })
        })
        .collect();

    if direct.is_empty() || direct.len() == targets.len() {
        // No differentiation possible — return the original set
        targets
    } else {
        direct
    }
}

#[cfg(feature = "jvm-classpath")]
fn filter_scope_targets<'a>(
    targets: Vec<&'a sqry_classpath::graph::emitter::ClasspathNodeRef>,
    allowed_jars: &std::collections::HashSet<PathBuf>,
) -> Vec<&'a sqry_classpath::graph::emitter::ClasspathNodeRef> {
    targets
        .into_iter()
        .filter(|target| allowed_jars.contains(&target.jar_path))
        .collect()
}

#[cfg(feature = "jvm-classpath")]
fn group_targets_by_fqn(
    targets: Vec<&sqry_classpath::graph::emitter::ClasspathNodeRef>,
) -> std::collections::HashMap<String, Vec<&sqry_classpath::graph::emitter::ClasspathNodeRef>> {
    let mut grouped = std::collections::HashMap::new();
    for target in targets {
        grouped
            .entry(target.fqn.clone())
            .or_insert_with(Vec::new)
            .push(target);
    }
    grouped
}

#[cfg(feature = "jvm-classpath")]
fn canonicalish_path(path: &Path) -> PathBuf {
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

#[allow(unused_variables, unused_mut)]
pub(crate) fn build_and_persist_with_optional_classpath(
    root_path: &Path,
    resolved_plugins: &plugin_defaults::ResolvedPluginManager,
    build_config: &sqry_core::graph::unified::build::BuildConfig,
    build_command: &str,
    progress: SharedReporter,
    classpath_opts: Option<&ClasspathCliOptions<'_>>,
    cache_dir: Option<&Path>,
) -> Result<BuildResult> {
    #[cfg(feature = "jvm-classpath")]
    let classpath_result = if let Some(classpath_opts) = classpath_opts.filter(|opts| opts.enabled)
    {
        run_classpath_pipeline_only(root_path, classpath_opts)?
    } else {
        None
    };

    #[cfg(not(feature = "jvm-classpath"))]
    if classpath_opts.is_some_and(|opts| opts.enabled) {
        eprintln!(
            "WARNING: --classpath flag requires the 'jvm-classpath' feature. \
             Rebuild sqry-cli with: cargo build --features jvm-classpath"
        );
    }

    let (mut graph, effective_threads) =
        sqry_core::graph::unified::build::build_unified_graph_with_progress(
            root_path,
            &resolved_plugins.plugin_manager,
            build_config,
            progress.clone(),
        )?;

    #[cfg(feature = "jvm-classpath")]
    if let Some(classpath_result) = &classpath_result {
        inject_classpath_into_graph(&mut graph, classpath_result)?;
    }

    // C001b-core: when `--cache-dir <DIR>` is supplied, persist a hash-index
    // snapshot covering every file the freshly built graph references. The
    // graph build itself is NOT short-circuited (the unified builder does not
    // yet support merging cached file segments), so the new graph is always
    // complete; this side-channel snapshot is what `sqry update` and the
    // forthcoming incremental-merge API will pick up next time.
    if let Some(dir) = cache_dir
        && let Err(err) = persist_hash_index_snapshot(&graph, dir)
    {
        log::warn!(
            "failed to persist hash index to {} ({err}); cache snapshot skipped",
            dir.display()
        );
    }

    let (_graph, build_result) = sqry_core::graph::unified::build::persist_and_analyze_graph(
        graph,
        root_path,
        &resolved_plugins.plugin_manager,
        build_config,
        build_command,
        resolved_plugins.persisted_selection.clone(),
        progress,
        effective_threads,
    )?;

    Ok(build_result)
}

/// Persist a fresh `HashIndex` capturing every parsed file from `graph` to
/// `cache_dir`. Read-side load + short-circuit is deferred (audit row
/// C001b-core); this is the save half of the pair.
fn persist_hash_index_snapshot(
    graph: &sqry_core::graph::unified::CodeGraph,
    cache_dir: &Path,
) -> Result<()> {
    use sqry_core::indexing::incremental::{FileHash, HashIndex};

    let mut index = HashIndex::new();
    let mut hashed = 0usize;
    let mut skipped = 0usize;
    for (_file_id, path) in graph.files().iter() {
        let path_ref: &Path = path.as_ref();
        match FileHash::compute(path_ref) {
            Ok(hash) => {
                index.update(path_ref.to_path_buf(), hash);
                hashed += 1;
            }
            Err(err) => {
                log::trace!(
                    "skipping hash for {} during cache snapshot: {err}",
                    path_ref.display()
                );
                skipped += 1;
            }
        }
    }
    index.save(cache_dir)?;
    log::debug!(
        "Persisted hash index snapshot to {}: {hashed} files hashed, {skipped} skipped",
        cache_dir.display()
    );
    Ok(())
}

/// Convert an [`IndexStatus`] snapshot into Prometheus / `OpenMetrics`-shaped
/// text so `sqry index --status --metrics-format prometheus` emits a payload
/// that monitoring systems can scrape.
///
/// The original (pre-v2.0) implementation operated against
/// `sqry_core::symbols::ValidationReport`, which the unified-graph migration
/// removed; this restoration projects the equivalent gauges from the surviving
/// [`IndexStatus`] surface (existence, freshness, node/file/relation counts).
fn format_validation_prometheus(status: &IndexStatus) -> String {
    use std::fmt::Write as _;

    let mut output = String::new();

    output.push_str("# HELP sqry_index_exists Whether the unified graph index exists on disk\n");
    output.push_str("# TYPE sqry_index_exists gauge\n");
    let _ = writeln!(output, "sqry_index_exists {}", u8::from(status.exists));

    output.push_str("# HELP sqry_index_supports_fuzzy Whether fuzzy search is enabled\n");
    output.push_str("# TYPE sqry_index_supports_fuzzy gauge\n");
    let _ = writeln!(
        output,
        "sqry_index_supports_fuzzy {}",
        u8::from(status.supports_fuzzy)
    );

    output
        .push_str("# HELP sqry_index_supports_relations Whether relation queries are supported\n");
    output.push_str("# TYPE sqry_index_supports_relations gauge\n");
    let _ = writeln!(
        output,
        "sqry_index_supports_relations {}",
        u8::from(status.supports_relations)
    );

    if let Some(symbols) = status.symbol_count {
        output.push_str("# HELP sqry_index_symbol_count Total number of indexed symbols\n");
        output.push_str("# TYPE sqry_index_symbol_count gauge\n");
        let _ = writeln!(output, "sqry_index_symbol_count {symbols}");
    }

    if let Some(files) = status.file_count {
        output.push_str("# HELP sqry_index_file_count Total number of indexed source files\n");
        output.push_str("# TYPE sqry_index_file_count gauge\n");
        let _ = writeln!(output, "sqry_index_file_count {files}");
    }

    if let Some(age) = status.age_seconds {
        output.push_str("# HELP sqry_index_age_seconds Index age in seconds since creation\n");
        output.push_str("# TYPE sqry_index_age_seconds gauge\n");
        let _ = writeln!(output, "sqry_index_age_seconds {age}");
    }

    if let Some(stale) = status.stale {
        output.push_str("# HELP sqry_index_stale Whether the index is considered stale\n");
        output.push_str("# TYPE sqry_index_stale gauge\n");
        let _ = writeln!(output, "sqry_index_stale {}", u8::from(stale));
    }

    if let Some(relations) = status.cross_language_relation_count {
        output.push_str(
            "# HELP sqry_index_cross_language_relation_count Total cross-language relations\n",
        );
        output.push_str("# TYPE sqry_index_cross_language_relation_count gauge\n");
        let _ = writeln!(
            output,
            "sqry_index_cross_language_relation_count {relations}"
        );
    }

    output
}

/// Run index build command
///
/// # Arguments
///
/// * `cli` - CLI configuration (for validation flags)
/// * `path` - Directory to index
/// * `force` - Force rebuild even if index exists
/// * `threads` - Number of threads for parallel indexing (None = auto-detect)
///
/// # Errors
///
/// Returns an error if index build or persistence fails.
///
/// # Panics
///
/// Panics if the index is missing after a successful build-and-save sequence.
#[allow(clippy::fn_params_excessive_bools)] // CLI flags map directly to booleans.
#[allow(clippy::too_many_arguments)]
/// Build a fresh index for the given path.
///
/// STEP_8 precedence: callers must resolve `path` via
/// [`crate::args::Cli::resolve_subcommand_path`] so that an explicit positional
/// `<path>` always wins over the global `--workspace` / `SQRY_WORKSPACE_FILE`
/// flag. This function trusts the caller to have applied that precedence.
pub fn run_index(
    cli: &Cli,
    path: &str,
    force: bool,
    threads: Option<usize>,
    add_to_gitignore: bool,
    no_incremental: bool,
    cache_dir: Option<&str>,
    enable_macro_expansion: bool,
    cfg_flags: &[String],
    expand_cache: Option<&std::path::Path>,
    classpath: bool,
    _no_classpath: bool,
    classpath_depth: crate::args::ClasspathDepthArg,
    classpath_file: Option<&Path>,
    build_system: Option<&str>,
    force_classpath: bool,
    allow_nested: bool,
) -> Result<()> {
    if let Some(0) = threads {
        anyhow::bail!("--threads must be >= 1");
    }

    let root_path = Path::new(path);

    handle_gitignore(root_path, add_to_gitignore);

    // Check if graph already exists
    let storage = GraphStorage::new(root_path);
    // C001a: `--no-incremental` forces a full rebuild even when a snapshot
    // exists, so the early-exit gate honours it alongside `--force`.
    if storage.exists() && !force && !no_incremental {
        println!("Index already exists at {}", storage.graph_dir().display());
        println!("Use --force to rebuild, or run 'sqry update' to update incrementally");
        return Ok(());
    }

    // Cluster-E §E.3 — refuse to create a nested `.sqry/` inside an outer
    // project that already has its own graph. The guard fires only on
    // *fresh* creation: existing graphs at `root_path` (handled by the
    // exit-gate above) and `--allow-nested` opt-in are exempt.
    if !storage.exists()
        && let Err(e) = sqry_core::workspace::assert_no_ancestor_graph(root_path, allow_nested)
    {
        anyhow::bail!("{e}");
    }

    // Log macro boundary analysis configuration
    if enable_macro_expansion || !cfg_flags.is_empty() || expand_cache.is_some() {
        log::info!(
            "Macro boundary config: expansion={enable_macro_expansion}, cfg_flags={cfg_flags:?}, expand_cache={expand_cache:?}",
        );
    }

    print_index_build_banner(root_path, threads);

    let start = Instant::now();
    let mut step_runner = StepRunner::new(!std::io::stderr().is_terminal() && !cli.json);

    let (progress_bar, progress) = create_progress_reporter(cli);

    // Build unified graph using the consolidated pipeline
    let build_config = create_build_config(cli, root_path, threads)?;
    let resolved_plugins =
        plugin_defaults::resolve_plugin_selection(cli, root_path, PluginSelectionMode::FreshWrite)?;
    let classpath_opts = ClasspathCliOptions {
        enabled: classpath,
        depth: classpath_depth,
        classpath_file,
        build_system,
        force_classpath,
    };
    // C001b: surface `--cache-dir` to the build pipeline so the post-parse
    // hash-index snapshot lands in the operator-supplied directory.
    let cache_dir_path = cache_dir.map(Path::new);
    let build_result = step_runner.step("Build unified graph", || -> Result<_> {
        build_and_persist_with_optional_classpath(
            root_path,
            &resolved_plugins,
            &build_config,
            "cli:index",
            progress.clone(),
            Some(&classpath_opts),
            cache_dir_path,
        )
    })?;

    finish_progress_bar(progress_bar.as_ref());

    let elapsed = start.elapsed();

    // Emit thread pool metrics if requested (diagnostic feature)
    if std::env::var("SQRY_EMIT_THREAD_POOL_METRICS")
        .ok()
        .is_some_and(|v| v == "1")
    {
        let metrics = ThreadPoolMetrics {
            thread_pool_creations: 1,
        };
        if let Ok(json) = serde_json::to_string(&metrics) {
            println!("{json}");
        }
    }

    // Report success
    if !cli.json {
        let status = build_graph_status(&storage)?;
        emit_graph_summary(
            &storage,
            &status,
            &build_result,
            elapsed,
            "✓ Index built successfully!",
        );
    }

    Ok(())
}

fn emit_graph_summary(
    storage: &GraphStorage,
    status: &IndexStatus,
    build_result: &BuildResult,
    elapsed: std::time::Duration,
    summary_banner: &str,
) {
    println!("\n{summary_banner}");
    println!(
        "  Graph: {} nodes, {} canonical edges ({} raw)",
        build_result.node_count, build_result.edge_count, build_result.raw_edge_count
    );
    println!(
        "  Corpus: {} files across {} languages",
        build_result.total_files,
        build_result.file_count.len()
    );
    println!(
        "  Top languages: {}",
        format_top_languages(&build_result.file_count)
    );
    println!(
        "  Reachability: {}",
        format_analysis_strategy_highlights(&build_result.analysis_strategies)
    );
    if !build_result.active_plugin_ids.is_empty() {
        println!(
            "  Active plugins: {}",
            build_result.active_plugin_ids.join(", ")
        );
    }
    if status.supports_relations {
        println!("  Relations: Enabled");
    }
    println!("  Graph path: {}", storage.graph_dir().display());
    println!("  Analysis path: {}", storage.analysis_dir().display());
    println!("  Time taken: {:.2}s", elapsed.as_secs_f64());
}

fn print_index_build_banner(root_path: &Path, threads: Option<usize>) {
    if let Some(1) = threads {
        println!(
            "Building index for {} (single-threaded)...",
            root_path.display()
        );
    } else if let Some(count) = threads {
        println!(
            "Building index for {} using {} threads...",
            root_path.display(),
            count
        );
    } else {
        println!("Building index for {} (parallel)...", root_path.display());
    }
}

pub(crate) fn create_progress_reporter(
    cli: &Cli,
) -> (Option<Arc<CliProgressReporter>>, SharedReporter) {
    // Create progress reporter (disable when not connected to a TTY)
    let progress_bar = if std::io::stderr().is_terminal() && !cli.json {
        Some(Arc::new(CliProgressReporter::new()))
    } else {
        None
    };

    let progress: SharedReporter = if let Some(progress_bar_ref) = &progress_bar {
        Arc::clone(progress_bar_ref) as SharedReporter
    } else if cli.json {
        no_op_reporter()
    } else {
        Arc::new(CliStepProgressReporter::new()) as SharedReporter
    };

    (progress_bar, progress)
}

fn finish_progress_bar(progress_bar: Option<&Arc<CliProgressReporter>>) {
    if let Some(progress_bar_ref) = progress_bar {
        progress_bar_ref.finish();
    }
}

// emit_index_summary removed — logic inlined in run_index
// handle_update_validation removed — validation moved to core
// emit_validation_failures removed — validation moved to core
// handle_validation_strictness removed — validation moved to core

// emit_update_summary removed

// build_index_status removed

// collect_languages removed

// write_index_status_json removed
// write_index_status_text removed
// write_index_status_found removed
// write_index_status_metadata removed
// write_index_status_missing removed
// write_validation_report_text removed
// write_dependency_validation removed
// write_id_validation removed
// write_graph_validation removed

fn build_graph_status(storage: &GraphStorage) -> Result<IndexStatus> {
    let snapshot_exists = storage.snapshot_path().exists();
    let manifest_exists = storage.manifest_path().exists();

    match (snapshot_exists, manifest_exists) {
        (false, false) => return Ok(IndexStatus::not_found()),
        (true, false) => {
            // Cluster-G §4.3 — daemon-built snapshot. The daemon's
            // `QueryDbHook` writes `snapshot.sqry` without a manifest,
            // so `storage.exists()` (which checks the manifest) would
            // mis-report "no graph snapshot found". Read the
            // node/edge counts from the snapshot header instead.
            let header = match load_header_from_path(storage.snapshot_path()) {
                Ok(h) => h,
                Err(e) => {
                    return Err(anyhow::anyhow!(
                        "snapshot present at {} but unreadable: {e}",
                        storage.snapshot_path().display()
                    ));
                }
            };
            // The snapshot header carries the file count but no
            // built_at timestamp; surface "unknown" so downstream
            // renderers can decide what to show.
            return Ok(IndexStatus::from_index(
                storage.graph_dir().display().to_string(),
                "unknown (daemon-built; no manifest)".to_string(),
                0,
            )
            .symbol_count(header.node_count)
            .file_count_opt(Some(header.file_count))
            .has_relations(header.edge_count > 0)
            .has_trigram(false)
            .build());
        }
        (false, true) => {
            // Manifest without a snapshot — corrupt half-built state.
            return Err(anyhow::anyhow!(
                "manifest at {} but no snapshot at {}; rebuild with `sqry index --force`",
                storage.manifest_path().display(),
                storage.snapshot_path().display()
            ));
        }
        (true, true) => {
            // Existing path: both files present, fall through.
        }
    }

    // Load manifest
    let manifest = storage
        .load_manifest()
        .context("Failed to load graph manifest")?;

    // Compute age
    let age_seconds = storage
        .snapshot_age(&manifest)
        .context("Failed to compute snapshot age")?
        .as_secs();

    // Get file count: prefer snapshot header (fast), fallback to manifest (CLI-built indexes)
    let total_files: Option<usize> =
        if let Ok(header) = load_header_from_path(storage.snapshot_path()) {
            // Read from snapshot header (always accurate)
            Some(header.file_count)
        } else if !manifest.file_count.is_empty() {
            // Fallback: sum manifest file counts (legacy CLI-built indexes)
            Some(manifest.file_count.values().sum())
        } else {
            // No file count available
            None
        };

    // Check if trigram index exists in graph storage
    // Trigram files would be stored alongside the snapshot
    let trigram_path = storage.graph_dir().join("trigram.idx");
    let has_trigram = trigram_path.exists();

    // Build status (map graph data to IndexStatus for compatibility)
    Ok(IndexStatus::from_index(
        storage.graph_dir().display().to_string(),
        manifest.built_at.clone(),
        age_seconds,
    )
    .symbol_count(manifest.node_count) // Map nodes → symbols
    .file_count_opt(total_files)
    .has_relations(manifest.edge_count > 0)
    .has_trigram(has_trigram)
    .build())
}

fn write_graph_status_text(
    streams: &mut crate::output::OutputStreams,
    status: &IndexStatus,
    root_path: &Path,
) -> Result<()> {
    if status.exists {
        streams.write_result("✓ Graph snapshot found\n")?;
        if let Some(path) = &status.path {
            streams.write_result(&format!("  Path: {path}\n"))?;
        }
        if let Some(created_at) = &status.created_at {
            streams.write_result(&format!("  Built: {created_at}\n"))?;
        }
        if let Some(age) = status.age_seconds {
            streams.write_result(&format!("  Age: {}\n", format_age(age)))?;
        }
        if let Some(count) = status.symbol_count {
            streams.write_result(&format!("  Nodes: {count}\n"))?;
        }
        if let Some(count) = status.file_count {
            streams.write_result(&format!("  Files: {count}\n"))?;
        }
        if status.supports_relations {
            streams.write_result("  Relations: ✓ Available\n")?;
        }
    } else {
        streams.write_result("✗ No graph snapshot found\n")?;
        streams.write_result("\nTo create a graph snapshot, run:\n")?;
        streams.write_result(&format!("  sqry index --force {}\n", root_path.display()))?;
    }

    Ok(())
}

fn format_age(age_seconds: u64) -> String {
    let hours = age_seconds / 3600;
    let days = hours / 24;
    if days > 0 {
        format!("{} days, {} hours", days, hours % 24)
    } else {
        format!("{hours} hours")
    }
}

fn format_top_languages(file_count: &std::collections::HashMap<String, usize>) -> String {
    if file_count.is_empty() {
        return "none".to_string();
    }

    let mut entries: Vec<_> = file_count.iter().collect();
    entries.sort_by(|(left_name, left_count), (right_name, right_count)| {
        right_count
            .cmp(left_count)
            .then_with(|| left_name.cmp(right_name))
    });

    entries
        .into_iter()
        .take(3)
        .map(|(language, count)| format!("{language}={count}"))
        .collect::<Vec<_>>()
        .join(", ")
}

fn format_analysis_strategy_highlights(analysis_strategies: &[AnalysisStrategySummary]) -> String {
    if analysis_strategies.is_empty() {
        return "not available".to_string();
    }

    let mut interval_labels = Vec::new();
    let mut dag_bfs = Vec::new();

    for strategy in analysis_strategies {
        match strategy.strategy {
            ReachabilityStrategy::IntervalLabels => interval_labels.push(strategy.edge_kind),
            ReachabilityStrategy::DagBfs => dag_bfs.push(strategy.edge_kind),
        }
    }

    let mut groups = Vec::new();
    if !interval_labels.is_empty() {
        groups.push(format!("interval_labels({})", interval_labels.join(",")));
    }
    if !dag_bfs.is_empty() {
        groups.push(format!("dag_bfs({})", dag_bfs.join(",")));
    }

    groups.join(" | ")
}

/// Create a `BuildConfig` from CLI flags.
pub(crate) fn create_build_config(
    cli: &Cli,
    root_path: &Path,
    threads: Option<usize>,
) -> Result<sqry_core::graph::unified::build::BuildConfig> {
    Ok(sqry_core::graph::unified::build::BuildConfig {
        max_depth: if cli.max_depth == 0 {
            None
        } else {
            Some(cli.max_depth)
        },
        follow_links: cli.follow,
        include_hidden: cli.hidden,
        num_threads: threads,
        label_budget: sqry_core::graph::unified::analysis::resolve_label_budget_config(
            root_path, None, None, None, false,
        )?,
        ..sqry_core::graph::unified::build::BuildConfig::default()
    })
}

/// Run index update command
///
/// # Arguments
///
/// * `cli` - CLI configuration (for validation flags)
/// * `path` - Directory with existing index
/// * `show_stats` - Show detailed statistics
///
/// # Errors
/// Returns an error if the index cannot be loaded, updated, or validated.
#[allow(clippy::too_many_arguments)]
#[allow(clippy::fn_params_excessive_bools)] // CLI flags map directly to booleans.
pub fn run_update(
    cli: &Cli,
    path: &str,
    threads: Option<usize>,
    show_stats: bool,
    _no_incremental: bool,
    cache_dir: Option<&str>,
    classpath: bool,
    _no_classpath: bool,
    classpath_depth: crate::args::ClasspathDepthArg,
    classpath_file: Option<&Path>,
    build_system: Option<&str>,
    force_classpath: bool,
) -> Result<()> {
    let root_path = Path::new(path);
    let mut step_runner = StepRunner::new(!std::io::stderr().is_terminal() && !cli.json);

    // Check if graph exists
    let storage = GraphStorage::new(root_path);
    if !storage.exists() {
        anyhow::bail!(
            "No index found at {}. Run 'sqry index' first.",
            storage.graph_dir().display()
        );
    }

    println!("Updating index for {}...", root_path.display());
    let start = Instant::now();

    // Determine update mode based on git availability
    let git_mode_disabled = std::env::var("SQRY_GIT_BACKEND")
        .ok()
        .is_some_and(|v| v == "none");

    let current_commit = if git_mode_disabled {
        None
    } else {
        get_git_head_commit(root_path)
    };

    // Determine if we're using git-aware or hash-based mode
    let using_git_mode = !git_mode_disabled && current_commit.is_some();

    let (progress_bar, progress) = create_progress_reporter(cli);

    // Update graph using consolidated pipeline
    let build_config = create_build_config(cli, root_path, threads)?;
    let resolved_plugins = plugin_defaults::resolve_plugin_selection(
        cli,
        root_path,
        PluginSelectionMode::ExistingWrite,
    )?;
    let classpath_opts = ClasspathCliOptions {
        enabled: classpath,
        depth: classpath_depth,
        classpath_file,
        build_system,
        force_classpath,
    };
    let cache_dir_path = cache_dir.map(Path::new);
    let build_result = step_runner.step("Update unified graph", || -> Result<_> {
        build_and_persist_with_optional_classpath(
            root_path,
            &resolved_plugins,
            &build_config,
            "cli:update",
            progress.clone(),
            Some(&classpath_opts),
            cache_dir_path,
        )
    })?;

    finish_progress_bar(progress_bar.as_ref());

    let elapsed = start.elapsed();

    // Report success with appropriate message based on update mode
    if !cli.json {
        let status = build_graph_status(&storage)?;

        if using_git_mode {
            emit_graph_summary(
                &storage,
                &status,
                &build_result,
                elapsed,
                "✓ Index updated successfully!",
            );
        } else {
            emit_graph_summary(
                &storage,
                &status,
                &build_result,
                elapsed,
                "✓ Index updated successfully (hash-based mode)!",
            );
        }
    }

    if show_stats {
        println!("(Detailed stats are not available for unified graph update)");
    }

    Ok(())
}

#[allow(deprecated)]
/// Run index status command for programmatic consumers.
///
/// # Arguments
///
/// * `cli` - CLI configuration
/// * `path` - Directory to check for index
///
/// # Errors
/// Returns an error if the index status cannot be loaded or rendered.
pub fn run_index_status(
    cli: &Cli,
    path: &str,
    metrics_format: crate::args::MetricsFormat,
) -> Result<()> {
    use crate::args::MetricsFormat;

    // Prometheus output bypasses the JSON / text branch and emits an
    // OpenMetrics-shaped scrape payload built from the current IndexStatus.
    if matches!(metrics_format, MetricsFormat::Prometheus) {
        let root_path = Path::new(path);
        let storage = GraphStorage::new(root_path);
        let status = build_graph_status(&storage)?;
        let mut streams = crate::output::OutputStreams::with_pager(cli.pager_config());
        let body = format_validation_prometheus(&status);
        streams.write_result(&body)?;
        return streams.finish_checked();
    }

    // JSON / text path: defer to the unified graph status renderer.
    // Programmatic consumers of `run_index_status` only express JSON intent
    // through `cli.json`, so do not synthesize an extra override here.
    run_graph_status_with_format(cli, path, false)
}

/// Run graph status command using unified graph architecture.
///
/// This command reports on the state of the unified graph snapshot stored in
/// the `.sqry/graph/` directory instead of the legacy `.sqry-index`.
///
/// `json_from_format` carries the threaded `--format` decision computed by
/// `resolve_graph_format` at the `Command::Graph` boundary, so that
/// `sqry graph --format json status` honors the alias contract for the
/// global `--json` flag and the per-subcommand `--json` flag (verivus-oss/sqry#79
/// / verivus-oss/sqry#158). The non-`--format` paths continue to flow
/// through `cli.json`.
///
/// # Errors
///
/// Returns an error if manifest cannot be loaded or output formatting fails.
pub fn run_graph_status_with_format(cli: &Cli, path: &str, json_from_format: bool) -> Result<()> {
    let root_path = Path::new(path);
    let storage = GraphStorage::new(root_path);
    let status = build_graph_status(&storage)?;

    // Output result (same format as run_index_status for compatibility)
    let mut streams = crate::output::OutputStreams::with_pager(cli.pager_config());

    let json_out = cli.json || json_from_format;
    if json_out {
        let json =
            serde_json::to_string_pretty(&status).context("Failed to serialize graph status")?;
        streams.write_result(&json)?;
    } else {
        write_graph_status_text(&mut streams, &status, root_path)?;
    }

    streams.finish_checked()
}

/// Handles the .gitignore check and modification.
fn handle_gitignore(path: &Path, add_to_gitignore: bool) {
    if let Some(root) = find_git_root(path) {
        let gitignore_path = root.join(".gitignore");
        let entry = ".sqry-index/";
        let mut is_already_indexed = false;

        if gitignore_path.exists()
            && let Ok(file) = fs::File::open(&gitignore_path)
        {
            let reader = BufReader::new(file);
            if reader.lines().any(|line| {
                line.map(|l| l.trim() == ".sqry-index" || l.trim() == ".sqry-index/")
                    .unwrap_or(false)
            }) {
                is_already_indexed = true;
            }
        }

        if !is_already_indexed
            && add_to_gitignore
            && let Ok(mut file) = fs::OpenOptions::new()
                .append(true)
                .create(true)
                .open(&gitignore_path)
            && writeln!(file, "\n{entry}").is_ok()
        {
            println!("Added '{entry}' to .gitignore");
        } else if !is_already_indexed {
            print_gitignore_warning();
        }
    }
}

/// Find the root of the git repository by traversing up from the given path.
fn find_git_root(path: &Path) -> Option<&Path> {
    let mut current = path;
    loop {
        if current.join(".git").is_dir() {
            return Some(current);
        }
        if let Some(parent) = current.parent() {
            current = parent;
        } else {
            return None;
        }
    }
}

/// Prints a standard warning message about .gitignore.
fn print_gitignore_warning() {
    eprintln!(
        "\n\u{26a0}\u{fe0f} Warning: It is recommended to add the '.sqry-index/' directory to your .gitignore file."
    );
    eprintln!("This is a generated cache and can become large.\n");
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::large_stack_test;
    use std::fs;
    use tempfile::TempDir;

    #[cfg(feature = "jvm-classpath")]
    #[test]
    fn classpath_auto_detection_miss_skips_pipeline() {
        let tmp_cli_workspace = TempDir::new().unwrap();
        let classpath_opts = ClasspathCliOptions {
            enabled: true,
            depth: crate::args::ClasspathDepthArg::Full,
            classpath_file: None,
            build_system: None,
            force_classpath: true,
        };

        let result = run_classpath_pipeline_only(tmp_cli_workspace.path(), &classpath_opts)
            .expect("missing JVM build system should be a non-fatal skip");
        assert!(result.is_none());
    }

    large_stack_test! {
    #[test]
    fn test_run_index_basic() {
        use crate::args::Cli;
        use clap::Parser;

        let tmp_cli_workspace = TempDir::new().unwrap();
        let file_path = tmp_cli_workspace.path().join("test.rs");
        fs::write(&file_path, "fn hello() {}").unwrap();

        let cli = Cli::parse_from(["sqry", "index"]);
        let result = run_index(
            &cli,
            tmp_cli_workspace.path().to_str().unwrap(),
            false,
            None,
            false,
            false,
            None,
            false, // enable_macro_expansion
            &[],  // cfg_flags
            None, // expand_cache
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
            false, // allow_nested
        );
        assert!(result.is_ok());

        // Check index was created
        let storage = GraphStorage::new(tmp_cli_workspace.path());
        assert!(storage.exists());
    }
    }

    large_stack_test! {
    #[test]
    fn test_run_index_force_rebuild() {
        use crate::args::Cli;
        use clap::Parser;

        let tmp_cli_workspace = TempDir::new().unwrap();
        let file_path = tmp_cli_workspace.path().join("test.rs");
        fs::write(&file_path, "fn hello() {}").unwrap();

        let cli = Cli::parse_from(["sqry", "index"]);

        // Build initial index
        run_index(
            &cli,
            tmp_cli_workspace.path().to_str().unwrap(),
            false,
            None,
            false,
            false,
            None,
            false, // enable_macro_expansion
            &[],   // cfg_flags
            None,  // expand_cache
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
            false, // allow_nested
        )
        .unwrap();

        // Try to rebuild without force (should skip)
        let result = run_index(
            &cli,
            tmp_cli_workspace.path().to_str().unwrap(),
            false,
            None,
            false,
            false,
            None,
            false, // enable_macro_expansion
            &[],   // cfg_flags
            None,  // expand_cache
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
            false, // allow_nested
        );
        assert!(result.is_ok());

        // Rebuild with force (should succeed)
        let result = run_index(
            &cli,
            tmp_cli_workspace.path().to_str().unwrap(),
            true,
            None,
            false,
            false,
            None,
            false, // enable_macro_expansion
            &[],   // cfg_flags
            None,  // expand_cache
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
            false, // allow_nested
        );
        assert!(result.is_ok());
    }
    }

    large_stack_test! {
    #[test]
    fn test_run_update_no_index() {
        use crate::args::Cli;
        use clap::Parser;

        let tmp_cli_workspace = TempDir::new().unwrap();
        let cli = Cli::parse_from(["sqry", "update"]);

        let result = run_update(
            &cli,
            tmp_cli_workspace.path().to_str().unwrap(),
            None,
            false,
            false,
            None,
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("No index found"));
    }
    }

    large_stack_test! {
    #[test]
    fn test_run_index_status_no_index() {
        use crate::args::Cli;
        use clap::Parser;

        let tmp_cli_workspace = TempDir::new().unwrap();

        // Create CLI with JSON flag
        let cli = Cli::parse_from(["sqry", "--json"]);

        // Should succeed even with no index
        let result = run_index_status(
            &cli,
            tmp_cli_workspace.path().to_str().unwrap(),
            crate::args::MetricsFormat::Json,
        );
        assert!(
            result.is_ok(),
            "Index status should not error on missing index"
        );

        // The output would be captured via OutputStreams
        // We can't easily test the output here, but we verified it doesn't panic
    }
    }

    large_stack_test! {
    #[test]
    fn test_run_index_status_with_index() {
        use crate::args::Cli;
        use clap::Parser;

        let tmp_cli_workspace = TempDir::new().unwrap();
        let file_path = tmp_cli_workspace.path().join("test.rs");
        fs::write(&file_path, "fn test_func() {}").unwrap();

        let cli = Cli::parse_from(["sqry", "index"]);

        // Build index first
        run_index(
            &cli,
            tmp_cli_workspace.path().to_str().unwrap(),
            false,
            None,
            false,
            false,
            None,
            false, // enable_macro_expansion
            &[],   // cfg_flags
            None,  // expand_cache
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
            false, // allow_nested
        )
        .unwrap();

        // Check status with JSON flag
        let cli = Cli::parse_from(["sqry", "--json"]);
        let result = run_index_status(
            &cli,
            tmp_cli_workspace.path().to_str().unwrap(),
            crate::args::MetricsFormat::Json,
        );
        assert!(
            result.is_ok(),
            "Index status should succeed with existing index"
        );

        // Verify the index actually exists
        let storage = GraphStorage::new(tmp_cli_workspace.path());
        assert!(storage.exists());

        // Load index and verify it has the symbol
        let manifest = storage.load_manifest().unwrap();
        assert_eq!(manifest.node_count, 1, "Should have 1 symbol");
    }
    }

    large_stack_test! {
    #[test]
    fn test_run_update_basic() {
        use crate::args::Cli;
        use clap::Parser;

        let tmp_cli_workspace = TempDir::new().unwrap();
        let file_path = tmp_cli_workspace.path().join("test.rs");
        fs::write(&file_path, "fn hello() {}").unwrap();

        let cli = Cli::parse_from(["sqry", "index"]);

        // Build initial index
        run_index(
            &cli,
            tmp_cli_workspace.path().to_str().unwrap(),
            false,
            None,
            false,
            false,
            None,
            false, // enable_macro_expansion
            &[],   // cfg_flags
            None,  // expand_cache
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
            false, // allow_nested
        )
        .unwrap();

        // Update should succeed
        let result = run_update(
            &cli,
            tmp_cli_workspace.path().to_str().unwrap(),
            None,
            true,
            false,
            None,
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
        );
        assert!(result.is_ok());
    }
    }

    large_stack_test! {
    #[test]
    fn test_no_incremental_triggers_full_rebuild_when_snapshot_exists() {
        // C001a: `sqry index --no-incremental` must rebuild the graph even
        // when `.sqry/graph/snapshot.sqry` already exists (without `--force`).
        use crate::args::Cli;
        use clap::Parser;

        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("rebuild.rs");
        fs::write(&file_path, "fn original() {}").unwrap();

        let cli = Cli::parse_from(["sqry", "index"]);

        // Initial build with one symbol.
        run_index(
            &cli,
            tmp.path().to_str().unwrap(),
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            None,
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
            false, // allow_nested
        )
        .expect("initial build should succeed");

        let storage = GraphStorage::new(tmp.path());
        assert!(storage.exists(), "snapshot must exist after initial build");
        let initial_node_count = storage.load_manifest().unwrap().node_count;

        // Add a second symbol and re-run with `--no-incremental` (force = false).
        // Without C001a, run_index would early-exit because the snapshot
        // already exists; the new symbol would not appear in the manifest.
        fs::write(&file_path, "fn original() {}\nfn added_symbol() {}").unwrap();

        run_index(
            &cli,
            tmp.path().to_str().unwrap(),
            false, // force = false
            None,
            false,
            true,  // no_incremental = true ← drives the full-rebuild path
            None,
            false,
            &[],
            None,
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
            false, // allow_nested
        )
        .expect("--no-incremental must rebuild even when snapshot exists");

        let post_rebuild_node_count = storage.load_manifest().unwrap().node_count;
        assert!(
            post_rebuild_node_count > initial_node_count,
            "--no-incremental should rebuild and pick up the new symbol \
             (initial={initial_node_count}, post={post_rebuild_node_count})"
        );
    }
    }

    #[test]
    fn format_validation_prometheus_emits_openmetrics_shape() {
        // C001d-a: the restored Prometheus formatter must emit HELP/TYPE
        // metadata plus the gauge sample lines for every populated field.
        let mut status = IndexStatus::not_found();
        status.exists = true;
        status.path = Some("/tmp/example/.sqry/graph".into());
        status.age_seconds = Some(42);
        status.symbol_count = Some(123);
        status.file_count = Some(11);
        status.supports_relations = true;
        status.cross_language_relation_count = Some(9);
        status.stale = Some(false);

        let body = format_validation_prometheus(&status);

        assert!(body.contains("# HELP sqry_index_exists"));
        assert!(body.contains("# TYPE sqry_index_exists gauge"));
        assert!(body.contains("\nsqry_index_exists 1\n"));
        assert!(body.contains("\nsqry_index_supports_relations 1\n"));
        assert!(body.contains("\nsqry_index_symbol_count 123\n"));
        assert!(body.contains("\nsqry_index_file_count 11\n"));
        assert!(body.contains("\nsqry_index_age_seconds 42\n"));
        assert!(body.contains("\nsqry_index_stale 0\n"));
        assert!(body.contains("\nsqry_index_cross_language_relation_count 9\n"));
    }

    large_stack_test! {
    #[test]
    fn run_index_status_prometheus_format_is_accepted() {
        // C001d-b: invoking `run_index_status` with `MetricsFormat::Prometheus`
        // must succeed (formerly the value was silently dropped via a `_`
        // prefix; now it routes through the restored formatter).
        use crate::args::{Cli, MetricsFormat};
        use clap::Parser;

        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("metrics.rs");
        fs::write(&file_path, "fn metric_target() {}").unwrap();

        let cli = Cli::parse_from(["sqry", "index"]);
        run_index(
            &cli,
            tmp.path().to_str().unwrap(),
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            None,
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
            false, // allow_nested
        )
        .expect("initial build for prometheus test must succeed");

        let cli_json = Cli::parse_from(["sqry", "--json"]);
        let result = run_index_status(
            &cli_json,
            tmp.path().to_str().unwrap(),
            MetricsFormat::Prometheus,
        );
        assert!(
            result.is_ok(),
            "--metrics-format prometheus must succeed: {result:?}"
        );
    }
    }

    // Cluster-E §E.3 — `run_index` refuses to create a nested `.sqry/`
    // when an outer project already has its own graph and the same
    // project boundary contains both. The recovery message names all
    // three paths.
    large_stack_test! {
    #[test]
    fn run_index_rejects_nested_creation_without_allow_nested() {
        use crate::args::Cli;
        use clap::Parser;

        let tmp = TempDir::new().unwrap();
        // Outer project: Cargo.toml + .sqry/graph already in place.
        let proj = tmp.path().join("proj");
        fs::create_dir_all(proj.join(".sqry").join("graph")).unwrap();
        fs::write(proj.join("Cargo.toml"), "[package]\n").unwrap();
        // Inner directory the user mistakenly tries to index.
        let nested = proj.join("sub");
        fs::create_dir_all(&nested).unwrap();

        let cli = Cli::parse_from(["sqry", "index"]);
        let result = run_index(
            &cli,
            nested.to_str().unwrap(),
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            None,
            false,
            false,
            crate::args::ClasspathDepthArg::Full,
            None,
            None,
            false,
            false, // allow_nested = false → guard fires
        );
        let err = result.expect_err("nested creation must error without --allow-nested");
        let msg = err.to_string();
        assert!(
            msg.contains("nested .sqry/ index"),
            "must surface the nested-index recovery text, got: {msg}"
        );
        assert!(
            msg.contains("--allow-nested"),
            "must hint at the --allow-nested escape hatch, got: {msg}"
        );
    }
    }

    #[test]
    fn plugin_manager_registers_elixir_extensions() {
        let pm = crate::plugin_defaults::create_plugin_manager();
        assert!(
            pm.plugin_for_extension("ex").is_some(),
            "Elixir .ex extension missing"
        );
        assert!(
            pm.plugin_for_extension("exs").is_some(),
            "Elixir .exs extension missing"
        );
    }

    #[test]
    fn test_format_top_languages_orders_by_count_then_name() {
        let counts = std::collections::HashMap::from([
            ("rust".to_string(), 9_usize),
            ("python".to_string(), 4_usize),
            ("go".to_string(), 4_usize),
            ("typescript".to_string(), 2_usize),
        ]);

        assert_eq!(format_top_languages(&counts), "rust=9, go=4, python=4");
    }

    #[test]
    fn test_format_analysis_strategy_highlights_groups_by_strategy() {
        let strategies = vec![
            AnalysisStrategySummary {
                edge_kind: "calls",
                strategy: ReachabilityStrategy::IntervalLabels,
            },
            AnalysisStrategySummary {
                edge_kind: "imports",
                strategy: ReachabilityStrategy::DagBfs,
            },
            AnalysisStrategySummary {
                edge_kind: "references",
                strategy: ReachabilityStrategy::DagBfs,
            },
            AnalysisStrategySummary {
                edge_kind: "inherits",
                strategy: ReachabilityStrategy::IntervalLabels,
            },
        ];

        assert_eq!(
            format_analysis_strategy_highlights(&strategies),
            "interval_labels(calls,inherits) | dag_bfs(imports,references)"
        );
    }

    #[cfg(feature = "jvm-classpath")]
    #[test]
    fn test_resolve_allowed_jars_prefers_nearest_scope() {
        let scopes = vec![
            (
                PathBuf::from("/repo/services/app"),
                std::collections::HashSet::from([PathBuf::from("/jars/app.jar")]),
            ),
            (
                PathBuf::from("/repo"),
                std::collections::HashSet::from([PathBuf::from("/jars/root.jar")]),
            ),
        ];

        let resolved =
            resolve_allowed_jars(Some(Path::new("/repo/services/app/src/Main.java")), &scopes)
                .expect("nearest scope should resolve");
        assert!(
            resolved
                .allowed_jars
                .contains(&PathBuf::from("/jars/app.jar"))
        );
        assert!(
            !resolved
                .allowed_jars
                .contains(&PathBuf::from("/jars/root.jar"))
        );
        assert_eq!(
            resolved.matched_root.as_deref(),
            Some(Path::new("/repo/services/app"))
        );
    }

    #[cfg(feature = "jvm-classpath")]
    #[test]
    fn test_filter_scope_targets_excludes_out_of_scope_jars() {
        let targets = [
            sqry_classpath::graph::emitter::ClasspathNodeRef {
                node_id: sqry_core::graph::unified::node::NodeId::new(1, 0),
                fqn: "com.example.Foo".to_string(),
                jar_path: PathBuf::from("/jars/app.jar"),
                file_id: sqry_core::graph::unified::FileId::new(1),
            },
            sqry_classpath::graph::emitter::ClasspathNodeRef {
                node_id: sqry_core::graph::unified::node::NodeId::new(2, 0),
                fqn: "com.example.Foo".to_string(),
                jar_path: PathBuf::from("/jars/other.jar"),
                file_id: sqry_core::graph::unified::FileId::new(2),
            },
        ];
        let allowed = std::collections::HashSet::from([PathBuf::from("/jars/app.jar")]);

        let filtered = filter_scope_targets(targets.iter().collect(), &allowed);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].jar_path, PathBuf::from("/jars/app.jar"));
    }

    #[cfg(feature = "jvm-classpath")]
    #[test]
    fn test_prefer_direct_targets_exact_import_direct_wins() {
        use sqry_classpath::graph::provenance::{ClasspathProvenance, ClasspathScope};

        let targets = [
            sqry_classpath::graph::emitter::ClasspathNodeRef {
                node_id: sqry_core::graph::unified::node::NodeId::new(1, 0),
                fqn: "com.example.Foo".to_string(),
                jar_path: PathBuf::from("/jars/direct.jar"),
                file_id: sqry_core::graph::unified::FileId::new(1),
            },
            sqry_classpath::graph::emitter::ClasspathNodeRef {
                node_id: sqry_core::graph::unified::node::NodeId::new(2, 0),
                fqn: "com.example.Foo".to_string(),
                jar_path: PathBuf::from("/jars/transitive.jar"),
                file_id: sqry_core::graph::unified::FileId::new(2),
            },
        ];

        let provenance = vec![
            ClasspathProvenance {
                jar_path: PathBuf::from("/jars/direct.jar"),
                coordinates: None,
                is_direct: true,
                scopes: vec![ClasspathScope {
                    module_name: "app".to_owned(),
                    module_root: PathBuf::from("/repo/app"),
                    is_direct: true,
                }],
            },
            ClasspathProvenance {
                jar_path: PathBuf::from("/jars/transitive.jar"),
                coordinates: None,
                is_direct: false,
                scopes: vec![ClasspathScope {
                    module_name: "app".to_owned(),
                    module_root: PathBuf::from("/repo/app"),
                    is_direct: false,
                }],
            },
        ];
        let lookup = build_provenance_lookup(&provenance);

        let result = prefer_direct_targets(
            targets.iter().collect(),
            Some(Path::new("/repo/app")),
            &lookup,
        );
        assert_eq!(result.len(), 1, "direct jar should win over transitive");
        assert_eq!(result[0].jar_path, PathBuf::from("/jars/direct.jar"));
    }

    #[cfg(feature = "jvm-classpath")]
    #[test]
    fn test_prefer_direct_targets_wildcard_same_shape() {
        use sqry_classpath::graph::provenance::{ClasspathProvenance, ClasspathScope};

        // Wildcard imports group by FQN first, then each group goes through
        // prefer_direct_targets. Simulate one FQN group with two candidates.
        let targets = [
            sqry_classpath::graph::emitter::ClasspathNodeRef {
                node_id: sqry_core::graph::unified::node::NodeId::new(10, 0),
                fqn: "com.example.Bar".to_string(),
                jar_path: PathBuf::from("/jars/direct.jar"),
                file_id: sqry_core::graph::unified::FileId::new(10),
            },
            sqry_classpath::graph::emitter::ClasspathNodeRef {
                node_id: sqry_core::graph::unified::node::NodeId::new(11, 0),
                fqn: "com.example.Bar".to_string(),
                jar_path: PathBuf::from("/jars/transitive.jar"),
                file_id: sqry_core::graph::unified::FileId::new(11),
            },
        ];

        let provenance = vec![
            ClasspathProvenance {
                jar_path: PathBuf::from("/jars/direct.jar"),
                coordinates: None,
                is_direct: true,
                scopes: vec![ClasspathScope {
                    module_name: "app".to_owned(),
                    module_root: PathBuf::from("/repo/app"),
                    is_direct: true,
                }],
            },
            ClasspathProvenance {
                jar_path: PathBuf::from("/jars/transitive.jar"),
                coordinates: None,
                is_direct: false,
                scopes: vec![ClasspathScope {
                    module_name: "app".to_owned(),
                    module_root: PathBuf::from("/repo/app"),
                    is_direct: false,
                }],
            },
        ];
        let lookup = build_provenance_lookup(&provenance);

        let result = prefer_direct_targets(
            targets.iter().collect(),
            Some(Path::new("/repo/app")),
            &lookup,
        );
        assert_eq!(
            result.len(),
            1,
            "wildcard: direct jar should win over transitive"
        );
        assert_eq!(result[0].jar_path, PathBuf::from("/jars/direct.jar"));
    }

    #[cfg(feature = "jvm-classpath")]
    #[test]
    fn test_prefer_direct_targets_true_ambiguity_two_direct_jars() {
        use sqry_classpath::graph::provenance::{ClasspathProvenance, ClasspathScope};

        // Two direct jars with the same FQN: true ambiguity, should remain
        // ambiguous (both returned).
        let targets = [
            sqry_classpath::graph::emitter::ClasspathNodeRef {
                node_id: sqry_core::graph::unified::node::NodeId::new(20, 0),
                fqn: "com.example.Baz".to_string(),
                jar_path: PathBuf::from("/jars/direct-a.jar"),
                file_id: sqry_core::graph::unified::FileId::new(20),
            },
            sqry_classpath::graph::emitter::ClasspathNodeRef {
                node_id: sqry_core::graph::unified::node::NodeId::new(21, 0),
                fqn: "com.example.Baz".to_string(),
                jar_path: PathBuf::from("/jars/direct-b.jar"),
                file_id: sqry_core::graph::unified::FileId::new(21),
            },
        ];

        let provenance = vec![
            ClasspathProvenance {
                jar_path: PathBuf::from("/jars/direct-a.jar"),
                coordinates: None,
                is_direct: true,
                scopes: vec![ClasspathScope {
                    module_name: "app".to_owned(),
                    module_root: PathBuf::from("/repo/app"),
                    is_direct: true,
                }],
            },
            ClasspathProvenance {
                jar_path: PathBuf::from("/jars/direct-b.jar"),
                coordinates: None,
                is_direct: true,
                scopes: vec![ClasspathScope {
                    module_name: "app".to_owned(),
                    module_root: PathBuf::from("/repo/app"),
                    is_direct: true,
                }],
            },
        ];
        let lookup = build_provenance_lookup(&provenance);

        let result = prefer_direct_targets(
            targets.iter().collect(),
            Some(Path::new("/repo/app")),
            &lookup,
        );
        assert_eq!(
            result.len(),
            2,
            "two direct jars = true ambiguity, both should remain"
        );
    }
}