loregrep 0.6.0

Repository indexing library for AI coding assistants. Tree-sitter parsing, fast in-memory indexing, and tool APIs for LLM integration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
// Placeholder RepoMap - will be enhanced in Phase 2: Task 2.1
use crate::storage::graph::{IndexPath, ModuleGraph, build_module_graph, normalize_path};
use crate::types::{
    AnalysisError, ExportStatement, FunctionSignature, ImportStatement, StructSignature, TreeNode,
    TypeKind,
};
use anyhow::Context;
use fuzzy_matcher::{FuzzyMatcher, skim::SkimMatcherV2};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::RwLock;
use std::time::SystemTime;

// Create our own Result type alias for this module
type Result<T> = std::result::Result<T, AnalysisError>;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CallSite {
    pub file_path: String,
    pub line_number: u32,
    pub column: u32,
    pub function_name: String,
    pub caller_function: Option<String>,
}

/// A function that transitively calls a target function, discovered by walking
/// UP the call graph. `depth` is the number of hops from the target (1 = direct
/// caller). `ambiguous` is true when this caller was reached by expanding a name
/// that has more than one definition in the repo — the call graph is name-keyed,
/// so which of those definitions the caller actually invokes cannot be
/// determined here; the caller is a *candidate*, not a confirmed link.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TransitiveCaller {
    pub function_name: String,
    pub file_path: String,
    pub depth: usize,
    #[serde(default)]
    pub ambiguous: bool,
}

#[derive(Debug, Clone)]
pub struct QueryResult<T> {
    pub items: Vec<T>,
    pub total_matches: usize,
    pub query_duration_ms: u64,
}

impl<T> QueryResult<T> {
    pub fn new(items: Vec<T>, total_matches: usize, query_duration_ms: u64) -> Self {
        Self {
            items,
            total_matches,
            query_duration_ms,
        }
    }
}

/// Compact representation of a file's key elements for repository overview
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileSkeleton {
    pub path: String,
    pub language: String,
    pub size_bytes: u64,
    pub line_count: u32,
    pub functions: Vec<FunctionSummary>,
    pub structs: Vec<StructSummary>,
    pub imports: Vec<String>,
    pub exports: Vec<String>,
    pub is_public: bool,
    pub is_test: bool,
    pub last_modified: Option<SystemTime>,
}

/// Compact function signature for repository overview
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionSummary {
    pub name: String,
    pub is_public: bool,
    pub is_async: bool,
    pub parameter_count: usize,
    pub return_type: Option<String>,
    pub line_number: u32,
}

/// Compact struct definition for repository overview  
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StructSummary {
    pub name: String,
    pub is_public: bool,
    pub field_count: usize,
    pub is_enum: bool,
    pub line_number: u32,
}

/// Directory node in the repository tree
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectoryNode {
    pub name: String,
    pub path: String,
    pub children: Vec<RepositoryTreeNode>,
    pub file_count: usize,
    pub total_lines: u32,
    pub languages: HashSet<String>,
}

/// File node in the repository tree
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileNode {
    pub name: String,
    pub path: String,
    pub skeleton: FileSkeleton,
}

/// Repository tree node (either directory or file)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum RepositoryTreeNode {
    Directory(DirectoryNode),
    File(FileNode),
}

/// Complete repository structure and overview
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepositoryTree {
    pub root: DirectoryNode,
    pub summary: RepositorySummary,
    pub generated_at: SystemTime,
}

/// High-level repository statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepositorySummary {
    pub total_files: usize,
    pub total_directories: usize,
    pub total_lines: u32,
    pub total_functions: usize,
    pub total_structs: usize,
    pub languages: HashMap<String, usize>, // language -> file count
    pub largest_files: Vec<(String, u64)>, // (path, size_bytes)
    pub function_distribution: HashMap<String, usize>, // file -> function count
    pub dependency_graph: HashMap<String, Vec<String>>, // file -> imported files
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepoMapMetadata {
    pub total_files: usize,
    pub total_functions: usize,
    pub total_structs: usize,
    pub total_imports: usize,
    pub total_exports: usize,
    pub languages: HashSet<String>,
    pub last_updated: SystemTime,
    pub memory_usage_bytes: usize,
    pub cache_hits: u64,
    pub cache_misses: u64,
}

impl Default for RepoMapMetadata {
    fn default() -> Self {
        Self {
            total_files: 0,
            total_functions: 0,
            total_structs: 0,
            total_imports: 0,
            total_exports: 0,
            languages: HashSet::new(),
            last_updated: SystemTime::now(),
            memory_usage_bytes: 0,
            cache_hits: 0,
            cache_misses: 0,
        }
    }
}

/// The outcome of resolving a caller-supplied file path against the index.
///
/// Exists because `Option<usize>` collapsed two different answers into `None`:
/// "no such file" and "several files match that suffix". A caller that renders
/// both as "not found" tells the agent its file is absent when the index in fact
/// holds ten of them, and gives it nothing to disambiguate with.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileLookup {
    /// Exactly one file matched.
    Found(usize),
    /// Several files matched the suffix; indices of every candidate, in index
    /// order. Never guess between them.
    Ambiguous(Vec<usize>),
    /// Nothing in the index matched.
    NotFound,
}

/// Enhanced RepoMap with fast lookups and comprehensive indexing
#[derive(Debug)]
pub struct RepoMap {
    // Core data
    files: Vec<TreeNode>,

    // Repository tree structure (uses RwLock for interior mutability)
    repository_tree: RwLock<Option<RepositoryTree>>,

    // Derived module graph (resolved cross-file imports). Rebuilt lazily from the
    // files after any change — never patched per file (see storage::graph).
    module_graph: RwLock<Option<ModuleGraph>>,

    // Fast indexes
    // file identity -> index. Keyed by `IndexPath`, which cannot be built
    // without normalizing, so this map and `graph::FileSet::by_path` can no
    // longer dedup on different keys (K2).
    file_index: HashMap<IndexPath, usize>,
    function_index: HashMap<String, Vec<usize>>, // function_name -> file indices
    struct_index: HashMap<String, Vec<usize>>,   // struct_name -> file indices
    import_index: HashMap<String, Vec<usize>>,   // import_path -> file indices
    export_index: HashMap<String, Vec<usize>>,   // export_name -> file indices
    language_index: HashMap<String, Vec<usize>>, // language -> file indices

    // Call graph
    call_graph: HashMap<String, Vec<CallSite>>, // function_name -> call sites

    // The directory this index was built from, as the caller named it.
    //
    // Agent-supplied paths must resolve against THIS, never the process working
    // directory, and nothing outside it may be read (see internal::paths).
    // Deliberately not derived from the indexed paths: `find_common_root_path`
    // infers a root by character-wise prefix, which is a guess, and a guess is
    // not something containment may rest on. Not serialized — a cache load
    // leaves it None until the caller sets it, and an unknown root refuses
    // rather than assuming one.
    scan_root: Option<String>,

    // Metadata
    metadata: RepoMapMetadata,

    // Memory management
    max_files: Option<usize>,

    // Query caching
    query_cache: HashMap<String, (Vec<usize>, SystemTime)>, // query -> (results, timestamp)
    cache_ttl_seconds: u64,
}

impl Clone for RepoMap {
    fn clone(&self) -> Self {
        // Clone the repository tree by reading it
        let repository_tree_clone = self.repository_tree.read().unwrap().clone();

        Self {
            files: self.files.clone(),
            repository_tree: RwLock::new(repository_tree_clone),
            // Derived; let the clone rebuild it on demand rather than deep-copying.
            module_graph: RwLock::new(None),
            file_index: self.file_index.clone(),
            scan_root: self.scan_root.clone(),
            function_index: self.function_index.clone(),
            struct_index: self.struct_index.clone(),
            import_index: self.import_index.clone(),
            export_index: self.export_index.clone(),
            language_index: self.language_index.clone(),
            call_graph: self.call_graph.clone(),
            metadata: self.metadata.clone(),
            max_files: self.max_files,
            query_cache: self.query_cache.clone(),
            cache_ttl_seconds: self.cache_ttl_seconds,
        }
    }
}

impl Default for RepoMap {
    fn default() -> Self {
        Self::new()
    }
}

impl RepoMap {
    pub fn new() -> Self {
        Self {
            files: Vec::new(),
            repository_tree: RwLock::new(None),
            module_graph: RwLock::new(None),
            file_index: HashMap::new(),
            function_index: HashMap::new(),
            struct_index: HashMap::new(),
            import_index: HashMap::new(),
            export_index: HashMap::new(),
            language_index: HashMap::new(),
            call_graph: HashMap::new(),
            scan_root: None,
            metadata: RepoMapMetadata::default(),
            max_files: None,
            query_cache: HashMap::new(),
            cache_ttl_seconds: 300, // 5 minutes
        }
    }

    pub fn with_max_files(mut self, max_files: usize) -> Self {
        self.max_files = Some(max_files);
        self
    }

    pub fn with_cache_ttl(mut self, ttl_seconds: u64) -> Self {
        self.cache_ttl_seconds = ttl_seconds;
        self
    }

    /// Add or update a file in the repository map.
    ///
    /// **This is the normalization boundary.** Every path the node carries — its
    /// own, and those on its functions/structs/imports/exports/call-sites — is
    /// rewritten to the one key form here, so nothing downstream has to remember
    /// to normalize and no two spellings of one file can occupy two slots.
    pub fn add_file(&mut self, tree_node: TreeNode) -> Result<()> {
        let tree_node = Self::canonicalize_paths(tree_node);
        let key = IndexPath::new(&tree_node.file_path);

        // Check memory limits
        if let Some(max) = self.max_files {
            if self.files.len() >= max && !self.file_index.contains_key(&key) {
                return Err(AnalysisError::Other(format!(
                    "Maximum file limit ({}) reached",
                    max
                )));
            }
        }

        // Remove existing file if present
        if let Some(&existing_index) = self.file_index.get(&key) {
            self.remove_file_by_index(existing_index);
        }

        // Add new file
        let new_index = self.files.len();
        self.files.push(tree_node.clone());

        // Update indexes
        self.update_indexes_for_file(new_index, &tree_node)?;

        // Update metadata
        self.update_metadata();

        // Clear cache as data has changed
        self.query_cache.clear();

        // Invalidate repository tree - will be rebuilt when next accessed
        self.repository_tree.write().unwrap().take();
        // The module graph is derived from the files too; invalidate it in lockstep.
        self.module_graph.write().unwrap().take();

        Ok(())
    }

    /// Rewrite every path a node carries into the single key form.
    ///
    /// Analyzers stamp the path they were handed onto each symbol they emit, so
    /// normalizing only `TreeNode::file_path` would leave `search_functions`
    /// emitting one vocabulary and `find_importers` another for the same file.
    fn canonicalize_paths(mut tree_node: TreeNode) -> TreeNode {
        let canonical = IndexPath::new(&tree_node.file_path).into_string();
        for f in &mut tree_node.functions {
            f.file_path = canonical.clone();
        }
        for s in &mut tree_node.structs {
            s.file_path = canonical.clone();
        }
        for i in &mut tree_node.imports {
            i.file_path = canonical.clone();
        }
        for e in &mut tree_node.exports {
            e.file_path = canonical.clone();
        }
        for c in &mut tree_node.function_calls {
            c.file_path = canonical.clone();
        }
        tree_node.file_path = canonical;
        tree_node
    }

    /// Remove a file from the repository map
    pub fn remove_file(&mut self, file_path: &str) -> Result<bool> {
        if let Some(&index) = self.file_index.get(&IndexPath::new(file_path)) {
            self.remove_file_by_index(index);
            self.update_metadata();
            self.query_cache.clear();

            // Invalidate repository tree - will be rebuilt when next accessed
            self.repository_tree.write().unwrap().take();
            // The module graph is derived from the files too; invalidate it in lockstep.
            self.module_graph.write().unwrap().take();

            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Get a file by path
    pub fn get_file(&self, file_path: &str) -> Option<&TreeNode> {
        self.file_index
            .get(&IndexPath::new(file_path))
            .and_then(|&index| self.files.get(index))
    }

    /// Get all files
    pub fn get_all_files(&self) -> &[TreeNode] {
        &self.files
    }

    /// Ensure the derived module graph is built (rebuild-all from the current
    /// files). Cheap no-op when already fresh; invalidated wholesale on any file
    /// change, so this is the single rebuild point — no per-file patching.
    pub fn build_module_graph_if_needed(&self) {
        if self.module_graph.read().unwrap().is_some() {
            return;
        }
        let graph = build_module_graph(&self.files);
        *self.module_graph.write().unwrap() = Some(graph);
    }

    /// A clone of the current module graph, building it first if stale. Cloned
    /// (not borrowed) because it lives behind interior-mutability; callers that
    /// need many queries should clone once and reuse.
    pub fn module_graph(&self) -> ModuleGraph {
        self.build_module_graph_if_needed();
        self.module_graph
            .read()
            .unwrap()
            .clone()
            .unwrap_or_default()
    }

    /// Map a file path to its index in the current file set (module-graph indices
    /// are positions in `get_all_files`).
    /// Record the directory this index was built from. Set by every entry point
    /// that scans (CLI, library, bindings) and after a cache load, since the
    /// cache does not carry it.
    /// The root is CANONICALIZED here (absolute, symlinks resolved), so however
    /// the caller spelled it — `.`, `../..`, a symlink — the index records one
    /// value. Callers comparing roots (the cache header, notably) compare this.
    pub fn set_scan_root(&mut self, root: impl Into<String>) {
        let root = root.into();
        let canonical = crate::scanner::discovery::canonical_root(&root);
        self.scan_root = Some(canonical.to_string_lossy().to_string());
    }

    /// Absolutize a stored (root-relative) path for filesystem access. `None`
    /// when no root is known — an unknown root refuses rather than falling back
    /// to the process cwd, which is precisely the K1 failure.
    pub fn absolute_path(&self, stored: &str) -> Option<std::path::PathBuf> {
        self.scan_root
            .as_ref()
            .map(|root| std::path::Path::new(root).join(stored))
    }

    /// The analysis root, if known. `None` means containment cannot be enforced,
    /// and callers must refuse rather than fall back to the process cwd.
    pub fn scan_root(&self) -> Option<&str> {
        self.scan_root.as_deref()
    }

    pub fn file_index_of(&self, file_path: &str) -> Option<usize> {
        self.file_index.get(&IndexPath::new(file_path)).copied()
    }

    /// Resolve a file argument to an index, tolerant of how an agent phrases the
    /// path: an exact match on the stored (absolute) path first, else a unique
    /// whole-segment suffix match (so a repo-relative `src/config.rs` finds
    /// `/abs/.../src/config.rs`). Ambiguous suffix → `None` (never guess).
    ///
    /// Callers that render an error should prefer [`RepoMap::lookup_file_index`]:
    /// this signature cannot distinguish "absent" from "matched several files",
    /// and reporting the second as the first teaches an agent that a file it can
    /// see in the index does not exist.
    pub fn resolve_file_index(&self, file_path: &str) -> Option<usize> {
        match self.lookup_file_index(file_path) {
            FileLookup::Found(idx) => Some(idx),
            _ => None,
        }
    }

    /// Resolve a file argument to an index, distinguishing the two ways it can
    /// fail. `mod.rs` in a repo with ten of them is not missing — it is
    /// ambiguous, and the caller can only say so if it is told so.
    /// Input tolerance is deliberate and one-directional: ANY reasonable spelling
    /// is accepted here (absolute, root-relative, `./`-prefixed, containing
    /// `..`), while what the index EMITS is always the single canonical
    /// root-relative form.
    pub fn lookup_file_index(&self, file_path: &str) -> FileLookup {
        if let Some(idx) = self.file_index_of(file_path) {
            return FileLookup::Found(idx);
        }
        // An absolute path (or one with `..`) that lands inside the root is the
        // same file under a different spelling — relativize it and try again.
        if let Some(rel) = self.relativize_to_root(file_path) {
            if let Some(idx) = self.file_index_of(&rel) {
                return FileLookup::Found(idx);
            }
        }
        let norm = normalize_path(file_path);
        let needle = format!("/{norm}");
        let mut hits: Vec<usize> = Vec::new();
        for (i, f) in self.files.iter().enumerate() {
            let np = normalize_path(&f.file_path);
            if np == norm || np.ends_with(&needle) {
                hits.push(i);
            }
        }
        match hits.len() {
            0 => FileLookup::NotFound,
            1 => FileLookup::Found(hits[0]),
            _ => FileLookup::Ambiguous(hits),
        }
    }

    /// Express `input` as a root-relative path, if it names something inside the
    /// recorded scan root. `None` when no root is known or the path is outside
    /// it — never a silent clamp.
    pub fn relativize_to_root(&self, input: &str) -> Option<String> {
        let root = self.scan_root.as_ref()?;
        let root_norm = normalize_path(root);
        if root_norm.is_empty() {
            return None;
        }
        // A relative input is resolved against the root, not the process cwd.
        let candidate = if std::path::Path::new(input).is_absolute() {
            normalize_path(input)
        } else {
            crate::storage::graph::join_normalized(&root_norm, input)
        };
        if candidate == root_norm {
            return Some(String::new());
        }
        candidate
            .strip_prefix(&format!("{root_norm}/"))
            .map(|s| s.to_string())
    }

    /// The longest path prefix common to every indexed file. Used only as a
    /// fallback anchor when no scan root was recorded (a cache loaded by an old
    /// writer, say); `scan_root()` is authoritative when present.
    pub fn common_root_path(&self) -> String {
        self.find_common_root_path()
    }

    /// Get files by language
    pub fn get_files_by_language(&self, language: &str) -> Vec<&TreeNode> {
        self.language_index
            .get(language)
            .map(|indices| indices.iter().filter_map(|&i| self.files.get(i)).collect())
            .unwrap_or_default()
    }

    /// Find functions by pattern (supports regex and fuzzy matching) - Original method
    pub fn find_functions(&self, pattern: &str) -> QueryResult<&FunctionSignature> {
        let start_time = std::time::Instant::now();

        // Check cache first
        let cache_key = format!("func:{}", pattern);
        if let Some((cached_indices, timestamp)) = self.query_cache.get(&cache_key) {
            if timestamp.elapsed().unwrap_or_default().as_secs() < self.cache_ttl_seconds {
                let functions: Vec<&FunctionSignature> = cached_indices
                    .iter()
                    .filter_map(|&file_idx| self.files.get(file_idx))
                    .flat_map(|file| &file.functions)
                    .filter(|func| self.matches_pattern(&func.name, pattern))
                    .collect();

                let len = functions.len();
                return QueryResult::new(functions, len, start_time.elapsed().as_millis() as u64);
            }
        }

        let mut results = Vec::new();

        // Try exact match first. function_index[pattern] lists a file index once
        // per definition of that name, so a file defining the name more than once
        // (e.g. a trait method signature plus its impl) appears multiple times.
        // Visit each file once — the inner loop already collects every matching
        // function in it — otherwise results are duplicated.
        if let Some(file_indices) = self.function_index.get(pattern) {
            let mut seen_files = HashSet::new();
            for &file_idx in file_indices {
                if !seen_files.insert(file_idx) {
                    continue;
                }
                if let Some(file) = self.files.get(file_idx) {
                    for func in &file.functions {
                        if func.name == pattern {
                            results.push(func);
                        }
                    }
                }
            }
        }

        // If no exact matches, try pattern matching
        if results.is_empty() {
            for file in &self.files {
                for func in &file.functions {
                    if self.matches_pattern(&func.name, pattern) {
                        results.push(func);
                    }
                }
            }
        }

        let duration = start_time.elapsed().as_millis() as u64;
        let len = results.len();
        QueryResult::new(results, len, duration)
    }

    /// Find functions with limit and fuzzy matching support - CLI-compatible method
    pub fn find_functions_with_options(
        &self,
        pattern: &str,
        limit: usize,
        fuzzy: bool,
    ) -> Vec<&FunctionSignature> {
        if fuzzy {
            let fuzzy_results = self.fuzzy_search(pattern, Some(limit));
            let mut function_results = Vec::new();

            for file in &self.files {
                for func in &file.functions {
                    for (fuzzy_match, _score) in &fuzzy_results {
                        if fuzzy_match.contains(&func.name) {
                            function_results.push(func);
                            if function_results.len() >= limit {
                                return function_results;
                            }
                        }
                    }
                }
            }

            function_results
        } else {
            let query_result = self.find_functions(pattern);
            query_result.items.into_iter().take(limit).collect()
        }
    }

    /// Find structs by pattern
    pub fn find_structs(&self, pattern: &str) -> QueryResult<&StructSignature> {
        let start_time = std::time::Instant::now();
        let mut results = Vec::new();

        // Try exact match first. Dedup file indices for the same reason as
        // find_functions: struct_index lists a file once per definition of the
        // name, so visiting each file once avoids duplicated results.
        if let Some(file_indices) = self.struct_index.get(pattern) {
            let mut seen_files = HashSet::new();
            for &file_idx in file_indices {
                if !seen_files.insert(file_idx) {
                    continue;
                }
                if let Some(file) = self.files.get(file_idx) {
                    for struct_def in &file.structs {
                        if struct_def.name == pattern {
                            results.push(struct_def);
                        }
                    }
                }
            }
        }

        // If no exact matches, try pattern matching
        if results.is_empty() {
            for file in &self.files {
                for struct_def in &file.structs {
                    if self.matches_pattern(&struct_def.name, pattern) {
                        results.push(struct_def);
                    }
                }
            }
        }

        let duration = start_time.elapsed().as_millis() as u64;
        let len = results.len();
        //println!("find_structs: {:?}", results);
        QueryResult::new(results, len, duration)
    }

    /// Find structs with limit and fuzzy matching support - CLI-compatible method
    pub fn find_structs_with_options(
        &self,
        pattern: &str,
        limit: usize,
        fuzzy: bool,
    ) -> Vec<&StructSignature> {
        if fuzzy {
            let fuzzy_results = self.fuzzy_search(pattern, Some(limit));
            let mut struct_results = Vec::new();

            for file in &self.files {
                for struct_def in &file.structs {
                    for (fuzzy_match, _score) in &fuzzy_results {
                        if fuzzy_match.contains(&struct_def.name) {
                            struct_results.push(struct_def);
                            if struct_results.len() >= limit {
                                return struct_results;
                            }
                        }
                    }
                }
            }

            struct_results
        } else {
            let query_result = self.find_structs(pattern);
            query_result.items.into_iter().take(limit).collect()
        }
    }

    /// Get file dependencies based on imports
    pub fn get_file_dependencies(&self, file_path: &str) -> Vec<String> {
        if let Some(file) = self.get_file(file_path) {
            file.imports
                .iter()
                .map(|import| import.module_path.clone())
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Find all callers of a specific function
    pub fn find_function_callers(&self, function_name: &str) -> Vec<CallSite> {
        self.call_graph
            .get(function_name)
            .cloned()
            .unwrap_or_default()
    }

    /// Return the distinct files that define `function_name`. More than one entry
    /// means the name is defined in more than one file — a cross-file collision:
    /// callers attributed to it through the name-keyed call graph are candidates,
    /// not a confirmed single target. Deduplicated by file, so a file that defines
    /// the name twice (e.g. a trait method signature plus its impl) counts once
    /// and is not mistaken for a collision. Used to explain ambiguity in output.
    pub fn function_definition_files(&self, function_name: &str) -> Vec<String> {
        let mut seen = HashSet::new();
        self.function_index
            .get(function_name)
            .into_iter()
            .flatten()
            .filter(|&&idx| seen.insert(idx))
            .filter_map(|&idx| self.files.get(idx).map(|f| f.file_path.clone()))
            .collect()
    }

    /// Number of distinct files defining `function_name`. `> 1` is the name-collision
    /// signal for ambiguity flagging: it counts each file once, so a trait signature
    /// plus its impl in the same file is not a false collision (the flaw the bare
    /// `function_index[name].len()` had).
    pub fn name_definition_file_count(&self, function_name: &str) -> usize {
        let mut seen = HashSet::new();
        self.function_index
            .get(function_name)
            .into_iter()
            .flatten()
            .filter(|&&idx| seen.insert(idx))
            .count()
    }

    /// The owning type of the function named `name` defined in `file_path`, if any
    /// (Rust `impl` type, Python/TS class). Used to render qualified caller names
    /// like `Loader::load`. If a file has more than one function of that name with
    /// *different* owners (e.g. `Foo::build` and `Bar::build`), the name is
    /// ambiguous within the file and we return `None` rather than guessing the
    /// wrong owner — an honest bare name beats a confidently wrong `Foo::build`.
    pub fn function_owner(&self, file_path: &str, name: &str) -> Option<String> {
        let file = self.get_file(file_path)?;
        let mut matches = file.functions.iter().filter(|f| f.name == name);
        let first = matches.next()?;
        if matches.any(|f| f.owner != first.owner) {
            return None;
        }
        first.owner.clone()
    }

    /// Render a function's display name as `Owner::name` when it has an owning
    /// type, else the bare name.
    pub fn qualified_function_name(&self, file_path: &str, name: &str) -> String {
        match self.function_owner(file_path, name) {
            Some(owner) => format!("{owner}::{name}"),
            None => name.to_string(),
        }
    }

    /// Walk UP the call graph to find every function that TRANSITIVELY calls
    /// `function_name`.
    ///
    /// BFS starting from the target: level-1 callers are the distinct enclosing
    /// functions (`caller_function`) taken from `find_function_callers`; for each
    /// of those we recurse to find ITS callers, and so on. `depth` records the
    /// level at which each caller was first reached (1 = direct caller). Visited
    /// functions are tracked so cycles terminate. `max_depth == 0` means
    /// unlimited depth.
    ///
    /// Caller identity is `(file_path, function_name)`: two functions that share a
    /// name in different files are distinct BFS nodes and never merge. The call
    /// graph itself is keyed by callee *name*, so when a callee name is defined in
    /// more than one file (`name_definition_file_count > 1`) the callers reached
    /// through it cannot be attributed to a single definition — they are flagged
    /// `ambiguous` (candidates), not dropped and not silently merged. Actually
    /// resolving which definition each call targets is deferred to the resolved
    /// call graph (Phase 3); this keeps the name-keyed view honest.
    ///
    /// KNOWN LIMITATION (name-keyed): every definition of the target name is seeded
    /// as visited so the target is not reported as its own caller (and cycles
    /// terminate). When the target name is itself multiply-defined, a *collision
    /// sibling* — a same-named function in another file that genuinely calls the
    /// target — is therefore not re-reported as a caller. Distinguishing that from
    /// self-recursion is impossible without resolved edges; Phase 3 fixes it. The
    /// effect is a rare under-report, never a wrong-direction edge.
    pub fn transitive_callers(
        &self,
        function_name: &str,
        max_depth: usize,
    ) -> Vec<TransitiveCaller> {
        let mut results: Vec<TransitiveCaller> = Vec::new();
        // Visited nodes keyed by (file_path, function_name).
        let mut visited: HashSet<(String, String)> = HashSet::new();
        // Every definition of the target is "visited" so a self-recursive call
        // does not re-enqueue the target as its own caller.
        if let Some(indices) = self.function_index.get(function_name) {
            for &idx in indices {
                visited.insert((self.files[idx].file_path.clone(), function_name.to_string()));
            }
        }

        // BFS frontier of caller names whose callers we still expand. Expansion is
        // name-keyed (the call graph only knows callee names); the file half of
        // each node exists for visited-dedup. The target is seeded by name with an
        // empty file placeholder, which never collides with a real caller node.
        let mut frontier: Vec<(String, String)> = vec![(String::new(), function_name.to_string())];
        let mut depth: usize = 1;

        while !frontier.is_empty() {
            if max_depth != 0 && depth > max_depth {
                break;
            }

            let mut next_frontier: Vec<(String, String)> = Vec::new();

            for (_from_file, callee) in &frontier {
                // A callee name defined in more than one file cannot be attributed
                // to one function; callers reached through it are candidates. Uses
                // distinct-file count so a trait signature + its impl in one file
                // is not a false collision.
                let ambiguous = self.name_definition_file_count(callee) > 1;

                for call_site in self.find_function_callers(callee) {
                    // Skip top-level/module-level calls with no enclosing function.
                    let caller = match &call_site.caller_function {
                        Some(name) => name.clone(),
                        None => continue,
                    };

                    let key = (call_site.file_path.clone(), caller.clone());
                    if visited.contains(&key) {
                        continue;
                    }
                    visited.insert(key);

                    results.push(TransitiveCaller {
                        function_name: caller.clone(),
                        file_path: call_site.file_path.clone(),
                        depth,
                        ambiguous,
                    });
                    next_frontier.push((call_site.file_path.clone(), caller));
                }
            }

            frontier = next_frontier;
            depth += 1;
        }

        results.sort_by(|a, b| {
            a.depth
                .cmp(&b.depth)
                .then_with(|| a.function_name.cmp(&b.function_name))
                .then_with(|| a.file_path.cmp(&b.file_path))
        });
        results
    }

    /// Get repository metadata
    pub fn get_metadata(&self) -> &RepoMapMetadata {
        &self.metadata
    }

    /// Get changed files since a specific time
    pub fn get_changed_files(&self, since: SystemTime) -> Vec<&TreeNode> {
        self.files
            .iter()
            .filter(|file| file.last_modified > since)
            .collect()
    }

    /// Search across all content using fuzzy matching
    pub fn fuzzy_search(&self, query: &str, limit: Option<usize>) -> Vec<(String, f64)> {
        let matcher = SkimMatcherV2::default();
        let mut results = Vec::new();

        // Search function names
        for file in &self.files {
            for func in &file.functions {
                if let Some(score) = matcher.fuzzy_match(&func.name, query) {
                    results.push((format!("fn {}", func.name), score as f64));
                }
            }

            // Search struct names
            for struct_def in &file.structs {
                if let Some(score) = matcher.fuzzy_match(&struct_def.name, query) {
                    results.push((format!("struct {}", struct_def.name), score as f64));
                }
            }
        }

        // Sort by score (higher is better)
        results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        if let Some(limit) = limit {
            results.truncate(limit);
        }

        results
    }

    /// Get memory usage statistics
    pub fn get_memory_usage(&self) -> usize {
        // Rough estimation of memory usage
        let base_size = std::mem::size_of::<Self>();
        let files_size = self.files.len() * std::mem::size_of::<TreeNode>();
        let indexes_size = self.file_index.len() * 64 // Rough estimate for HashMap entries
            + self.function_index.len() * 64
            + self.struct_index.len() * 64
            + self.import_index.len() * 64
            + self.export_index.len() * 64
            + self.language_index.len() * 64;

        base_size + files_size + indexes_size
    }

    /// Clear query cache
    pub fn clear_cache(&mut self) {
        self.query_cache.clear();
    }

    /// Find imports by pattern
    pub fn find_imports(&self, pattern: &str, limit: usize) -> Vec<&ImportStatement> {
        let mut results = Vec::new();

        for file in &self.files {
            for import in &file.imports {
                if self.matches_pattern(&import.module_path, pattern) {
                    results.push(import);
                    if results.len() >= limit {
                        return results;
                    }
                }
            }
        }

        results
    }

    /// Find exports by pattern
    pub fn find_exports(&self, pattern: &str, limit: usize) -> Vec<&ExportStatement> {
        let mut results = Vec::new();

        for file in &self.files {
            for export in &file.exports {
                if self.matches_pattern(&export.exported_item, pattern) {
                    results.push(export);
                    if results.len() >= limit {
                        return results;
                    }
                }
            }
        }

        results
    }

    /// Get the number of files in the repository map
    pub fn file_count(&self) -> usize {
        self.files.len()
    }

    /// Check if the repository map is empty
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }

    /// Get memory usage in bytes
    pub fn memory_usage(&self) -> usize {
        self.get_memory_usage()
    }

    /// Get the repository tree (building it if necessary)
    pub fn get_repository_tree(&self) -> Option<RepositoryTree> {
        // First try to read existing tree
        if let Ok(tree_guard) = self.repository_tree.read() {
            if tree_guard.is_some() {
                return tree_guard.clone();
            }
        }

        // If tree doesn't exist, we need to build it
        // Since we can't mutate self in this immutable method, return None
        // The caller should use build_repository_tree_if_needed instead
        None
    }

    /// Build repository tree if it doesn't exist (for mutable access)
    pub fn build_repository_tree_if_needed(&mut self) -> Result<()> {
        if self.repository_tree.read().unwrap().is_none() {
            self.build_repository_tree()?;
        }
        Ok(())
    }

    /// Build the complete repository tree structure from current files
    pub fn build_repository_tree(&mut self) -> Result<()> {
        let mut directory_map: HashMap<String, DirectoryNode> = HashMap::new();
        let mut file_nodes: Vec<FileNode> = Vec::new();

        // Generate file skeletons and organize by directory
        for tree_node in &self.files {
            let file_skeleton = self.generate_file_skeleton(tree_node)?;
            let file_node = FileNode {
                name: std::path::Path::new(&tree_node.file_path)
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string(),
                path: tree_node.file_path.clone(),
                skeleton: file_skeleton,
            };

            // Get directory path
            let dir_path = std::path::Path::new(&tree_node.file_path)
                .parent()
                .unwrap_or_else(|| std::path::Path::new("/"))
                .to_string_lossy()
                .to_string();

            // Create directory node if it doesn't exist
            let dir_name = std::path::Path::new(&dir_path)
                .file_name()
                .unwrap_or_else(|| std::path::Path::new(&dir_path).as_os_str())
                .to_string_lossy()
                .to_string();

            // Seed a directory node for this file's parent directory, but do NOT
            // accumulate file_count / total_lines here. The authoritative roll-up
            // (both files-in-directory and nested-directory totals) is computed
            // once in `build_directory_hierarchy`. Counting here as well would
            // double-count every file. Only the language set is pre-populated,
            // which is idempotent (a HashSet) and harmless to merge again later.
            if let Some(dir_node) = directory_map.get_mut(&dir_path) {
                dir_node.languages.insert(tree_node.language.clone());
            } else {
                let mut languages = HashSet::new();
                languages.insert(tree_node.language.clone());

                directory_map.insert(
                    dir_path.clone(),
                    DirectoryNode {
                        name: dir_name,
                        path: dir_path,
                        children: Vec::new(),
                        file_count: 0,
                        total_lines: 0,
                        languages,
                    },
                );
            }

            file_nodes.push(file_node);
        }

        // Build hierarchical directory structure
        let root = self.build_directory_hierarchy(directory_map, file_nodes)?;

        // Generate repository summary
        let summary = self.generate_repository_summary()?;

        // Create repository tree
        let repository_tree = RepositoryTree {
            root,
            summary,
            generated_at: SystemTime::now(),
        };

        *self.repository_tree.write().unwrap() = Some(repository_tree);

        Ok(())
    }

    /// Generate a file skeleton from a TreeNode
    fn generate_file_skeleton(&self, tree_node: &TreeNode) -> Result<FileSkeleton> {
        let function_summaries: Vec<FunctionSummary> = tree_node
            .functions
            .iter()
            .map(|func| FunctionSummary {
                name: func.name.clone(),
                is_public: func.is_public,
                is_async: func.is_async,
                parameter_count: func.parameters.len(),
                return_type: func.return_type.clone(),
                line_number: func.start_line,
            })
            .collect();

        let struct_summaries: Vec<StructSummary> = tree_node
            .structs
            .iter()
            .map(|struct_def| StructSummary {
                name: struct_def.name.clone(),
                is_public: struct_def.is_public,
                field_count: struct_def.fields.len(),
                is_enum: struct_def.kind == TypeKind::Enum,
                line_number: struct_def.start_line,
            })
            .collect();

        let imports: Vec<String> = tree_node
            .imports
            .iter()
            .map(|import| import.module_path.clone())
            .collect();

        let exports: Vec<String> = tree_node
            .exports
            .iter()
            .map(|export| export.exported_item.clone())
            .collect();

        // Determine if file is public or test based on path and content
        let is_test = tree_node.file_path.contains("test")
            || tree_node.file_path.contains("tests")
            || function_summaries
                .iter()
                .any(|f| f.name.starts_with("test_"));

        let is_public = tree_node.file_path.contains("lib.rs")
            || tree_node.file_path.contains("main.rs")
            || exports.len() > 0;

        // Estimate file size and line count based on content
        let estimated_size =
            (tree_node.functions.len() * 100 + tree_node.structs.len() * 50) as u64;
        let estimated_lines = (tree_node.functions.len() * 10 + tree_node.structs.len() * 5) as u32;

        Ok(FileSkeleton {
            path: tree_node.file_path.clone(),
            language: tree_node.language.clone(),
            size_bytes: estimated_size,
            line_count: estimated_lines,
            functions: function_summaries,
            structs: struct_summaries,
            imports,
            exports,
            is_public,
            is_test,
            last_modified: Some(tree_node.last_modified),
        })
    }

    /// Build hierarchical directory structure from flat directory map
    fn build_directory_hierarchy(
        &self,
        mut directory_map: HashMap<String, DirectoryNode>,
        file_nodes: Vec<FileNode>,
    ) -> Result<DirectoryNode> {
        // Find the common root path for all files
        let root_path = self.find_common_root_path();

        // Build a proper nested directory structure
        let mut path_to_node: HashMap<String, DirectoryNode> = HashMap::new();

        // First, ensure all directory paths exist
        let mut all_dir_paths: HashSet<String> = HashSet::new();

        // Collect all directory paths from files.
        //
        // The walk stops AT the root instead of merely skipping it. Walking past
        // it produced a directory node for every terminal ancestor — `""` for a
        // relative root, `"/"` for an absolute one — which surfaced as a phantom
        // child `{"name": "", "path": ""}` in every tree. Feeding that empty path
        // back to a tool that takes a path prefix then matched nothing and
        // reported success, so the tree taught agents a path that silently lies.
        for file_node in &file_nodes {
            let mut current_path = std::path::Path::new(&file_node.path);
            while let Some(parent) = current_path.parent() {
                let parent_str = parent.to_string_lossy().to_string();
                if parent_str == root_path || parent_str.is_empty() || parent_str == "/" {
                    break;
                }
                all_dir_paths.insert(parent_str);
                current_path = parent;
            }
        }

        // Create directory nodes for all paths
        for dir_path in &all_dir_paths {
            let dir_name = std::path::Path::new(dir_path)
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .to_string();

            // Check if we already have this directory from the directory_map
            let dir_node = directory_map
                .remove(dir_path)
                .unwrap_or_else(|| DirectoryNode {
                    name: dir_name,
                    path: dir_path.clone(),
                    children: Vec::new(),
                    file_count: 0,
                    total_lines: 0,
                    languages: HashSet::new(),
                });

            path_to_node.insert(dir_path.clone(), dir_node);
        }

        // Create root directory.
        //
        // Stored paths are root-relative, so the root's own path is `"."` — the
        // root-relative spelling of the root — and never the empty string, which
        // is what produced the phantom `{"name": "", "path": ""}` node that
        // `get_dependency_graph` then matched nothing against. Its NAME comes
        // from the recorded scan root, which is the only place the directory's
        // real name survives once paths are relative to it.
        let root_name = self
            .scan_root
            .as_deref()
            .and_then(|r| std::path::Path::new(r).file_name().map(|n| n.to_owned()))
            .map(|n| n.to_string_lossy().to_string())
            .filter(|n| !n.is_empty())
            .unwrap_or_else(|| "root".to_string());

        let mut root = directory_map
            .remove(&root_path)
            .unwrap_or_else(|| DirectoryNode {
                name: String::new(),
                path: root_path.clone(),
                children: Vec::new(),
                file_count: 0,
                total_lines: 0,
                languages: HashSet::new(),
            });
        if root.name.is_empty() {
            root.name = root_name;
        }
        if root.path.is_empty() {
            root.path = ".".to_string();
        }

        // Add files to their respective directories
        for file_node in file_nodes {
            let file_dir_path = std::path::Path::new(&file_node.path)
                .parent()
                .unwrap_or_else(|| std::path::Path::new("/"))
                .to_string_lossy()
                .to_string();

            if file_dir_path == root_path {
                // File belongs directly in root - update stats before moving
                root.file_count += 1;
                if let Some(lang) = self.get_file_language(&file_node.skeleton) {
                    root.languages.insert(lang);
                }
                root.total_lines += file_node.skeleton.line_count;
                root.children.push(RepositoryTreeNode::File(file_node));
            } else if let Some(dir_node) = path_to_node.get_mut(&file_dir_path) {
                // File belongs in a subdirectory - update stats before moving
                dir_node.file_count += 1;
                if let Some(lang) = self.get_file_language(&file_node.skeleton) {
                    dir_node.languages.insert(lang);
                }
                dir_node.total_lines += file_node.skeleton.line_count;
                dir_node.children.push(RepositoryTreeNode::File(file_node));
            }
        }

        // Now build the nested structure by organizing directories hierarchically
        // Sort paths by depth (shallowest first) to ensure proper nesting
        let mut sorted_paths: Vec<_> = all_dir_paths.into_iter().collect();
        sorted_paths.sort_by_key(|path| path.matches('/').count());

        // Process directories from deepest to shallowest to build bottom-up
        for dir_path in sorted_paths.iter().rev() {
            if let Some(dir_node) = path_to_node.remove(dir_path) {
                // Find this directory's parent
                let parent_path = std::path::Path::new(dir_path)
                    .parent()
                    .map(|p| p.to_string_lossy().to_string());

                match parent_path {
                    Some(parent_path) if parent_path == root_path => {
                        // This directory's parent is root - update stats before moving
                        root.file_count += dir_node.file_count;
                        root.total_lines += dir_node.total_lines;
                        for lang in &dir_node.languages {
                            root.languages.insert(lang.clone());
                        }
                        root.children.push(RepositoryTreeNode::Directory(dir_node));
                    }
                    Some(parent_path) => {
                        // This directory has another directory as parent
                        if let Some(parent_node) = path_to_node.get_mut(&parent_path) {
                            // Update parent stats before moving
                            parent_node.file_count += dir_node.file_count;
                            parent_node.total_lines += dir_node.total_lines;
                            for lang in &dir_node.languages {
                                parent_node.languages.insert(lang.clone());
                            }
                            parent_node
                                .children
                                .push(RepositoryTreeNode::Directory(dir_node));
                        }
                    }
                    None => {
                        // This shouldn't happen, but fallback to root
                        root.children.push(RepositoryTreeNode::Directory(dir_node));
                    }
                }
            }
        }

        Ok(root)
    }

    /// Helper to extract language from file skeleton
    fn get_file_language(&self, skeleton: &FileSkeleton) -> Option<String> {
        if skeleton.language.is_empty() {
            None
        } else {
            Some(skeleton.language.clone())
        }
    }

    /// The directory every indexed path hangs off.
    ///
    /// Stored paths are root-relative, so that directory is the root itself and
    /// the answer is the empty string — "" is "the root", not "unknown". The
    /// prefix computation below survives only for an index whose paths are not
    /// root-relative (a hand-built `RepoMap` in a test or an embedding host).
    fn find_common_root_path(&self) -> String {
        if self.files.is_empty() {
            return String::new();
        }

        // Root-relative storage: a single relative path means the root anchors
        // everything, so there is nothing to infer.
        if self.files.iter().any(|f| !f.file_path.starts_with('/')) {
            return String::new();
        }

        let mut common_prefix = normalize_path(&self.files[0].file_path);
        for file in &self.files[1..] {
            common_prefix =
                Self::find_common_prefix(&common_prefix, &normalize_path(&file.file_path));
        }

        // The prefix is already a whole-segment path; drop the trailing file
        // component when every file shares one (a single-file index).
        if self.files.len() == 1 {
            return crate::storage::graph::parent_dir(&common_prefix);
        }
        common_prefix
    }

    /// The longest **whole-segment** directory prefix shared by two normalized
    /// paths.
    ///
    /// This used to compare character-by-character, which made `src/foo` and
    /// `src/foobar` "share" the prefix `src/foo` — a directory that need not
    /// exist, handed onward as a path (F9). Comparison is per segment, so the
    /// answer is always a real ancestor directory of both inputs.
    fn find_common_prefix(path1: &str, path2: &str) -> String {
        let absolute = path1.starts_with('/') && path2.starts_with('/');
        let segs1: Vec<&str> = path1.trim_start_matches('/').split('/').collect();
        let segs2: Vec<&str> = path2.trim_start_matches('/').split('/').collect();

        // The LAST segment of each path is the file name, never a directory, so
        // it can never contribute to a shared directory prefix.
        let limit = segs1.len().saturating_sub(1).min(segs2.len() - 1);
        let mut shared: Vec<&str> = Vec::new();
        for i in 0..limit {
            if segs1[i] == segs2[i] {
                shared.push(segs1[i]);
            } else {
                break;
            }
        }

        let joined = shared.join("/");
        if absolute {
            format!("/{joined}")
        } else {
            joined
        }
    }

    /// Generate repository summary statistics
    fn generate_repository_summary(&self) -> Result<RepositorySummary> {
        let mut language_counts: HashMap<String, usize> = HashMap::new();
        let mut largest_files: Vec<(String, u64)> = Vec::new();
        let mut function_distribution: HashMap<String, usize> = HashMap::new();
        let mut dependency_graph: HashMap<String, Vec<String>> = HashMap::new();

        let mut total_lines = 0;
        let mut total_functions = 0;
        let mut total_structs = 0;
        let mut directory_set: HashSet<String> = HashSet::new();

        for file in &self.files {
            // Language distribution
            *language_counts.entry(file.language.clone()).or_insert(0) += 1;

            // File sizes (estimated based on content)
            let estimated_file_size = (file.functions.len() * 100 + file.structs.len() * 50) as u64;
            largest_files.push((file.file_path.clone(), estimated_file_size));

            // Function distribution
            function_distribution.insert(file.file_path.clone(), file.functions.len());

            // Dependencies (imports)
            let dependencies: Vec<String> = file
                .imports
                .iter()
                .map(|imp| imp.module_path.clone())
                .collect();
            dependency_graph.insert(file.file_path.clone(), dependencies);

            // Statistics (estimated lines based on content)
            let estimated_lines = (file.functions.len() * 10 + file.structs.len() * 5) as u32;
            total_lines += estimated_lines;
            total_functions += file.functions.len();
            total_structs += file.structs.len();

            // Directory count
            if let Some(parent) = std::path::Path::new(&file.file_path).parent() {
                directory_set.insert(parent.to_string_lossy().to_string());
            }
        }

        // Sort largest files by size
        largest_files.sort_by(|a, b| b.1.cmp(&a.1));
        largest_files.truncate(10); // Keep top 10

        Ok(RepositorySummary {
            total_files: self.files.len(),
            total_directories: directory_set.len(),
            total_lines,
            total_functions,
            total_structs,
            languages: language_counts,
            largest_files,
            function_distribution,
            dependency_graph,
        })
    }

    /// Force rebuild of repository tree (useful when files are added/removed)
    pub fn rebuild_repository_tree(&mut self) -> Result<()> {
        self.repository_tree.write().unwrap().take();
        // The module graph is derived from the files too; invalidate it in lockstep.
        self.module_graph.write().unwrap().take();
        self.build_repository_tree()
    }

    /// Get repository tree as JSON for AI tools
    pub fn get_repository_tree_json(&self) -> Result<serde_json::Value> {
        if let Some(tree) = self.get_repository_tree() {
            Ok(serde_json::to_value(tree)?)
        } else {
            Err(AnalysisError::Other(
                "Repository tree not available".to_string(),
            ))
        }
    }

    // Private helper methods

    fn remove_file_by_index(&mut self, index: usize) {
        if index >= self.files.len() {
            return;
        }

        let file = &self.files[index];
        let file_path = file.file_path.clone();

        // Remove from file index
        self.file_index.remove(&IndexPath::new(&file_path));

        // Remove from other indexes
        self.remove_from_function_index(index);
        self.remove_from_struct_index(index);
        self.remove_from_import_index(index);
        self.remove_from_export_index(index);
        self.remove_from_language_index(index);
        // call_graph is keyed by call-site file_path (not numeric file index), so it is
        // pruned by path here and needs no shift in reindex_after_removal.
        self.remove_from_call_graph(&file_path);

        // Remove from files vector and update remaining indexes
        self.files.remove(index);
        self.reindex_after_removal(index);
    }

    /// Drop every call site originating in `file_path` from the call graph, removing any
    /// key whose call-site vector becomes empty. Without this, `add_file` re-adding a path
    /// appends its call sites a second time (duplicates) and `remove_file` leaves stale ones
    /// — poisoning `find_function_callers`, `trace_callers`, and `analyze_impact`.
    fn remove_from_call_graph(&mut self, file_path: &str) {
        self.call_graph.retain(|_name, sites| {
            sites.retain(|site| site.file_path != file_path);
            !sites.is_empty()
        });
    }

    fn update_indexes_for_file(&mut self, index: usize, tree_node: &TreeNode) -> Result<()> {
        let file_path = tree_node.file_path.clone();

        // Update file index
        self.file_index.insert(IndexPath::new(&file_path), index);

        // Update function index
        for func in &tree_node.functions {
            self.function_index
                .entry(func.name.clone())
                .or_insert_with(Vec::new)
                .push(index);
        }

        // Update struct index
        for struct_def in &tree_node.structs {
            self.struct_index
                .entry(struct_def.name.clone())
                .or_insert_with(Vec::new)
                .push(index);
        }

        // Update import index
        for import in &tree_node.imports {
            self.import_index
                .entry(import.module_path.clone())
                .or_insert_with(Vec::new)
                .push(index);
        }

        // Update export index
        for export in &tree_node.exports {
            self.export_index
                .entry(export.exported_item.clone())
                .or_insert_with(Vec::new)
                .push(index);
        }

        // Update language index
        self.language_index
            .entry(tree_node.language.clone())
            .or_insert_with(Vec::new)
            .push(index);

        // Update call graph
        for call in &tree_node.function_calls {
            // Determine the enclosing function by line-range containment: the
            // function in this same file whose [start_line, end_line] contains the
            // call's line_number. If several functions contain it (nested/impl
            // blocks), pick the INNERMOST one (smallest containing range).
            let caller_function = tree_node
                .functions
                .iter()
                .filter(|f| f.start_line <= call.line_number && call.line_number <= f.end_line)
                .min_by_key(|f| f.end_line.saturating_sub(f.start_line))
                .map(|f| f.name.clone());

            let call_site = CallSite {
                file_path: tree_node.file_path.clone(),
                line_number: call.line_number,
                column: call.column,
                function_name: call.function_name.clone(),
                caller_function,
            };

            self.call_graph
                .entry(call.function_name.clone())
                .or_insert_with(Vec::new)
                .push(call_site);
        }

        Ok(())
    }

    fn remove_from_function_index(&mut self, file_index: usize) {
        let keys_to_update: Vec<String> = self.function_index.keys().cloned().collect();
        for key in keys_to_update {
            if let Some(indices) = self.function_index.get_mut(&key) {
                indices.retain(|&i| i != file_index);
                if indices.is_empty() {
                    self.function_index.remove(&key);
                }
            }
        }
    }

    fn remove_from_struct_index(&mut self, file_index: usize) {
        let keys_to_update: Vec<String> = self.struct_index.keys().cloned().collect();
        for key in keys_to_update {
            if let Some(indices) = self.struct_index.get_mut(&key) {
                indices.retain(|&i| i != file_index);
                if indices.is_empty() {
                    self.struct_index.remove(&key);
                }
            }
        }
    }

    fn remove_from_import_index(&mut self, file_index: usize) {
        let keys_to_update: Vec<String> = self.import_index.keys().cloned().collect();
        for key in keys_to_update {
            if let Some(indices) = self.import_index.get_mut(&key) {
                indices.retain(|&i| i != file_index);
                if indices.is_empty() {
                    self.import_index.remove(&key);
                }
            }
        }
    }

    fn remove_from_export_index(&mut self, file_index: usize) {
        let keys_to_update: Vec<String> = self.export_index.keys().cloned().collect();
        for key in keys_to_update {
            if let Some(indices) = self.export_index.get_mut(&key) {
                indices.retain(|&i| i != file_index);
                if indices.is_empty() {
                    self.export_index.remove(&key);
                }
            }
        }
    }

    fn remove_from_language_index(&mut self, file_index: usize) {
        let keys_to_update: Vec<String> = self.language_index.keys().cloned().collect();
        for key in keys_to_update {
            if let Some(indices) = self.language_index.get_mut(&key) {
                indices.retain(|&i| i != file_index);
                if indices.is_empty() {
                    self.language_index.remove(&key);
                }
            }
        }
    }

    fn reindex_after_removal(&mut self, removed_index: usize) {
        // Update all indexes to account for the removed file
        for indices in self.function_index.values_mut() {
            for index in indices.iter_mut() {
                if *index > removed_index {
                    *index -= 1;
                }
            }
        }

        for indices in self.struct_index.values_mut() {
            for index in indices.iter_mut() {
                if *index > removed_index {
                    *index -= 1;
                }
            }
        }

        for indices in self.import_index.values_mut() {
            for index in indices.iter_mut() {
                if *index > removed_index {
                    *index -= 1;
                }
            }
        }

        for indices in self.export_index.values_mut() {
            for index in indices.iter_mut() {
                if *index > removed_index {
                    *index -= 1;
                }
            }
        }

        for indices in self.language_index.values_mut() {
            for index in indices.iter_mut() {
                if *index > removed_index {
                    *index -= 1;
                }
            }
        }

        // Update file_index
        let files_to_update: Vec<(IndexPath, usize)> = self
            .file_index
            .iter()
            .filter_map(|(path, &index)| {
                if index > removed_index {
                    Some((path.clone(), index - 1))
                } else {
                    None
                }
            })
            .collect();

        for (path, new_index) in files_to_update {
            self.file_index.insert(path, new_index);
        }
    }

    fn update_metadata(&mut self) {
        self.metadata.total_files = self.files.len();
        self.metadata.total_functions = self.files.iter().map(|f| f.functions.len()).sum();
        self.metadata.total_structs = self.files.iter().map(|f| f.structs.len()).sum();
        self.metadata.total_imports = self.files.iter().map(|f| f.imports.len()).sum();
        self.metadata.total_exports = self.files.iter().map(|f| f.exports.len()).sum();
        self.metadata.languages = self.files.iter().map(|f| f.language.clone()).collect();
        self.metadata.last_updated = SystemTime::now();
        self.metadata.memory_usage_bytes = self.get_memory_usage();
    }

    fn matches_pattern(&self, text: &str, pattern: &str) -> bool {
        // Try exact match first
        if text == pattern {
            return true;
        }

        // Try case-insensitive match
        if text.to_lowercase() == pattern.to_lowercase() {
            return true;
        }

        // Try regex if pattern looks like regex (contains regex special chars)
        if pattern.contains([
            '*', '^', '$', '[', ']', '(', ')', '{', '}', '|', '+', '?', '\\',
        ]) {
            if let Ok(regex) = Regex::new(pattern) {
                return regex.is_match(text);
            }
        }

        // Try substring match
        text.to_lowercase().contains(&pattern.to_lowercase())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{
        ExportStatement, FunctionCall, FunctionSignature, ImportStatement, Parameter,
        StructSignature,
    };
    use std::time::SystemTime;

    fn create_test_tree_node(name: &str, language: &str) -> TreeNode {
        let mut node = TreeNode::new(format!("/test/{}.rs", name), language.to_string());

        // Add some test functions
        node.functions.push(
            FunctionSignature::new(format!("function_{}", name), node.file_path.clone())
                .with_parameters(vec![
                    Parameter::new("param1".to_string(), "i32".to_string()),
                    Parameter::new("param2".to_string(), "String".to_string()),
                ])
                .with_return_type("Result<(), Error>".to_string())
                .with_visibility(true)
                .with_async(true),
        );

        // Add some test structs
        node.structs.push(StructSignature::new(
            format!("Struct{}", name.to_uppercase()),
            node.file_path.clone(),
        ));

        // Add some test imports
        node.imports.push(
            ImportStatement::new(format!("crate::{}", name), node.file_path.clone())
                .with_external(false),
        );

        // Add some test exports
        node.exports.push(ExportStatement::new(
            format!("pub_{}", name),
            node.file_path.clone(),
        ));

        // Add some test function calls
        node.function_calls.push(FunctionCall::new(
            format!("call_{}", name),
            node.file_path.clone(),
            42,
        ));

        node.content_hash = format!("hash_{}", name);
        node
    }

    #[test]
    fn test_repo_map_creation() {
        let repo_map = RepoMap::new();
        assert_eq!(repo_map.get_all_files().len(), 0);
        assert_eq!(repo_map.get_metadata().total_files, 0);
        assert_eq!(repo_map.get_metadata().total_functions, 0);
    }

    #[test]
    fn test_repo_map_with_limits() {
        let repo_map = RepoMap::new().with_max_files(5).with_cache_ttl(60);

        assert_eq!(repo_map.max_files, Some(5));
        assert_eq!(repo_map.cache_ttl_seconds, 60);
    }

    #[test]
    fn test_add_file() {
        let mut repo_map = RepoMap::new();
        let node = create_test_tree_node("test1", "rust");

        let result = repo_map.add_file(node.clone());
        assert!(result.is_ok());

        assert_eq!(repo_map.get_all_files().len(), 1);
        assert_eq!(repo_map.get_metadata().total_files, 1);
        assert_eq!(repo_map.get_metadata().total_functions, 1);
        assert_eq!(repo_map.get_metadata().total_structs, 1);

        // Verify file can be retrieved
        let retrieved = repo_map.get_file(&node.file_path);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().file_path, node.file_path);
    }

    #[test]
    fn test_add_multiple_files() {
        let mut repo_map = RepoMap::new();

        for i in 0..5 {
            let node = create_test_tree_node(&format!("test{}", i), "rust");
            let result = repo_map.add_file(node);
            assert!(result.is_ok());
        }

        assert_eq!(repo_map.get_all_files().len(), 5);
        assert_eq!(repo_map.get_metadata().total_files, 5);
        assert_eq!(repo_map.get_metadata().total_functions, 5);
        assert_eq!(repo_map.get_metadata().total_structs, 5);
    }

    #[test]
    fn test_update_existing_file() {
        let mut repo_map = RepoMap::new();
        let mut node = create_test_tree_node("test", "rust");

        // Add initial file
        repo_map.add_file(node.clone()).unwrap();
        assert_eq!(repo_map.get_all_files().len(), 1);

        // Update the same file
        node.content_hash = "updated_hash".to_string();
        node.functions.push(FunctionSignature::new(
            "new_function".to_string(),
            node.file_path.clone(),
        ));

        repo_map.add_file(node.clone()).unwrap();

        // Should still have only one file but with updated content
        assert_eq!(repo_map.get_all_files().len(), 1);
        assert_eq!(repo_map.get_metadata().total_functions, 2); // Now has 2 functions

        let retrieved = repo_map.get_file(&node.file_path).unwrap();
        assert_eq!(retrieved.content_hash, "updated_hash");
        assert_eq!(retrieved.functions.len(), 2);
    }

    #[test]
    fn test_remove_file() {
        let mut repo_map = RepoMap::new();
        let node = create_test_tree_node("test", "rust");
        let file_path = node.file_path.clone();

        // Add file
        repo_map.add_file(node).unwrap();
        assert_eq!(repo_map.get_all_files().len(), 1);

        // Remove file
        let result = repo_map.remove_file(&file_path);
        assert!(result.is_ok());
        assert!(result.unwrap()); // Should return true indicating file was removed

        assert_eq!(repo_map.get_all_files().len(), 0);
        assert_eq!(repo_map.get_metadata().total_files, 0);
        assert!(repo_map.get_file(&file_path).is_none());

        // Try to remove non-existent file
        let result = repo_map.remove_file("non_existent.rs");
        assert!(result.is_ok());
        assert!(!result.unwrap()); // Should return false
    }

    #[test]
    fn test_max_files_limit() {
        let mut repo_map = RepoMap::new().with_max_files(2);

        // Add files up to limit
        for i in 0..2 {
            let node = create_test_tree_node(&format!("test{}", i), "rust");
            let result = repo_map.add_file(node);
            assert!(result.is_ok());
        }

        // Try to add one more file - should fail
        let node = create_test_tree_node("overflow", "rust");
        let result = repo_map.add_file(node);
        assert!(result.is_err());
        assert_eq!(repo_map.get_all_files().len(), 2);
    }

    #[test]
    fn test_find_functions_exact_match() {
        let mut repo_map = RepoMap::new();
        let node = create_test_tree_node("test", "rust");
        repo_map.add_file(node).unwrap();

        let result = repo_map.find_functions("function_test");
        assert_eq!(result.items.len(), 1);
        assert_eq!(result.items[0].name, "function_test");
        assert!(result.query_duration_ms < 100); // Should be fast
    }

    #[test]
    fn test_find_functions_pattern_match() {
        let mut repo_map = RepoMap::new();

        // Add multiple files with functions
        for i in 0..3 {
            let node = create_test_tree_node(&format!("test{}", i), "rust");
            repo_map.add_file(node).unwrap();
        }

        // Search for pattern that matches all functions
        let result = repo_map.find_functions("function_");
        assert_eq!(result.items.len(), 3);

        // Search for specific pattern
        let result = repo_map.find_functions("function_test1");
        assert_eq!(result.items.len(), 1);
        assert_eq!(result.items[0].name, "function_test1");
    }

    #[test]
    fn test_find_structs() {
        let mut repo_map = RepoMap::new();
        let node = create_test_tree_node("example", "rust");
        repo_map.add_file(node).unwrap();

        let result = repo_map.find_structs("StructEXAMPLE");
        assert_eq!(result.items.len(), 1);
        assert_eq!(result.items[0].name, "StructEXAMPLE");
    }

    #[test]
    fn test_get_files_by_language() {
        let mut repo_map = RepoMap::new();

        // Add Rust files
        for i in 0..2 {
            let node = create_test_tree_node(&format!("rust{}", i), "rust");
            repo_map.add_file(node).unwrap();
        }

        // Add Python files
        for i in 0..3 {
            let mut node = create_test_tree_node(&format!("python{}", i), "python");
            node.file_path = format!("/test/python{}.py", i);
            repo_map.add_file(node).unwrap();
        }

        let rust_files = repo_map.get_files_by_language("rust");
        assert_eq!(rust_files.len(), 2);

        let python_files = repo_map.get_files_by_language("python");
        assert_eq!(python_files.len(), 3);

        let js_files = repo_map.get_files_by_language("javascript");
        assert_eq!(js_files.len(), 0);
    }

    #[test]
    fn test_get_file_dependencies() {
        let mut repo_map = RepoMap::new();
        let node = create_test_tree_node("test", "rust");
        let file_path = node.file_path.clone();
        repo_map.add_file(node).unwrap();

        let dependencies = repo_map.get_file_dependencies(&file_path);
        assert_eq!(dependencies.len(), 1);
        assert_eq!(dependencies[0], "crate::test");
    }

    // P2-1: the derived module graph is wired into RepoMap — built lazily from the
    // files and rebuilt wholesale (not patched) when files change.
    #[test]
    fn test_module_graph_builds_and_rebuilds_on_change() {
        let mut repo_map = RepoMap::new();
        repo_map
            .add_file(create_test_tree_node("a", "rust"))
            .unwrap();
        repo_map
            .add_file(create_test_tree_node("b", "rust"))
            .unwrap();

        let g = repo_map.module_graph();
        assert_eq!(g.forward.len(), 2, "one forward-edge list per file");
        // Each test node carries one import; it is retained (resolved later by P2-4).
        assert_eq!(g.imports(0).len(), 1);

        // Adding a file invalidates and rebuilds the graph to the new file set.
        repo_map
            .add_file(create_test_tree_node("c", "rust"))
            .unwrap();
        assert_eq!(repo_map.module_graph().forward.len(), 3);

        // Removing a file rebuilds again — no stale entries for the gone file.
        repo_map.remove_file("/test/c.rs").unwrap();
        assert_eq!(repo_map.module_graph().forward.len(), 2);
    }

    #[test]
    fn test_find_function_callers() {
        let mut repo_map = RepoMap::new();
        let node = create_test_tree_node("test", "rust");
        repo_map.add_file(node).unwrap();

        let callers = repo_map.find_function_callers("call_test");
        assert_eq!(callers.len(), 1);
        assert_eq!(callers[0].function_name, "call_test");
        assert_eq!(callers[0].line_number, 42);
    }

    // A file defining the same name twice (e.g. a trait method signature + its
    // impl) lists that file twice in function_index; find_functions must not
    // return the matches multiple times.
    #[test]
    fn test_find_functions_no_duplicate_same_file_same_name() {
        let mut repo_map = RepoMap::new();
        let path = "/test/dup.rs".to_string();
        let mut node = TreeNode::new(path.clone(), "rust".to_string());
        node.functions
            .push(FunctionSignature::new("ingest".to_string(), path.clone()).with_location(1, 2));
        node.functions.push(
            FunctionSignature::new("ingest".to_string(), path.clone())
                .with_owner("Thing")
                .with_location(5, 7),
        );
        node.content_hash = "h_dup".to_string();
        repo_map.add_file(node).unwrap();

        let result = repo_map.find_functions("ingest");
        assert_eq!(
            result.items.len(),
            2,
            "each definition counted exactly once"
        );
        let owners: Vec<Option<&str>> = result.items.iter().map(|f| f.owner.as_deref()).collect();
        assert!(owners.contains(&None));
        assert!(owners.contains(&Some("Thing")));
    }

    // A file defining a name twice (trait signature + impl) is ONE definition
    // file, not a cross-file collision — so it must not be flagged ambiguous.
    #[test]
    fn test_name_defined_twice_in_one_file_is_not_a_collision() {
        let mut repo_map = RepoMap::new();
        let path = "/test/repo.rs".to_string();
        let mut node = TreeNode::new(path.clone(), "rust".to_string());
        node.functions
            .push(FunctionSignature::new("get".to_string(), path.clone()).with_location(1, 1));
        node.functions.push(
            FunctionSignature::new("get".to_string(), path.clone())
                .with_owner("S")
                .with_location(3, 5),
        );
        node.content_hash = "h".to_string();
        repo_map.add_file(node).unwrap();

        assert_eq!(repo_map.name_definition_file_count("get"), 1);
        assert_eq!(
            repo_map.function_definition_files("get"),
            vec!["/test/repo.rs"]
        );
    }

    // function_owner must not guess when a file has same-named methods with
    // different owners; it returns None rather than the first (possibly wrong) one.
    #[test]
    fn test_function_owner_ambiguous_within_file_returns_none() {
        let mut repo_map = RepoMap::new();
        let path = "/test/build.rs".to_string();
        let mut node = TreeNode::new(path.clone(), "rust".to_string());
        node.functions.push(
            FunctionSignature::new("build".to_string(), path.clone())
                .with_owner("Foo")
                .with_location(1, 3),
        );
        node.functions.push(
            FunctionSignature::new("build".to_string(), path.clone())
                .with_owner("Bar")
                .with_location(5, 7),
        );
        node.functions.push(
            FunctionSignature::new("only".to_string(), path.clone())
                .with_owner("Foo")
                .with_location(9, 10),
        );
        node.content_hash = "h".to_string();
        repo_map.add_file(node).unwrap();

        // Conflicting owners for `build` -> don't guess.
        assert_eq!(repo_map.function_owner(&path, "build"), None);
        assert_eq!(repo_map.qualified_function_name(&path, "build"), "build");
        // Unambiguous name still qualifies.
        assert_eq!(
            repo_map.function_owner(&path, "only"),
            Some("Foo".to_string())
        );
        assert_eq!(repo_map.qualified_function_name(&path, "only"), "Foo::only");
    }

    // P0-1 regression: call_graph must not accumulate stale/duplicate call sites across
    // file re-add and removal (previously remove_file_by_index skipped the call_graph).
    #[test]
    fn test_call_graph_no_duplicates_on_readd() {
        let mut repo_map = RepoMap::new();
        let node = create_test_tree_node("test", "rust");

        repo_map.add_file(node.clone()).unwrap();
        let before = repo_map.find_function_callers("call_test").len();
        assert_eq!(before, 1);

        // Re-adding the same file (watch mode / re-scan) must not duplicate call sites.
        repo_map.add_file(node.clone()).unwrap();
        let after = repo_map.find_function_callers("call_test").len();
        assert_eq!(after, before, "re-adding a file duplicated its call sites");
    }

    #[test]
    fn test_call_graph_cleared_on_remove() {
        let mut repo_map = RepoMap::new();
        let node = create_test_tree_node("test", "rust");
        let file_path = node.file_path.clone();

        repo_map.add_file(node).unwrap();
        assert_eq!(repo_map.find_function_callers("call_test").len(), 1);

        repo_map.remove_file(&file_path).unwrap();

        // No CallSite from the removed file may survive.
        let callers = repo_map.find_function_callers("call_test");
        assert!(
            callers.iter().all(|c| c.file_path != file_path),
            "removed file left stale call sites in the call graph"
        );
        assert_eq!(callers.len(), 0);
    }

    #[test]
    fn test_call_graph_drops_emptied_keys_on_remove() {
        let mut repo_map = RepoMap::new();
        let node = create_test_tree_node("test", "rust");
        let file_path = node.file_path.clone();

        repo_map.add_file(node).unwrap();
        repo_map.remove_file(&file_path).unwrap();

        // The only key ("call_test") had all its sites removed, so it must not linger as an
        // empty Vec keyed in the map.
        assert!(
            repo_map.call_graph.values().all(|sites| !sites.is_empty()),
            "call_graph retained an empty CallSite vector after removal"
        );
        assert!(!repo_map.call_graph.contains_key("call_test"));
    }

    /// Build a TreeNode with an explicitly positioned outer and (nested) inner
    /// function plus a call, so we can assert enclosing-function resolution.
    fn tree_node_with_nested_call() -> TreeNode {
        let mut node = TreeNode::new("/test/nested.rs".to_string(), "rust".to_string());

        // outer spans lines 1..=20, inner is nested inside it spanning 5..=15.
        node.functions.push(
            FunctionSignature::new("outer".to_string(), node.file_path.clone())
                .with_location(1, 20),
        );
        node.functions.push(
            FunctionSignature::new("inner".to_string(), node.file_path.clone())
                .with_location(5, 15),
        );

        // A call on line 10 sits inside BOTH outer and inner; innermost = inner.
        node.function_calls.push(FunctionCall::new(
            "target".to_string(),
            node.file_path.clone(),
            10,
        ));
        // A call on line 18 sits inside outer only.
        node.function_calls.push(FunctionCall::new(
            "outer_only".to_string(),
            node.file_path.clone(),
            18,
        ));
        // A call on line 25 is outside every function (module-level).
        node.function_calls.push(FunctionCall::new(
            "top_level".to_string(),
            node.file_path.clone(),
            25,
        ));

        node.content_hash = "hash_nested".to_string();
        node
    }

    #[test]
    fn test_caller_function_populated_for_nested_call() {
        let mut repo_map = RepoMap::new();
        repo_map.add_file(tree_node_with_nested_call()).unwrap();

        // Innermost enclosing function wins for the nested call.
        let target_callers = repo_map.find_function_callers("target");
        assert_eq!(target_callers.len(), 1);
        assert_eq!(
            target_callers[0].caller_function,
            Some("inner".to_string()),
            "nested call should resolve to the innermost enclosing function"
        );

        // A call inside only the outer function resolves to outer.
        let outer_callers = repo_map.find_function_callers("outer_only");
        assert_eq!(outer_callers[0].caller_function, Some("outer".to_string()));

        // A module-level call has no enclosing function.
        let top_callers = repo_map.find_function_callers("top_level");
        assert_eq!(top_callers[0].caller_function, None);
    }

    #[test]
    fn test_transitive_callers_multi_level() {
        // Build a chain across files: a -> b -> c -> parse_config
        // Each function calls the next; we assert BFS depth + cycle safety.
        let mut repo_map = RepoMap::new();

        let mut mk = |fname: &str, calls: &str, line: u32| {
            let path = format!("/test/{}.rs", fname);
            let mut node = TreeNode::new(path.clone(), "rust".to_string());
            node.functions
                .push(FunctionSignature::new(fname.to_string(), path.clone()).with_location(1, 10));
            node.function_calls
                .push(FunctionCall::new(calls.to_string(), path.clone(), line));
            node.content_hash = format!("hash_{}", fname);
            node
        };

        repo_map.add_file(mk("a", "b", 5)).unwrap();
        repo_map.add_file(mk("b", "c", 5)).unwrap();
        repo_map.add_file(mk("c", "parse_config", 5)).unwrap();

        let callers = repo_map.transitive_callers("parse_config", 0);
        let names: Vec<(&str, usize)> = callers
            .iter()
            .map(|c| (c.function_name.as_str(), c.depth))
            .collect();
        assert_eq!(names, vec![("c", 1), ("b", 2), ("a", 3)]);

        // max_depth limits the walk.
        let shallow = repo_map.transitive_callers("parse_config", 1);
        assert_eq!(shallow.len(), 1);
        assert_eq!(shallow[0].function_name, "c");
    }

    #[test]
    fn test_transitive_callers_cycle_safe() {
        // a -> b -> a (cycle). Traversal must terminate.
        let mut repo_map = RepoMap::new();
        let mut mk = |fname: &str, calls: &str| {
            let path = format!("/test/{}.rs", fname);
            let mut node = TreeNode::new(path.clone(), "rust".to_string());
            node.functions
                .push(FunctionSignature::new(fname.to_string(), path.clone()).with_location(1, 10));
            node.function_calls
                .push(FunctionCall::new(calls.to_string(), path.clone(), 5));
            node.content_hash = format!("hash_{}", fname);
            node
        };
        repo_map.add_file(mk("a", "b")).unwrap();
        repo_map.add_file(mk("b", "a")).unwrap();

        let callers = repo_map.transitive_callers("a", 0);
        // b calls a (depth 1); a calls b but a is the target (visited) -> stop.
        assert_eq!(callers.len(), 1);
        assert_eq!(callers[0].function_name, "b");
    }

    // P0-3: two functions named `load` in different files, each on its own caller
    // chain. Tracing `load` cannot attribute the direct callers to one definition
    // (name-keyed call graph), so both are flagged ambiguous — but the deeper,
    // uniquely-named callers on each chain resolve exactly and stay disjoint.
    #[test]
    fn test_transitive_callers_same_name_flagged_ambiguous() {
        let mut repo_map = RepoMap::new();

        // Build a file defining `load` plus a two-link caller chain into it.
        let mk_chain = |file: &str, caller: &str, top: &str| {
            let path = format!("/test/{}.rs", file);
            let mut node = TreeNode::new(path.clone(), "rust".to_string());
            node.functions
                .push(FunctionSignature::new("load".to_string(), path.clone()).with_location(1, 3));
            node.functions.push(
                FunctionSignature::new(caller.to_string(), path.clone()).with_location(5, 10),
            );
            node.functions
                .push(FunctionSignature::new(top.to_string(), path.clone()).with_location(12, 18));
            // caller() calls load(); top() calls caller().
            node.function_calls
                .push(FunctionCall::new("load".to_string(), path.clone(), 7));
            node.function_calls
                .push(FunctionCall::new(caller.to_string(), path.clone(), 14));
            node.content_hash = format!("hash_{}", file);
            node
        };

        repo_map
            .add_file(mk_chain("coll_a", "caller_a", "top_a"))
            .unwrap();
        repo_map
            .add_file(mk_chain("coll_b", "caller_b", "top_b"))
            .unwrap();

        let callers = repo_map.transitive_callers("load", 0);

        // Direct callers of `load` (depth 1): both chains cross here and both are
        // ambiguous, because `load` has two definitions.
        let direct: Vec<&TransitiveCaller> = callers.iter().filter(|c| c.depth == 1).collect();
        assert_eq!(direct.len(), 2, "both direct callers present");
        assert!(
            direct.iter().all(|c| c.ambiguous),
            "direct callers of an ambiguous name must be flagged, not exact"
        );
        let direct_names: HashSet<&str> = direct.iter().map(|c| c.function_name.as_str()).collect();
        assert_eq!(direct_names, HashSet::from(["caller_a", "caller_b"]));

        // Deeper callers (depth 2) have unique names, so they resolve exactly and
        // each stays attributed to its own file — the chains do not cross.
        let deep: Vec<&TransitiveCaller> = callers.iter().filter(|c| c.depth == 2).collect();
        assert_eq!(deep.len(), 2);
        assert!(
            deep.iter().all(|c| !c.ambiguous),
            "unique-named callers are exact"
        );
        let top_a = deep.iter().find(|c| c.function_name == "top_a").unwrap();
        assert_eq!(top_a.file_path, "/test/coll_a.rs");
        let top_b = deep.iter().find(|c| c.function_name == "top_b").unwrap();
        assert_eq!(top_b.file_path, "/test/coll_b.rs");
    }

    #[test]
    fn test_get_changed_files() {
        let mut repo_map = RepoMap::new();
        let timestamp = SystemTime::now();

        // Add a file before timestamp
        let mut old_node = create_test_tree_node("old", "rust");
        old_node.last_modified = timestamp - std::time::Duration::from_secs(60);
        repo_map.add_file(old_node).unwrap();

        // Add a file after timestamp
        let mut new_node = create_test_tree_node("new", "rust");
        new_node.last_modified = timestamp + std::time::Duration::from_secs(60);
        repo_map.add_file(new_node).unwrap();

        let changed_files = repo_map.get_changed_files(timestamp);
        assert_eq!(changed_files.len(), 1);
        assert!(changed_files[0].file_path.contains("new"));
    }

    #[test]
    fn test_fuzzy_search() {
        let mut repo_map = RepoMap::new();

        // Add files with various function and struct names
        let mut node = create_test_tree_node("example", "rust");
        node.functions.push(FunctionSignature::new(
            "calculate_hash".to_string(),
            node.file_path.clone(),
        ));
        node.functions.push(FunctionSignature::new(
            "parse_content".to_string(),
            node.file_path.clone(),
        ));
        node.structs.push(StructSignature::new(
            "Parser".to_string(),
            node.file_path.clone(),
        ));
        node.structs.push(StructSignature::new(
            "Calculator".to_string(),
            node.file_path.clone(),
        ));
        repo_map.add_file(node).unwrap();

        // Fuzzy search for "calc"
        let results = repo_map.fuzzy_search("calc", Some(10));
        assert!(!results.is_empty());

        // Should find both calculate_hash function and Calculator struct
        let calc_results: Vec<_> = results
            .iter()
            .filter(|(name, _)| name.to_lowercase().contains("calc"))
            .collect();
        assert!(!calc_results.is_empty());
    }

    #[test]
    fn test_memory_usage() {
        let mut repo_map = RepoMap::new();
        let initial_usage = repo_map.get_memory_usage();

        // Add some files
        for i in 0..10 {
            let node = create_test_tree_node(&format!("test{}", i), "rust");
            repo_map.add_file(node).unwrap();
        }

        let after_usage = repo_map.get_memory_usage();
        assert!(after_usage > initial_usage);
        assert_eq!(repo_map.get_metadata().memory_usage_bytes, after_usage);
    }

    #[test]
    fn test_query_cache() {
        let mut repo_map = RepoMap::new().with_cache_ttl(1); // 1 second TTL
        let node = create_test_tree_node("test", "rust");
        repo_map.add_file(node).unwrap();

        // First query - should be uncached
        let result1 = repo_map.find_functions("function_test");
        assert_eq!(result1.items.len(), 1);

        // Clear cache manually
        repo_map.clear_cache();

        // Query again - should work the same
        let result2 = repo_map.find_functions("function_test");
        assert_eq!(result2.items.len(), 1);
    }

    #[test]
    fn test_metadata_updates() {
        let mut repo_map = RepoMap::new();

        // Initial metadata
        let metadata = repo_map.get_metadata();
        assert_eq!(metadata.total_files, 0);
        assert_eq!(metadata.total_functions, 0);
        assert_eq!(metadata.total_structs, 0);
        assert!(metadata.languages.is_empty());

        // Add a file and check metadata updates
        let node = create_test_tree_node("test", "rust");
        repo_map.add_file(node).unwrap();

        let metadata = repo_map.get_metadata();
        assert_eq!(metadata.total_files, 1);
        assert_eq!(metadata.total_functions, 1);
        assert_eq!(metadata.total_structs, 1);
        assert_eq!(metadata.total_imports, 1);
        assert_eq!(metadata.total_exports, 1);
        assert!(metadata.languages.contains("rust"));
    }

    #[test]
    fn test_complex_indexing_scenario() {
        let mut repo_map = RepoMap::new();

        // Add multiple files with overlapping function names
        for i in 0..5 {
            let mut node = create_test_tree_node(&format!("file{}", i), "rust");

            // Add a common function name
            node.functions.push(FunctionSignature::new(
                "common_function".to_string(),
                node.file_path.clone(),
            ));

            // Add unique function
            node.functions.push(FunctionSignature::new(
                format!("unique_func_{}", i),
                node.file_path.clone(),
            ));

            repo_map.add_file(node).unwrap();
        }

        // Search for common function - should find 5 instances
        let results = repo_map.find_functions("common_function");
        assert_eq!(results.items.len(), 5);

        // Search for unique function - should find 1 instance
        let results = repo_map.find_functions("unique_func_2");
        assert_eq!(results.items.len(), 1);

        // Remove one file and verify indexes are updated correctly
        repo_map.remove_file("/test/file2.rs").unwrap();

        // Common function should now have 4 instances
        let results = repo_map.find_functions("common_function");
        assert_eq!(results.items.len(), 4);

        // unique_func_2 should no longer exist
        let results = repo_map.find_functions("unique_func_2");
        assert_eq!(results.items.len(), 0);

        // But unique_func_3 should still exist
        let results = repo_map.find_functions("unique_func_3");
        assert_eq!(results.items.len(), 1);
    }

    #[test]
    fn test_pattern_matching() {
        let repo_map = RepoMap::new();

        // Test exact match
        assert!(repo_map.matches_pattern("test_function", "test_function"));

        // Test case insensitive match
        assert!(repo_map.matches_pattern("TestFunction", "testfunction"));

        // Test substring match
        assert!(repo_map.matches_pattern("test_function_with_params", "function"));

        // Test regex pattern (if it looks like regex)
        assert!(repo_map.matches_pattern("test_function", "test_.*"));

        // Test non-matches
        assert!(!repo_map.matches_pattern("other_function", "test"));
    }

    fn repo_map_with_paths(paths: &[&str]) -> RepoMap {
        let mut map = RepoMap::new();
        for path in paths {
            let mut node = TreeNode::new(path.to_string(), "rust".to_string());
            node.content_hash = format!("h_{path}");
            map.add_file(node).unwrap();
        }
        map
    }

    // K8: a suffix that matches several files is AMBIGUOUS, not absent. The old
    // `Option` signature could not say so, and callers rendered both as
    // "file not found in the index: mod.rs" for a file the index holds twice.
    #[test]
    fn lookup_file_index_distinguishes_ambiguous_from_missing() {
        let map = repo_map_with_paths(&["/repo/a/mod.rs", "/repo/b/mod.rs", "/repo/only.rs"]);

        match map.lookup_file_index("mod.rs") {
            FileLookup::Ambiguous(indices) => assert_eq!(indices.len(), 2),
            other => panic!("expected Ambiguous, got {other:?}"),
        }
        assert_eq!(map.lookup_file_index("nope.rs"), FileLookup::NotFound);
        // A suffix unique enough to name one file still resolves.
        assert!(matches!(
            map.lookup_file_index("a/mod.rs"),
            FileLookup::Found(_)
        ));
        assert!(matches!(
            map.lookup_file_index("/repo/only.rs"),
            FileLookup::Found(_)
        ));
    }

    // The Option-returning wrapper keeps its old contract for callers that only
    // want "did it resolve": ambiguity is still None, never a guess.
    #[test]
    fn resolve_file_index_still_refuses_to_guess() {
        let map = repo_map_with_paths(&["/repo/a/mod.rs", "/repo/b/mod.rs"]);
        assert_eq!(map.resolve_file_index("mod.rs"), None);
        assert!(map.resolve_file_index("a/mod.rs").is_some());
    }

    fn collect_dir_paths(node: &RepositoryTreeNode, out: &mut Vec<(String, String)>) {
        if let RepositoryTreeNode::Directory(dir) = node {
            out.push((dir.name.clone(), dir.path.clone()));
            for child in &dir.children {
                collect_dir_paths(child, out);
            }
        }
    }

    // F8: the parent walk used to insert every ancestor of every file, including
    // the terminal `""` (relative roots) and `"/"` (absolute roots), producing a
    // phantom child `{"name": "", "path": ""}` in every tree. That empty path is
    // not a valid input to any sibling tool, so the tree emitted a path that
    // silently lies.
    #[test]
    fn repository_tree_has_no_phantom_empty_directory_node() {
        for paths in [
            // Relative roots yielded the `""` phantom...
            vec!["./src/a.rs", "./src/deep/b.rs", "./tests/c.rs"],
            // ...absolute ones the `"/"` phantom.
            vec!["/repo/src/a.rs", "/repo/src/deep/b.rs", "/repo/tests/c.rs"],
        ] {
            let mut map = repo_map_with_paths(&paths);
            map.build_repository_tree().unwrap();
            let tree = map.get_repository_tree().unwrap();

            let mut dirs = Vec::new();
            collect_dir_paths(&RepositoryTreeNode::Directory(tree.root.clone()), &mut dirs);
            assert!(
                !dirs.is_empty(),
                "expected directory nodes for {paths:?}, got none"
            );
            for (name, path) in &dirs {
                assert!(
                    !path.is_empty() && path != "/",
                    "phantom directory node {name:?} -> {path:?} in tree for {paths:?}: {dirs:?}"
                );
            }
            // The real directories are still there.
            assert!(
                dirs.iter().any(|(n, _)| n == "deep"),
                "lost a real directory: {dirs:?}"
            );
        }
    }

    // ----------------------------------------------------------------- //
    // Canonical-path refactor regressions
    // ----------------------------------------------------------------- //

    /// F9: `find_common_prefix` compared characters, so `src/foo` and
    /// `src/foobar` "shared" the prefix `src/foo` — a directory that need not
    /// exist, handed onward as a path. Prefixes are whole segments now.
    #[test]
    fn common_prefix_is_segment_aware_not_character_wise() {
        // The old character-wise implementation returned "src/foo" here.
        assert_eq!(
            RepoMap::find_common_prefix("src/foo/a.rs", "src/foobar/b.rs"),
            "src"
        );
        // A shared directory IS reported.
        assert_eq!(
            RepoMap::find_common_prefix("src/foo/a.rs", "src/foo/b.rs"),
            "src/foo"
        );
        // Nothing in common -> nothing claimed.
        assert_eq!(RepoMap::find_common_prefix("a/x.rs", "b/y.rs"), "");
        // Absolute paths keep their leading slash.
        assert_eq!(
            RepoMap::find_common_prefix("/r/src/foo/a.rs", "/r/src/foobar/b.rs"),
            "/r/src"
        );
        // And the file name itself is never a directory prefix.
        assert_eq!(RepoMap::find_common_prefix("src/a.rs", "src/a.rs"), "src");
    }

    /// K2: two spellings of one root used to produce TWO `file_index` entries
    /// (raw-string dedup) that collapsed into ONE `graph::FileSet` slot
    /// (normalized dedup). Both maps key on `IndexPath` now, so a second
    /// spelling REPLACES rather than duplicates.
    #[test]
    fn two_spellings_of_one_path_occupy_one_index_entry() {
        let mut map = RepoMap::new();
        for spelling in ["src/a.rs", "./src/a.rs", "src/./x/../a.rs"] {
            let mut node = TreeNode::new(spelling.to_string(), "rust".to_string());
            node.content_hash = "h".to_string();
            map.add_file(node).unwrap();
        }
        assert_eq!(map.get_all_files().len(), 1, "one file, one entry");
        // And it is stored under the canonical form, whatever was handed in.
        assert_eq!(map.get_all_files()[0].file_path, "src/a.rs");
        // Every spelling still RESOLVES: input tolerance is one-directional.
        for spelling in ["src/a.rs", "./src/a.rs", "src/x/../a.rs"] {
            assert!(
                matches!(map.lookup_file_index(spelling), FileLookup::Found(0)),
                "{spelling} must resolve"
            );
        }
    }

    /// Symbols carry the file's path too; if only `TreeNode::file_path` were
    /// normalized, `search_functions` and `find_importers` would speak two
    /// vocabularies for one file.
    #[test]
    fn symbol_paths_are_normalized_with_the_file() {
        let mut node = TreeNode::new("./src/a.rs".to_string(), "rust".to_string());
        node.functions.push(FunctionSignature::new(
            "f".to_string(),
            "./src/a.rs".to_string(),
        ));
        node.function_calls.push(FunctionCall::new(
            "g".to_string(),
            "./src/a.rs".to_string(),
            3,
        ));
        let mut map = RepoMap::new();
        map.add_file(node).unwrap();

        let stored = &map.get_all_files()[0];
        assert_eq!(stored.file_path, "src/a.rs");
        assert_eq!(stored.functions[0].file_path, "src/a.rs");
        assert_eq!(stored.function_calls[0].file_path, "src/a.rs");
    }

    /// Input tolerance survives the switch to root-relative keys: an ABSOLUTE
    /// path under the root names the same file as its relative spelling.
    #[test]
    fn absolute_input_resolves_against_the_recorded_root() {
        let dir = tempfile::TempDir::new().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        let mut map = RepoMap::new();
        map.set_scan_root(root.to_string_lossy().to_string());
        let mut node = TreeNode::new("src/a.rs".to_string(), "rust".to_string());
        node.content_hash = "h".to_string();
        map.add_file(node).unwrap();

        let abs = root.join("src/a.rs");
        assert!(matches!(
            map.lookup_file_index(&abs.to_string_lossy()),
            FileLookup::Found(0)
        ));
        // A path outside the root does not become root-relative by accident.
        assert_eq!(map.relativize_to_root("/somewhere/else/a.rs"), None);
    }

    /// K9: a symlinked root and the real root are one repository, so the index
    /// records one canonical root for both.
    #[test]
    #[cfg(unix)]
    fn scan_root_is_canonicalized_through_symlinks() {
        let dir = tempfile::TempDir::new().unwrap();
        let real = dir.path().join("real");
        std::fs::create_dir(&real).unwrap();
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        let mut via_real = RepoMap::new();
        via_real.set_scan_root(real.to_string_lossy().to_string());
        let mut via_link = RepoMap::new();
        via_link.set_scan_root(link.to_string_lossy().to_string());
        assert_eq!(via_real.scan_root(), via_link.scan_root());
    }
}