devscout-rs 0.5.0

Fast code index for C# and TypeScript codebases -- map, find, refs, impact from the CLI.
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
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
// Artifact build/load, fragments cache, incremental reuse.
// Writes are atomic (tmp+rename); fragments cache keying is load-bearing --
// a mismatch makes reuse break silently.
//
// This module owns every serde struct for graph.json + the fragments-cache
// pair (fragments-v18.json, fragments-index-v18.json), plus their path resolution,
// atomic I/O, and the cache-then-resolve-then-write orchestration
// (`rebuild_graph`). The pure resolution ladder that
// turns fragments into `defs`/`edges` lives in `resolve.rs` and returns the
// `Graph` value this module serializes -- see that module for the ladder
// itself.
//
// Schema notes (the on-disk format graph.json must keep):
//   - graph.json is compact JSON with NO indentation:
//     `{"key":value,...}`, no spaces. `serde_json::to_vec` (non-pretty)
//     matches this by default.
//   - Key order is insertion order, not sorted. Defs keep first-insertion
//     order (partial-class duplicates land in
//     `also_in`, not a second top-level entry) -- backed here by a
//     Vec<Def> + HashMap<id, index> pair (`build_def_index` in resolve.rs)
//     rather than a HashMap alone, which has no defined iteration order.
//   - `also_in` is omitted entirely (not `[]`) when a def has no additional
//     declaring sites -- `#[serde(skip_serializing_if = "Vec::is_empty")]`.
//   - `edges` are shape-heterogeneous by `kind`: inherits/uses-type/
//     uses-member share `{kind, from_file, from_line, to, to_file}`;
//     imports is `{kind, from_file, from_line, target}`; ambiguous is
//     `{kind, origin, from_file, from_line, raw, candidates,
//     candidate_count}`. Modeled as an internally-tagged enum
//     (`#[serde(tag = "kind")]`) -- serde always emits the tag field first,
//     matching every one of these shapes' field order.
//   - a `uses-member` edge appends three more keys AFTER that shared prefix,
//     in this exact order: `heuristic` (omitted when precise), `tier`, then
//     `member`. `tier` names WHICH guess tier emitted the row and is present
//     exactly when `heuristic` is; `member` names the member the reference
//     reads or calls and is written on EVERY uses-member edge, the precise
//     ones included -- it is the one fact the row never carried. Both are
//     omit-when-`None`, so the append-last rule every other added key follows
//     holds here too; the other two flagged kinds (inherits, uses-type) stay
//     exactly as they were.
//   - `schema_version` is `GRAPH_SCHEMA_VERSION`, which the `tier`/`member`
//     append above moved to 2. `rebuild_graph`'s unchanged fast path reads
//     the first bytes of an existing graph.json and refuses to reuse one
//     written at an older version, so a stale artifact is rebuilt on the next
//     `map` even when not one fragment moved.
//   - `units` is the LAST key of the whole object, appended after `names`
//     and omitted entirely (not `[]`) when the repo declares no `.csproj` --
//     so a tree without one serializes byte-for-byte as it did before the
//     project model existed. Each row's own key order is fixed too: `id`,
//     `name`, then `refs` (omitted when the project references nothing) and
//     `test` (omitted when false). A unit's DIRECTORY is not persisted: it
//     is `id`'s parent, recomputed on read (`project::units_from_graph`),
//     and neither is per-file/per-def membership -- that is derived from the
//     unit list by `ProjectModel` rather than stored.
//   - `stats.edges_by_kind` has a FIXED key order (inherits, uses-type,
//     imports, uses-member, ctor-di) -- not
//     alphabetical, not insertion order of first edge seen. A plain struct
//     with that declared field order reproduces it.
//   - `stats.ambiguous_pct` is `round(x*1000)/10`: a number that prints
//     WITHOUT a decimal point when whole (`20`, not `20.0`) and with
//     exactly one decimal digit otherwise (`33.3`). Rust's f64 Serialize
//     (ryu-backed) does not reproduce this -- see `Percent1` below, which
//     stores tenths as an integer and branches serialize_i64/serialize_f64
//     so whole values come out as bare integers, without needing serde_json's
//     `arbitrary_precision`/`raw_value` features (neither is enabled).
//   - fragments.json / fragments-index.json are objects keyed by
//     repo-relative path, in file-walk order (fragments-index.json is
//     rebuilt by iterating the same cache object fragments.json used).
//     A `HashMap` has no serialization order guarantee and `serde_json`'s
//     default `Map` (no `preserve_order` feature, which is off here) sorts
//     by key -- neither matches. `OrderedMap<V>` below hand-rolls
//     Serialize/Deserialize (using serde's own `SerializeMap` / `MapAccess`
//     traits, not a bespoke JSON writer) to preserve insertion order.
//   - `built_at_head` records `git -C <root> rev-parse HEAD` (`null` on any
//     failure incl. no commits yet). `manifest.rs` already owns that
//     (`manifest::git_head`) -- `resolve_graph` (resolve.rs) calls THAT, so
//     this module does not duplicate it.

use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::io;
use std::io::Read;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use serde::de::{MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::extract;
use crate::repo::{git_common_dir, scout_dir};

// ---------------------------------------------------------------------------
// Path resolution (private helpers for the graph directory and cache paths).
// ---------------------------------------------------------------------------

// The def/ref graph lives in the git COMMON dir (shared by every linked
// worktree, alongside the manifest), one level down; a non-git root falls
// back to `<root>/.scout/graph/`.
fn graph_dir(root: &Path) -> PathBuf {
    match git_common_dir(root) {
        Some(common) => common.join("scout").join("graph"),
        None => scout_dir(root).join("graph"),
    }
}

/// Path to the graph artifact (`graph.json`) for `root`.
pub fn graph_json_path(root: &Path) -> PathBuf {
    graph_dir(root).join("graph.json")
}

/// Path to the project-model staleness sidecar for `root`.
///
/// Holds exactly the bytes `graph.json`'s `units` array would carry -- the
/// serialized `Vec<GraphUnit>` and nothing else. `map` compares this file
/// against a freshly discovered model to notice a `.csproj` edit, which no
/// mtime in the fragments index can see: `.csproj` is not a `SOURCE_EXT`, so
/// editing one moves no graph file and `index_is_stale` stays false. Written
/// by `rebuild_graph` only when a model exists and DELETED when one does not,
/// so a repo that never had a `.csproj` never grows the file and one whose
/// last `.csproj` was removed still sees a difference on the next run.
pub fn project_units_path(root: &Path) -> PathBuf {
    graph_dir(root).join("project-units.json")
}

// The version in both cache filenames is the fragment SCHEMA version, bumped
// whenever the extractor starts recording something old cached fragments
// lack -- v10 added def `type_params`/`base_generic_args` and the new
// `ctor-param` ref kind (with its `args` field), v11 added markup graph
// facts (a `.xaml` file's fragment now carries the `x:Class` def and its
// element/`x:Bind` refs, where every cached markup fragment before it carried
// names only), v12 added the TS/JS reference fragment, v13 added def
// `propertyTypes` and ref `receiverPropertyOwner` plus the ref
// `receiverCallOwner`/`receiverCallMember` pair, plus the foreach
// element-type fact -- no new field (it settles into the existing
// `receiver_type`), but a cached fragment from before it can still disagree
// with a fresh one for the same unchanged file, so it rides the same bump
// rather than skipping it. v16 added the ref `receiverBase` flag, set only
// for a `base.` qualifier -- a cached v15 fragment carries none, so every
// `base.` receiver would silently resolve (or fail to resolve) as if it
// were a plain `this.` receiver. v17 added no field: the extractor now
// blanks the inactive arms of `#if`/`#else` groups before parsing, so a
// cached v16 fragment of an unchanged file can carry twin defs and refs
// from both arms that a fresh one no longer records -- the same
// "disagrees for an unchanged file" case that moved v13, so it rides a
// bump too. v18 added def `methodParams` and ref `receiverLambda`, the
// untyped-lambda-parameter callee slot -- a cached v17 fragment carries
// neither, so every per-overload parameter shape and every untyped-lambda
// callee-slot lookup they back would silently see no candidates. The
// rename IS the invalidation mechanism:
// pre-bump caches stop being found, every file reparses
// once, no reader carries version-compat logic. Writers delete every
// superseded generation (see `remove_superseded_caches`).
fn fragments_cache_path(root: &Path) -> PathBuf {
    graph_dir(root).join("fragments-v18.json")
}

fn fragments_index_path(root: &Path) -> PathBuf {
    graph_dir(root).join("fragments-index-v18.json")
}

// Every generation below the current one, not just the immediately previous:
// a repo mapped last under v1 and never since would otherwise keep its v1
// pair forever.
const SUPERSEDED_CACHE_FILES: &[&str] = &[
    "fragments.json",
    "fragments-index.json",
    "fragments-v2.json",
    "fragments-index-v2.json",
    "fragments-v3.json",
    "fragments-index-v3.json",
    "fragments-v4.json",
    "fragments-index-v4.json",
    "fragments-v5.json",
    "fragments-index-v5.json",
    "fragments-v6.json",
    "fragments-index-v6.json",
    "fragments-v7.json",
    "fragments-index-v7.json",
    "fragments-v8.json",
    "fragments-index-v8.json",
    "fragments-v9.json",
    "fragments-index-v9.json",
    "fragments-v10.json",
    "fragments-index-v10.json",
    "fragments-v11.json",
    "fragments-index-v11.json",
    "fragments-v12.json",
    "fragments-index-v12.json",
    "fragments-v13.json",
    "fragments-index-v13.json",
    "fragments-v14.json",
    "fragments-index-v14.json",
    "fragments-v15.json",
    "fragments-index-v15.json",
    "fragments-v16.json",
    "fragments-index-v16.json",
    "fragments-v17.json",
    "fragments-index-v17.json",
];

fn remove_superseded_caches(root: &Path) {
    for name in SUPERSEDED_CACHE_FILES {
        // Best-effort cleanup only -- a leftover superseded file is inert.
        let _ = fs::remove_file(graph_dir(root).join(name));
    }
}

// ---------------------------------------------------------------------------
// Atomic writes -- tmp file in the SAME directory as the target (so
// the final `rename` is same-filesystem and therefore atomic), unique name
// so concurrent writers (this process's own sequential graph/fragments/index
// writes, or a genuinely concurrent process) never collide. Writing to a
// tmp file and renaming is a deliberate upgrade over an in-place write --
// output BYTES are unaffected, only the write's crash-safety.
// ---------------------------------------------------------------------------

static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);

fn atomic_write_bytes(path: &Path, bytes: &[u8]) -> io::Result<()> {
    let dir = path.parent().unwrap_or_else(|| Path::new("."));
    fs::create_dir_all(dir)?;
    let file_name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("artifact");
    let counter = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    let tmp_path = dir.join(format!(".{file_name}.tmp.{}.{counter}", std::process::id()));
    let write_result = fs::write(&tmp_path, bytes);
    if write_result.is_err() {
        let _ = fs::remove_file(&tmp_path);
        write_result?;
    }
    fs::rename(&tmp_path, path)?;
    Ok(())
}

fn atomic_write_json<T: Serialize>(path: &Path, value: &T) -> io::Result<()> {
    let bytes = serde_json::to_vec(value).map_err(io::Error::other)?;
    atomic_write_bytes(path, &bytes)
}

// ---------------------------------------------------------------------------
// Insertion-ordered string-keyed map -- backs fragments.json's `{rel:
// {mtime, fragment}}` and fragments-index.json's `{rel: mtime}`. A HashMap
// has no defined iteration order and serde_json's default Map serializer
// (the `preserve_order` feature is not enabled) sorts by key; neither
// matches the required file-walk-order construction. Built on serde's own
// SerializeMap/MapAccess traits,
// not a hand-rolled JSON writer -- serde_json still owns the actual byte
// encoding.
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
/// Represents `OrderedMap`.
pub struct OrderedMap<V> {
    entries: Vec<(String, V)>,
    index: HashMap<String, usize>,
}

impl<V> OrderedMap<V> {
    /// Creates an empty insertion-ordered map.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            index: HashMap::new(),
        }
    }

    /// Insert, or overwrite in place when the key already exists --
    /// preserves that key's ORIGINAL position, like assigning to an existing
    /// key on a JSON object.
    pub fn insert(&mut self, key: String, value: V) {
        match self.index.get(&key) {
            Some(&i) => self.entries[i].1 = value,
            None => {
                self.index.insert(key.clone(), self.entries.len());
                self.entries.push((key, value));
            }
        }
    }

    /// Returns the value associated with `key`, if present.
    pub fn get(&self, key: &str) -> Option<&V> {
        self.index.get(key).map(|&i| &self.entries[i].1)
    }

    /// Returns the number of entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns whether the map contains no entries.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Iterates over entries in insertion order.
    pub fn iter(&self) -> impl Iterator<Item = (&String, &V)> {
        self.entries.iter().map(|(k, v)| (k, v))
    }
}

impl<V> Default for OrderedMap<V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<V: Serialize> Serialize for OrderedMap<V> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(self.entries.len()))?;
        for (k, v) in &self.entries {
            map.serialize_entry(k, v)?;
        }
        map.end()
    }
}

impl<'de, V: Deserialize<'de>> Deserialize<'de> for OrderedMap<V> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct OrderedMapVisitor<V>(PhantomData<V>);

        impl<'de, V: Deserialize<'de>> Visitor<'de> for OrderedMapVisitor<V> {
            type Value = OrderedMap<V>;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a JSON object")
            }

            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
                let mut out = OrderedMap::new();
                while let Some((k, v)) = map.next_entry::<String, V>()? {
                    out.insert(k, v);
                }
                Ok(out)
            }
        }

        deserializer.deserialize_map(OrderedMapVisitor(PhantomData))
    }
}

// ---------------------------------------------------------------------------
// `stats.ambiguous_pct` -- see module header. Stored as tenths (an i64) so
// the "is this whole?" branch is exact integer arithmetic, never a float
// epsilon comparison.
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Represents `Percent1`.
pub struct Percent1(pub i64);

impl Percent1 {
    /// Returns a zero percentage value.
    pub fn zero() -> Self {
        Percent1(0)
    }

    /// `ambiguous_pct` as `round((ambiguous / attempts) * 1000) / 10`, or 0
    /// when there are no attempts. Takes the pre-division inputs so the
    /// rounding happens exactly once.
    pub fn from_ratio(numerator: usize, denominator: usize) -> Self {
        if denominator == 0 {
            return Percent1::zero();
        }
        let raw = (numerator as f64 / denominator as f64) * 1000.0;
        Percent1(raw.round() as i64)
    }
}

impl Serialize for Percent1 {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if self.0 % 10 == 0 {
            serializer.serialize_i64(self.0 / 10)
        } else {
            serializer.serialize_f64(self.0 as f64 / 10.0)
        }
    }
}

impl<'de> Deserialize<'de> for Percent1 {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let v = f64::deserialize(deserializer)?;
        Ok(Percent1((v * 10.0).round() as i64))
    }
}

// ---------------------------------------------------------------------------
// graph.json schema.
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Represents `AlsoIn`.
pub struct AlsoIn {
    /// The file value.
    pub file: String,
    /// The line value.
    pub line: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Represents `Def`.
pub struct Def {
    /// The id value.
    pub id: String,
    /// The name value.
    pub name: String,
    /// The namespace value.
    pub namespace: String,
    /// The kind value.
    pub kind: String,
    /// The file value.
    pub file: String,
    /// The line value.
    pub line: usize,
    /// The methods value.
    pub methods: Vec<String>,
    /// Test-coverage stage -- the one member fact that SURVIVES onto disk
    /// (`properties`/`fields`/`extensionMethods`/`bases` are resolution inputs
    /// only, stripped before the row is written): `devscout tests` reads it back
    /// out of graph.json. Positioned after `methods` and before `also_in`, and
    /// omitted when empty, so a def declaring no tests keeps its exact
    /// pre-stage bytes.
    #[serde(default, rename = "testMethods", skip_serializing_if = "Vec::is_empty")]
    pub test_methods: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// The also in value.
    pub also_in: Vec<AlsoIn>,
    #[serde(default, rename = "endLine", skip_serializing_if = "is_zero")]
    /// The end line value.
    pub end_line: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Represents `Candidate`.
pub struct Candidate {
    /// The id value.
    pub id: String,
    /// The file value.
    pub file: String,
}

/// Which heuristic tier emitted a guess.
///
/// The two differ by an order of magnitude in precision and `heuristic: true`
/// alone cannot tell them apart: `Ext` is C#'s own extension-method lookup run over a recorded
/// `(member, this-type)` bucket -- a real rule, only unverifiable against an
/// out-of-graph receiver -- while `Guess` is the scored tier picking by NAME
/// among the defs that happen to declare a member so called.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HeuristicTier {
    /// Tier (f): extension-method lookup.
    Ext,
    /// The scored tier: a name guess.
    Guess,
}

/// The guess tag, appended LAST on every edge kind that can
/// carry it. `heuristic: true` is set only on an edge a heuristic tier
/// emitted and never writes `heuristic: false`, so this side pairs
/// `skip_serializing_if` with `default`: absent == precise, and a precise
/// edge's bytes are exactly what they were before the tag existed. Only
/// the resolver's heuristic tiers set it today (both
/// `uses-member`), but the flag lives on all three targeted kinds because
/// the query layer's heuristic adjacency is kind-keyed, so a future tier
/// tagging a `uses-type` edge needs no schema change.
///
/// `uses-member` carries two more appended keys, `tier` then `member`, in
/// that order and NOT mirrored onto the other two kinds: neither has a
/// member to name, and no tier tags one today. `tier` splits the umbrella
/// flag into the two tiers a reader can act on differently; `member` names
/// the member the reference reads or calls and is written on every
/// uses-member edge, precise ones included, because "which member" is a fact
/// about the reference rather than about the guess. Both are
/// omit-when-`None`, so a reader of the old shape sees only added keys.
///
/// The next slot on this variant is reserved for `source: Option<Provenance>`
/// (`"semantic"` for an edge a real compiler vouched for), appended after
/// `member` and omitted when empty, on the same rule.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum Edge {
    #[serde(rename = "inherits")]
    /// Represents `Inherits`.
    Inherits {
        /// The value value.
        from_file: String,
        /// The value value.
        from_line: usize,
        /// The value value.
        to: String,
        /// The value value.
        to_file: String,
        #[serde(default, skip_serializing_if = "is_false")]
        /// The value value.
        heuristic: bool,
    },
    #[serde(rename = "uses-type")]
    /// Represents `UsesType`.
    UsesType {
        /// The value value.
        from_file: String,
        /// The value value.
        from_line: usize,
        /// The value value.
        to: String,
        /// The value value.
        to_file: String,
        #[serde(default, skip_serializing_if = "is_false")]
        /// The value value.
        heuristic: bool,
    },
    #[serde(rename = "uses-member")]
    /// Represents `UsesMember`.
    UsesMember {
        /// The value value.
        from_file: String,
        /// The value value.
        from_line: usize,
        /// The value value.
        to: String,
        /// The value value.
        to_file: String,
        #[serde(default, skip_serializing_if = "is_false")]
        /// The value value.
        heuristic: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        /// Which guess tier emitted this edge -- `Some` exactly when
        /// `heuristic` is true. Build the variant through
        /// `Edge::uses_member`, which derives one from the other.
        tier: Option<HeuristicTier>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        /// The member this reference reads or calls, on precise and
        /// heuristic edges alike. `None` only for a reference the extractor
        /// recorded no member name for.
        member: Option<String>,
    },
    #[serde(rename = "imports")]
    /// The value value.
    Imports {
        /// The source file.
        from_file: String,
        /// The source line.
        from_line: usize,
        /// The imported target.
        target: String,
    },
    #[serde(rename = "ambiguous")]
    /// Represents `Ambiguous`.
    Ambiguous {
        /// The value value.
        origin: String,
        /// The value value.
        from_file: String,
        /// The value value.
        from_line: usize,
        /// The value value.
        raw: String,
        /// The value value.
        candidates: Vec<Candidate>,
        /// The value value.
        candidate_count: usize,
    },
    /// Constructor-parameter DI resolution (see resolve.rs's
    /// `resolve_ctor_param`). Field order (`kind`, `from_file`, `from_line`,
    /// `iface`, `resolution`, `args`, `to`, `candidates`) is significant --
    /// it fixes the serialized field order.
    /// `iface` is the injected type's bare identifier; `args` its closed
    /// generic arguments, present only when it has any; `to` the resolved
    /// implementation's def id, present only for 'plain'/'closed'/
    /// 'open-generic'; `candidates` the capped, sorted tie list, present only
    /// for 'ambiguous'.
    #[serde(rename = "ctor-di")]
    CtorDi {
        /// The value value.
        from_file: String,
        /// The value value.
        from_line: usize,
        /// The value value.
        iface: String,
        /// The value value.
        resolution: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        /// The value value.
        args: Option<Vec<String>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        /// The value value.
        to: Option<String>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        /// The value value.
        candidates: Vec<Candidate>,
    },
    /// A TS/TSX module import. Distinct from `imports` (C#'s
    /// `using` directive, which names a NAMESPACE and resolves to no file):
    /// `target` is the specifier as written and `to_file` the file it
    /// resolved to. `via` is appended LAST and present only on a
    /// barrel-followed edge, naming the module the source literally imported
    /// so a reader can tell the routing table apart from the dependency.
    #[serde(rename = "import")]
    Import {
        /// The value value.
        from_file: String,
        /// The value value.
        from_line: usize,
        /// The value value.
        target: String,
        /// The value value.
        to_file: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        /// The value value.
        via: Option<String>,
    },
    /// A call or `new` naming an imported or locally-exported
    /// declaration.
    #[serde(rename = "call")]
    /// The value value.
    Call {
        /// The source file.
        from_file: String,
        /// The source line.
        from_line: usize,
        /// The target definition identifier.
        to: String,
        /// The target file.
        to_file: String,
    },
    /// A JSX tag naming a component declaration.
    #[serde(rename = "jsx-use")]
    /// The value value.
    JsxUse {
        /// The source file.
        from_file: String,
        /// The source line.
        from_line: usize,
        /// The target definition identifier.
        to: String,
        /// The target file.
        to_file: String,
    },
    /// An action creator or thunk handed to a dispatching call
    /// (`dispatch(...)`, `ofType(...)`).
    #[serde(rename = "dispatch")]
    /// The value value.
    Dispatch {
        /// The source file.
        from_file: String,
        /// The source line.
        from_line: usize,
        /// The target definition identifier.
        to: String,
        /// The target file.
        to_file: String,
    },
}

impl Edge {
    /// The guess tier that emitted this edge, or `None` on a precise one --
    /// and on every kind that carries no tier at all, which is every kind but
    /// `uses-member`.
    pub fn tier(&self) -> Option<HeuristicTier> {
        match self {
            Edge::UsesMember { tier, .. } => *tier,
            _ => None,
        }
    }

    /// Whether the edge declares itself a guess, across the three kinds that
    /// can carry the flag.
    pub fn is_heuristic(&self) -> bool {
        match self {
            Edge::Inherits { heuristic, .. }
            | Edge::UsesType { heuristic, .. }
            | Edge::UsesMember { heuristic, .. } => *heuristic,
            _ => false,
        }
    }

    /// The one way to build a `uses-member` edge. `heuristic` is DERIVED from
    /// `tier` rather than passed alongside it, so the two cannot disagree: a
    /// tagged edge is always flagged, a flagged edge always names its tier,
    /// and no emit site can grow a third state by forgetting a field.
    pub fn uses_member(
        from_file: String,
        from_line: usize,
        to: String,
        to_file: String,
        member: Option<String>,
        tier: Option<HeuristicTier>,
    ) -> Edge {
        Edge::UsesMember {
            from_file,
            from_line,
            to,
            to_file,
            heuristic: tier.is_some(),
            tier,
            member,
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
/// Represents `EdgesByKind`.
pub struct EdgesByKind {
    /// The inherits value.
    pub inherits: usize,
    #[serde(rename = "uses-type")]
    /// The uses type value.
    pub uses_type: usize,
    /// The imports value.
    pub imports: usize,
    #[serde(rename = "uses-member")]
    /// The uses member value.
    pub uses_member: usize,
    /// Appended LAST, matching the `ctor-di` slot in the fixed key order.
    #[serde(rename = "ctor-di")]
    pub ctor_di: usize,
    /// The four TS edge counts, appended after `ctor-di` in this exact order
    /// and ONLY when the repo carries a TS fragment at all. A C#-only repo's
    /// stats block omits them entirely -- which is why these are `Option` and
    /// not a plain `0`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub import: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// The call value.
    pub call: Option<usize>,
    #[serde(rename = "jsx-use", default, skip_serializing_if = "Option::is_none")]
    /// The jsx use value.
    pub jsx_use: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// The dispatch value.
    pub dispatch: Option<usize>,
}

/// `heuristic_edge_count` split by the tier that emitted each edge, in the
/// fixed key order every tier-keyed output uses (ext, then guess).
///
/// Both keys are always written, and `ext + guess` equals `heuristic_edge_count` --
/// including after the heuristic-side dedup, which decrements the dropped
/// edge's own tier.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct HeuristicByTier {
    /// Edges tier (f) emitted.
    pub ext: usize,
    /// Edges the scored tier emitted.
    pub guess: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Represents `Stats`.
pub struct Stats {
    /// The def count value.
    pub def_count: usize,
    /// The file count value.
    pub file_count: usize,
    /// The edges by kind value.
    pub edges_by_kind: EdgesByKind,
    /// The ambiguous count value.
    pub ambiguous_count: usize,
    /// The ambiguous pct value.
    pub ambiguous_pct: Percent1,
    /// The unresolved external count value.
    pub unresolved_external_count: usize,
    /// Appended LAST, and always serialized (unlike the edge flag above): the
    /// key is written unconditionally, so a graph with no guesses still
    /// carries `"heuristic_edge_count":0`. `default` is for the READ side only
    /// -- a graph.json written before this counter existed has no such key,
    /// and it must read back as 0 rather than fail to parse.
    #[serde(default)]
    pub heuristic_edge_count: usize,
    /// Test-coverage stage -- appended LAST and always serialized, like the
    /// stage-4 counter above it. Counts merged DEF ROWS, not fragment entries,
    /// so a partial test class split across two files is one test def.
    #[serde(default)]
    pub test_def_count: usize,
    /// The TS resolver's own four counters, omitted entirely when the repo
    /// carries no TS fragment (the same omit-when-empty rule every other
    /// appended fact follows). Appended after `test_def_count`, and NOT last
    /// any more: `heuristic_by_tier` below is the newer fact and takes the
    /// tail, so a TS repo's stats block appends in the order the facts were
    /// added rather than interleaving the newest one before an older key.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ts: Option<crate::tsgraph::TsStats>,
    /// The tier split of `heuristic_edge_count`, appended LAST and always
    /// serialized, like the two counters above it. `default` is for the READ
    /// side only: a graph.json written before the tiers existed has no such
    /// key and must read back as two zeros rather than fail to parse.
    ///
    /// A C#-only repo writes no `ts` key at all, so for such a tree this key
    /// still follows `test_def_count` directly and the bytes are unchanged.
    #[serde(default)]
    pub heuristic_by_tier: HeuristicByTier,
}

/// One row of the full name index. Field order (`name`, `kind`,
/// `file`, `line`, `owner`) is significant; `owner` carries the
/// declaring type's def id for a member and is omitted for a type, an enum
/// member, and every markup or resource key.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GraphName {
    /// The name value.
    pub name: String,
    /// The kind value.
    pub kind: String,
    /// The file value.
    pub file: String,
    /// The line value.
    pub line: usize,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    /// The owner value.
    pub owner: String,
}

/// One `.csproj` project as graph.json persists it.
///
/// Field order (`id`, `name`, `refs`, `test`) is significant, and the last two are
/// omit-when-empty/omit-when-false: a leaf project that references nothing
/// and is not a test project serializes as just its `id` and `name`.
///
/// Deliberately NOT `project::Unit`: that type also carries `dir`, which is
/// always `id`'s parent directory and so is recomputed on read rather than
/// stored (`project::units_from_graph`). Nothing about which FILE belongs to
/// which unit is persisted either -- `ProjectModel` derives that from the
/// unit list.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GraphUnit {
    /// Repo-relative path to the `.csproj` file, which is also this unit's
    /// identity -- what `refs` entries name.
    pub id: String,
    /// The project name (the csproj file name without its extension).
    pub name: String,
    /// The `id`s of this project's DIRECT `ProjectReference` targets, not
    /// transitively closed. Omitted when empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub refs: Vec<String>,
    /// Whether this is a test project. Omitted when false.
    #[serde(default, skip_serializing_if = "is_not_test")]
    pub test: bool,
}

fn is_not_test(b: &bool) -> bool {
    !*b
}

/// The version stamped into every graph.json this build writes, and the one
/// `rebuild_graph` demands before it reuses an artifact it did not just
/// produce.
///
/// Bumped to 2 when `uses-member` edges gained `tier` and `member`:
/// a schema-1 graph is READABLE (both keys default) but it is missing facts
/// the query layer now reports, so it gets rebuilt rather than trusted.
pub const GRAPH_SCHEMA_VERSION: u32 = 2;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Represents `Graph`.
pub struct Graph {
    /// The schema version value.
    pub schema_version: u32,
    /// The built at head value.
    pub built_at_head: Option<String>,
    /// The defs value.
    pub defs: Vec<Def>,
    /// The edges value.
    pub edges: Vec<Edge>,
    /// The stats value.
    pub stats: Stats,
    /// Appended LAST, after `stats`, and omitted when empty: the
    /// house rule for every added field, and what keeps a graph built over a
    /// set that declares no name byte-identical to what it was.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub names: Vec<GraphName>,
    /// The repo's `.csproj` projects, sorted by `id` -- appended LAST, after
    /// `names`, and omitted entirely when the repo declares none. A tree with
    /// no `.csproj` therefore serializes exactly as it did before the project
    /// model existed.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub units: Vec<GraphUnit>,
}

/// Reads and deserializes the repository graph, returning `None` on failure.
pub fn read_graph(root: &Path) -> Option<Graph> {
    let text = fs::read_to_string(graph_json_path(root)).ok()?;
    serde_json::from_str(&text).ok()
}

fn write_graph(root: &Path, graph: &Graph) -> io::Result<()> {
    atomic_write_json(&graph_json_path(root), graph)
}

// ---------------------------------------------------------------------------
// Fragments cache schema -- the RAW (unresolved) per-file extraction output,
// keyed by repo-relative path. Mirrors extract.rs's DefRecord/UsingRecord/
// RefRecord field-for-field; the serde impls live here rather than on the
// extractor's own types.
// ---------------------------------------------------------------------------

/// Field order is significant: id, name, namespace, kind, line, methods, then
/// the member-fact additions in that exact order -- properties, fields,
/// methodReturns -- and after those extensionMethods, appended LAST. Each is
/// omitted entirely when empty, so a type declaring none of them serializes
/// exactly as it did before those additions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FragDef {
    /// The id value.
    pub id: String,
    /// The name value.
    pub name: String,
    /// The namespace value.
    pub namespace: String,
    /// The kind value.
    pub kind: String,
    /// The line value.
    pub line: usize,
    /// The methods value.
    pub methods: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// The properties value.
    pub properties: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// The fields value.
    pub fields: Vec<String>,
    /// Member name -> declared return type NAME, in FIRST-DECLARATION SOURCE
    /// ORDER -- deliberately `OrderedMap`, never a `BTreeMap`: this is an
    /// ordered pair list, and sorting the keys here would break the
    /// serialized bytes.
    #[serde(
        default,
        rename = "methodReturns",
        skip_serializing_if = "OrderedMap::is_empty"
    )]
    pub method_returns: OrderedMap<String>,
    /// The extension methods this type declares, in source
    /// order, deduped by (name, thisType, arityMin, arityMax). Appended after
    /// `method_returns`, and omitted entirely when empty, so a type declaring
    /// none keeps its exact prior bytes.
    #[serde(
        default,
        rename = "extensionMethods",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub extension_methods: Vec<FragExtensionMethod>,
    /// DIRECT base-type identifiers, source
    /// order, deduped. Appended LAST, after `extension_methods`, omitted when
    /// empty. A resolution input only: `resolve_graph` strips it (along with
    /// properties/fields/extensionMethods) before graph.json's def rows, so
    /// the on-disk def bytes are unchanged.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bases: Vec<String>,
    /// The declaring type's own type-parameter names, empty for
    /// every non-generic declaration. Appended after `bases`, omitted when
    /// empty. A resolution input, like `bases`: the ctor-DI resolver's
    /// "is this def itself an open-generic implementation" signal.
    #[serde(default, rename = "typeParams", skip_serializing_if = "Vec::is_empty")]
    pub type_params: Vec<String>,
    /// Per base name that carried a type-argument list, that
    /// list's generic-arg descriptors relative to `type_params` (`OrderedMap`
    /// for the same reason `method_returns` is one: the serialized key order
    /// is significant). Appended after `type_params`, omitted when
    /// empty.
    #[serde(
        default,
        rename = "baseGenericArgs",
        skip_serializing_if = "OrderedMap::is_empty"
    )]
    pub base_generic_args: OrderedMap<Vec<String>>,
    /// The methods a test framework would DISCOVER as
    /// tests, source order, deduped. Appended LAST, after `baseGenericArgs`,
    /// omitted when empty. Unlike its neighbours this one is NOT stripped by
    /// `resolve_graph`: it is what `devscout tests` answers from.
    #[serde(default, rename = "testMethods", skip_serializing_if = "Vec::is_empty")]
    pub test_methods: Vec<String>,
    /// Property name -> declared type fact, in source order and
    /// under the same dedup as `properties`. An `OrderedMap` for the same
    /// reason `method_returns` is one: the serialized key order is significant.
    /// Appended LAST, after `test_methods`, omitted when empty. A
    /// resolution input only, like `properties`/`fields`.
    #[serde(
        default,
        rename = "propertyTypes",
        skip_serializing_if = "OrderedMap::is_empty"
    )]
    pub property_types: OrderedMap<FragFact>,
    /// Field name -> declared type fact, in source order and
    /// under the same dedup as `fields`. Mirrors `propertyTypes` field for
    /// field: an `OrderedMap` for the same reason (the serialized key order
    /// is significant), a resolution input only, like `properties`/`fields`,
    /// and this is a purely additive field -- an absent key reads back as
    /// "no fields typed", the safe default for every fragment cached before
    /// this field existed, so it joins the schema with no cache-version
    /// bump. Appended right after `propertyTypes`, omitted when empty.
    #[serde(
        default,
        rename = "fieldTypes",
        skip_serializing_if = "OrderedMap::is_empty"
    )]
    pub field_types: OrderedMap<FragFact>,
    /// Per method name `methodReturns` also carries an entry for,
    /// that return type's top-level generic-arg descriptors -- the same
    /// capture `baseGenericArgs` keeps beside `bases` (see extract.rs's
    /// `DefRecord`). `methodReturns` itself is left exactly as it always
    /// was (the bare return-type identifier, "Task" for
    /// `Task<Order> GetAsync()`) so an UNAWAITED use of the same callee
    /// keeps reading "Task" unchanged; this is a purely additive sibling
    /// field, not a reshaping of `methodReturns`, which is what lets it
    /// join the schema with no cache-version bump -- an absent key reads
    /// back as "no generic args", the safe default for every fragment
    /// cached before this field existed. Appended LAST of all, after
    /// `fieldTypes`, omitted when empty.
    #[serde(
        default,
        rename = "methodReturnArgs",
        skip_serializing_if = "OrderedMap::is_empty"
    )]
    pub method_return_args: OrderedMap<Vec<String>>,
    /// Declared method names `methods` does not carry because
    /// `is_recorded_method` gates that list on a literal `public` modifier
    /// (or `kind == "interface"`, where this list is always empty). Source
    /// order, no dedup, same as `methods`. A resolution input only, like
    /// `properties`/`fields`/`bases`: `resolve_graph` strips it before
    /// graph.json's def rows. Consulted only for hierarchy-internal
    /// receivers (`base.` and the `this.` shape's own base walk); the
    /// scored tier keeps reading `methods` alone. Appended LAST of all,
    /// after `methodReturnArgs`, omitted when empty -- purely additive, so
    /// an absent key reads back as "no non-public methods", the safe
    /// default for every fragment cached before this field existed, which
    /// is what lets it join the schema with no cache-version bump.
    #[serde(
        default,
        rename = "nonPublicMethods",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub non_public_methods: Vec<String>,
    /// Method name -> the (min, max) argument-count range every overload
    /// sharing that name accepts, one tuple per overload, in declaration
    /// order -- covers every method, public and non-public alike (see
    /// `extract::DefRecord::method_arities`). `max` is -1 for an unbounded
    /// `params` overload, the same sentinel `FragExtensionMethod::arity_max`
    /// already uses. An `OrderedMap` for the same reason `methodReturns` is
    /// one: the serialized key order is significant. Appended LAST of all,
    /// after `nonPublicMethods`, omitted when empty -- purely additive, so
    /// an absent key reads back as "no arity facts", the safe default for
    /// every fragment cached before this field existed, which is what lets
    /// it join the schema with no cache-version bump.
    #[serde(
        default,
        rename = "methodArities",
        skip_serializing_if = "OrderedMap::is_empty"
    )]
    pub method_arities: OrderedMap<Vec<(usize, i64)>>,
    /// Method name -> per-overload parameter type descriptors, one
    /// `Vec<String>` per overload in declaration order -- covers every
    /// method, public and non-public alike, same method set as
    /// `methodArities` (see `extract::DefRecord::method_params`). A
    /// position naming a type parameter of the enclosing method or class is
    /// recorded as `"*"`; a parameter carrying the `this` modifier is
    /// written `"this <descriptor>"`. A `delegate` def carries exactly one
    /// entry here, keyed `"Invoke"`. An `OrderedMap` for the same reason
    /// `methodArities` is one: the serialized key order is significant.
    /// Appended LAST of all, after `methodArities`, omitted when empty.
    /// Joined the schema with the v18 cache bump: a v17 fragment read back
    /// carries none, and every overload-shape/`this`-marker/callee-slot
    /// lookup this field backs would silently see no candidates.
    #[serde(
        default,
        rename = "methodParams",
        skip_serializing_if = "OrderedMap::is_empty"
    )]
    pub method_params: OrderedMap<Vec<Vec<String>>>,
    #[serde(default, rename = "endLine", skip_serializing_if = "is_zero")]
    /// The end line value.
    pub end_line: usize,
}

/// One declared type fact: the type NAME, plus its top-level
/// type-argument descriptors when the declaration carried any. Field order
/// (`type`, `args`) is significant, and `args` is omitted when absent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FragFact {
    #[serde(rename = "type")]
    /// The type name value.
    pub type_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// The args value.
    pub args: Option<Vec<String>>,
}

/// One `extensionMethods` entry. Serialized field order (`name`, `thisType`,
/// `arityMin`, `arityMax`, `thisArgs`) is significant, and serde emits struct
/// fields in declaration order. The two arity halves are NOT optional: they joined the
/// schema with the v6 cache rename, so no fragment this reader can meet is
/// missing them. `arity_max` is signed because -1 is the unbounded-`params`
/// sentinel.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FragExtensionMethod {
    /// The name value.
    pub name: String,
    #[serde(rename = "thisType")]
    /// The this type value.
    pub this_type: String,
    #[serde(rename = "arityMin")]
    /// The arity min value.
    pub arity_min: usize,
    #[serde(rename = "arityMax")]
    /// The arity max value.
    pub arity_max: i64,
    /// Present only when the this-parameter type is generic (the key is omitted
    /// key otherwise), so a non-generic entry keeps four fields exactly.
    #[serde(default, rename = "thisArgs", skip_serializing_if = "Option::is_none")]
    pub this_args: Option<Vec<String>>,
}

/// One untyped lambda parameter's callee slot (see extract.rs's `LambdaSlot`).
///
/// Field order (`owner`, `member`, `argCount`, `argIndex`,
/// `arity`, `index`) is significant: serde emits struct fields in
/// declaration order under `#[serde(rename_all = "camelCase")]`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FragLambdaSlot {
    /// The callee's type-name text.
    pub owner: String,
    /// The callee method name.
    pub member: String,
    /// The argument count of the callee invocation.
    pub arg_count: usize,
    /// The position of the lambda among the callee invocation's arguments.
    pub arg_index: usize,
    /// The lambda's own parameter count.
    pub arity: usize,
    /// This parameter's position inside the lambda's parameter list.
    pub index: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
/// Represents `FragUsing`.
pub enum FragUsing {
    /// The value value.
    Alias {
        /// The alias name.
        alias: String,
        /// The aliased target.
        target: String,
        /// Whether the directive is global.
        global: bool,
    },
    /// The value value.
    Plain {
        /// The imported namespace text.
        text: String,
        /// Whether the directive is global.
        global: bool,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Represents `FragRef`.
pub struct FragRef {
    /// The kind value.
    pub kind: String,
    /// The name value.
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// The qualified value.
    pub qualified: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// The member value.
    pub member: Option<String>,
    /// The line value.
    pub line: usize,
    /// Always serialized, including when `null` (imports refs) -- NOT
    /// `skip_serializing_if`, unlike `qualified`/`member` which are omitted
    /// entirely when absent. See extract.rs's RefRecord doc comment.
    pub namespace: Option<String>,
    #[serde(
        default,
        rename = "typeArgCount",
        skip_serializing_if = "Option::is_none"
    )]
    /// The type arg count value.
    pub type_arg_count: Option<usize>,
    /// Type-certainty flag (see extract.rs's RefRecord). Serialized last and
    /// only when `true`; an absent key reads back as false, which also makes
    /// an older fragment JSON parse safely.
    #[serde(default, skip_serializing_if = "is_false")]
    pub generic: bool,
    /// Receiver fact (see extract.rs's RefRecord). Appended AFTER `generic`,
    /// and set only when a fact actually fired -- so it serializes last and
    /// only when present, and an absent key reads back as "no fact", the safe
    /// default.
    #[serde(
        default,
        rename = "receiverType",
        skip_serializing_if = "Option::is_none"
    )]
    pub receiver_type: Option<String>,
    /// The callee arg count (see extract.rs's RefRecord). Appended AFTER
    /// `receiverType`, set only when the member access was the callee of an
    /// invocation -- so it serializes last and only when present, and an
    /// absent key reads back as "not a call", which is what keeps a property
    /// read out of the extension tier.
    #[serde(default, rename = "argCount", skip_serializing_if = "Option::is_none")]
    pub arg_count: Option<usize>,
    /// Receiver generic-arg descriptors (see extract.rs's RefRecord). Appended
    /// LAST, after `argCount`, set only when the receiver's DECLARED type was
    /// generic -- an absent key reads back as "not generic", which is what
    /// makes a generic-vs-non-generic pairing fail to unify.
    #[serde(
        default,
        rename = "receiverArgs",
        skip_serializing_if = "Option::is_none"
    )]
    pub receiver_args: Option<Vec<String>>,
    /// Enclosing-type stack (see extract.rs's RefRecord). Appended LAST, after
    /// `receiverArgs`, and set only when non-empty. A Vec rather than an Option
    /// because empty and absent mean the same thing here -- a ref at namespace
    /// level and an older cached fragment both read back as "no enclosing
    /// type", which is what keeps them off the step.
    #[serde(default, rename = "outerTypes", skip_serializing_if = "Vec::is_empty")]
    pub outer_types: Vec<String>,
    /// Generic-arg descriptors for a 'ctor-param' ref (see extract.rs's
    /// RefRecord). Appended LAST of all, after `outerTypes`, and set only when
    /// the parameter's type was generic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,
    /// (See extract.rs's RefRecord.) The type whose PROPERTY the
    /// qualifier's last segment is, for a two-segment chain whose head the
    /// enclosing scope could type. Appended after `args`, and never present
    /// alongside `receiverType`.
    #[serde(
        default,
        rename = "receiverPropertyOwner",
        skip_serializing_if = "Option::is_none"
    )]
    pub receiver_property_owner: Option<String>,
    /// (See extract.rs's RefRecord.) The type whose METHOD a
    /// `var x = Q.M(...)` initializer called, and that method's name. Appended
    /// LAST of all, always as a pair, and never alongside `receiverType`: an
    /// absent pair reads back as "no call fact", which is what leaves the local
    /// taken-but-unknown.
    #[serde(
        default,
        rename = "receiverCallOwner",
        skip_serializing_if = "Option::is_none"
    )]
    pub receiver_call_owner: Option<String>,
    #[serde(
        default,
        rename = "receiverCallMember",
        skip_serializing_if = "Option::is_none"
    )]
    /// The receiver call member value.
    pub receiver_call_member: Option<String>,
    /// `true` for a `base.` qualifier -- the member lookup starts at the
    /// enclosing type's bases and never considers the enclosing type
    /// itself (see `extract.rs`'s `RefRecord`). Appended LAST of all, and
    /// omitted when `false` -- an absent key reads back as `false`, the
    /// same as a plain `this.` receiver and as every ref kind that never
    /// sets it, and also what makes a v15 cached fragment parse safely.
    #[serde(default, rename = "receiverBase", skip_serializing_if = "is_false")]
    pub receiver_base: bool,
    /// `true` when `receiverCallOwner`/`receiverCallMember` came from an
    /// AWAITED call (see `extract.rs`'s `RefRecord`). Appended LAST of all,
    /// after `receiverBase`, and omitted when `false` -- an absent key reads
    /// back as `false`, the same as an unawaited call fact and as every ref
    /// kind that never sets it, which is also what lets a cached fragment
    /// from before this field existed parse safely with no cache-version
    /// bump: it simply reads back as "not awaited", the same answer the
    /// resolver gave before this field existed.
    #[serde(default, rename = "receiverAwaited", skip_serializing_if = "is_false")]
    pub receiver_awaited: bool,
    /// `true` when this ref's qualifier is a bare identifier for which the
    /// enclosing MEMBER's own fact table (locals, parameters, lambda
    /// parameters, patterns, `out` designations) holds ANY entry for the
    /// name, typed or taken-but-unknown (see `extract.rs`'s `RefRecord` and
    /// `Scope::has_local_fact`). Read ONLY by the bare-identifier
    /// field/property fallback: a member-scoped name always shadows a
    /// same-named field, whether or not anything vouches for its type, so
    /// that fallback never runs when this is `true`. `false` for every
    /// dotted or generic qualifier, for `this.`/`base.` (never asked of the
    /// enclosing scope's local table at all), and for every ref kind but
    /// `uses-member`. Appended LAST of all, after `receiverAwaited`, and
    /// omitted when `false` -- an absent key reads back as `false`, the
    /// same as every ref kind that never sets it, which is also what lets a
    /// cached fragment from before this field existed parse safely with no
    /// cache-version bump.
    #[serde(default, rename = "receiverLocal", skip_serializing_if = "is_false")]
    pub receiver_local: bool,
    /// Set when this ref's qualifier is an untyped lambda parameter whose
    /// type is a delegate parameter of some OTHER callee (see extract.rs's
    /// `RefRecord`). Never present alongside `receiverType` or
    /// `receiverCallOwner`. Appended LAST of all, after `receiverLocal`,
    /// omitted when absent. Joined the schema with the v18 cache bump: a
    /// v17 fragment read back carries none, and every untyped-lambda
    /// callee-slot lookup this field backs would silently see no
    /// candidate.
    #[serde(
        default,
        rename = "receiverLambda",
        skip_serializing_if = "Option::is_none"
    )]
    pub receiver_lambda: Option<FragLambdaSlot>,
}

fn is_false(b: &bool) -> bool {
    !*b
}

fn is_zero(n: &usize) -> bool {
    *n == 0
}

/// One declared member, with the line its own NAME token sits on.
/// Field order (`name`, `kind`, `line`, `owner`) is significant, and `owner`
/// is omitted when empty -- which is how
/// a markup or resource key, owned by no C# type, serializes with three fields.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FragName {
    /// The name value.
    pub name: String,
    /// The kind value.
    pub kind: String,
    /// The line value.
    pub line: usize,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    /// The owner value.
    pub owner: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Represents `Fragment`.
pub struct Fragment {
    /// The defs value.
    pub defs: Vec<FragDef>,
    /// The usings value.
    pub usings: Vec<FragUsing>,
    /// The refs value.
    pub refs: Vec<FragRef>,
    /// Appended LAST, after `refs`. Always serialized, like its
    /// three siblings: a fragment's top-level arrays are a fixed shape, and
    /// only the fields INSIDE a record follow the omit-when-empty rule.
    #[serde(default)]
    pub names: Vec<FragName>,
}

/// The two shapes a cached fragment can have. Each rel is keyed to whichever
/// shape the file's grammar produced; the `ts: 1` tag is what tells them
/// apart, on disk and at the
/// resolver's door. Untagged, and TS FIRST: a C#/markup fragment carries no
/// `ts` key (so the TS arm always fails on it) and a TS fragment carries no
/// `usings` (so the C# arm always fails on it) -- the discrimination is total
/// in both directions, never a first-match-wins guess.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AnyFragment {
    /// Represents `Ts`.
    Ts(extract::TsFragment),
    /// Represents `Cs`.
    Cs(Fragment),
}

impl From<Fragment> for AnyFragment {
    fn from(f: Fragment) -> Self {
        AnyFragment::Cs(f)
    }
}

impl From<extract::TsFragment> for AnyFragment {
    fn from(f: extract::TsFragment) -> Self {
        AnyFragment::Ts(f)
    }
}

/// Build a graph fragment from this crate's extractor output.
/// `Extraction.purpose` has no fragment
/// counterpart -- the fragment is graph-only.
#[allow(
    clippy::too_many_lines,
    reason = "one ordered field-by-field translation from Extraction into Fragment; splitting it would separate fields that must stay mapped consistently"
)]
pub fn fragment_from_extraction(e: &extract::Extraction) -> Fragment {
    Fragment {
        defs: e
            .defs
            .iter()
            .map(|d| FragDef {
                id: d.id.clone(),
                name: d.name.clone(),
                namespace: d.namespace.clone(),
                kind: d.kind.clone(),
                line: d.line,
                methods: d.methods.clone(),
                properties: d.properties.clone(),
                fields: d.fields.clone(),
                method_returns: {
                    let mut m = OrderedMap::new();
                    for (name, returns) in &d.method_returns {
                        m.insert(name.clone(), returns.clone());
                    }
                    m
                },
                extension_methods: d
                    .extension_methods
                    .iter()
                    .map(|e| FragExtensionMethod {
                        name: e.name.clone(),
                        this_type: e.this_type.clone(),
                        arity_min: e.arity_min,
                        arity_max: e.arity_max,
                        this_args: e.this_args.clone(),
                    })
                    .collect(),
                bases: d.bases.clone(),
                type_params: d.type_params.clone(),
                base_generic_args: {
                    let mut m = OrderedMap::new();
                    for (name, args) in &d.base_generic_args {
                        m.insert(name.clone(), args.clone());
                    }
                    m
                },
                test_methods: d.test_methods.clone(),
                property_types: {
                    let mut m = OrderedMap::new();
                    for (name, fact) in &d.property_types {
                        m.insert(
                            name.clone(),
                            FragFact {
                                type_name: fact.type_name.clone(),
                                args: fact.args.clone(),
                            },
                        );
                    }
                    m
                },
                field_types: {
                    let mut m = OrderedMap::new();
                    for (name, fact) in &d.field_types {
                        m.insert(
                            name.clone(),
                            FragFact {
                                type_name: fact.type_name.clone(),
                                args: fact.args.clone(),
                            },
                        );
                    }
                    m
                },
                method_return_args: {
                    let mut m = OrderedMap::new();
                    for (name, args) in &d.method_return_args {
                        m.insert(name.clone(), args.clone());
                    }
                    m
                },
                non_public_methods: d.non_public_methods.clone(),
                method_arities: {
                    let mut m = OrderedMap::new();
                    for (name, ranges) in &d.method_arities {
                        m.insert(name.clone(), ranges.clone());
                    }
                    m
                },
                method_params: {
                    let mut m = OrderedMap::new();
                    for (name, overloads) in &d.method_params {
                        m.insert(name.clone(), overloads.clone());
                    }
                    m
                },
                end_line: d.end_line,
            })
            .collect(),
        usings: e
            .usings
            .iter()
            .map(|u| match u {
                extract::UsingRecord::Alias {
                    alias,
                    target,
                    global,
                } => FragUsing::Alias {
                    alias: alias.clone(),
                    target: target.clone(),
                    global: *global,
                },
                extract::UsingRecord::Plain { text, global } => FragUsing::Plain {
                    text: text.clone(),
                    global: *global,
                },
            })
            .collect(),
        refs: e
            .refs
            .iter()
            .map(|r| FragRef {
                kind: r.kind.clone(),
                name: r.name.clone(),
                qualified: r.qualified.clone(),
                member: r.member.clone(),
                line: r.line,
                namespace: r.namespace.clone(),
                type_arg_count: r.type_arg_count,
                generic: r.generic,
                receiver_type: r.receiver_type.clone(),
                arg_count: r.arg_count,
                receiver_args: r.receiver_args.clone(),
                outer_types: r.outer_types.clone(),
                args: r.args.clone(),
                receiver_property_owner: r.receiver_property_owner.clone(),
                receiver_call_owner: r.receiver_call_owner.clone(),
                receiver_call_member: r.receiver_call_member.clone(),
                receiver_base: r.receiver_base,
                receiver_awaited: r.receiver_awaited,
                receiver_local: r.receiver_local,
                receiver_lambda: r.receiver_lambda.as_ref().map(|s| FragLambdaSlot {
                    owner: s.owner.clone(),
                    member: s.member.clone(),
                    arg_count: s.arg_count,
                    arg_index: s.arg_index,
                    arity: s.arity,
                    index: s.index,
                }),
            })
            .collect(),
        names: e
            .names
            .iter()
            .map(|n| FragName {
                name: n.name.clone(),
                kind: n.kind.clone(),
                line: n.line,
                owner: n.owner.clone(),
            })
            .collect(),
    }
}

/// Markup and resource files never reach the extractor: a
/// line scan reads them instead (see markup.rs). They still get a fragment even
/// when they declare nothing, because the fragments index is what tells `map`
/// whether the graph's input set changed, and a file missing from it reads as a
/// permanent mismatch. `usings` is always empty: XAML has no using-directive
/// equivalent, and the `xmlns:` prefix declarations that stand in for one are
/// already resolved into fully-qualified ref names by the scan.
pub fn markup_fragment(root: &Path, rel: &str) -> Option<Fragment> {
    // Lossy read: an invalid byte becomes U+FFFD rather than dropping the
    // file.
    let text = String::from_utf8_lossy(&fs::read(root.join(rel)).ok()?).into_owned();
    let facts = crate::markup::markup_facts(rel, &text);
    Some(Fragment {
        defs: facts
            .defs
            .into_iter()
            .map(|d| FragDef {
                id: d.id,
                name: d.name,
                namespace: d.namespace,
                kind: d.kind,
                line: d.line,
                methods: Vec::new(),
                properties: Vec::new(),
                fields: Vec::new(),
                method_returns: OrderedMap::new(),
                extension_methods: Vec::new(),
                bases: Vec::new(),
                type_params: Vec::new(),
                base_generic_args: OrderedMap::new(),
                test_methods: Vec::new(),
                property_types: OrderedMap::new(),
                field_types: OrderedMap::new(),
                method_return_args: OrderedMap::new(),
                non_public_methods: Vec::new(),
                method_arities: OrderedMap::new(),
                method_params: OrderedMap::new(),
                end_line: d.line,
            })
            .collect(),
        usings: Vec::new(),
        refs: facts
            .refs
            .into_iter()
            .map(|r| FragRef {
                kind: r.kind,
                name: r.name,
                qualified: r.qualified,
                member: r.member,
                line: r.line,
                // A markup ref site has no enclosing namespace of its own, and
                // the empty string is what a C# ref at file scope carries too --
                // never `None`, which is the 'imports' spelling.
                namespace: Some(String::new()),
                type_arg_count: Some(0),
                generic: false,
                receiver_type: None,
                arg_count: None,
                receiver_args: None,
                outer_types: Vec::new(),
                args: None,
                receiver_property_owner: None,
                receiver_call_owner: None,
                receiver_call_member: None,
                receiver_base: false,
                receiver_awaited: false,
                receiver_local: false,
                receiver_lambda: None,
            })
            .collect(),
        names: facts
            .names
            .into_iter()
            .map(|n| FragName {
                name: n.name,
                kind: n.kind,
                line: n.line,
                owner: n.owner,
            })
            .collect(),
    })
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Represents `FragmentCacheEntry`.
pub struct FragmentCacheEntry {
    /// The mtime value.
    pub mtime: i64,
    /// The fragment value.
    pub fragment: AnyFragment,
}

fn read_fragments_cache(root: &Path) -> OrderedMap<FragmentCacheEntry> {
    match fs::read_to_string(fragments_cache_path(root)) {
        Ok(text) => serde_json::from_str(&text).unwrap_or_default(),
        Err(_) => OrderedMap::default(),
    }
}

fn write_fragments_cache(root: &Path, cache: &OrderedMap<FragmentCacheEntry>) -> io::Result<()> {
    atomic_write_json(&fragments_cache_path(root), cache)
}

/// Read the fragments index (rel -> mtime). Used for the per-file reuse
/// decision, independent of the graph rebuild.
pub fn read_fragments_index(root: &Path) -> OrderedMap<i64> {
    match fs::read_to_string(fragments_index_path(root)) {
        Ok(text) => serde_json::from_str(&text).unwrap_or_default(),
        Err(_) => OrderedMap::default(),
    }
}

fn write_fragments_index(root: &Path, cache: &OrderedMap<FragmentCacheEntry>) -> io::Result<()> {
    let mut index = OrderedMap::new();
    for (rel, entry) in cache.iter() {
        index.insert(rel.clone(), entry.mtime);
    }
    atomic_write_json(&fragments_index_path(root), &index)
}

/// Whether the fragments index is stale for the given graph files (any mtime
/// mismatch, or a differing file count).
pub fn index_is_stale(index: &OrderedMap<i64>, graph_files: &[GraphFile]) -> bool {
    graph_files
        .iter()
        .any(|f| index.get(&f.rel) != Some(&f.mtime))
        || index.len() != graph_files.len()
}

// ---------------------------------------------------------------------------
// `devscout map`'s cache-then-resolve-then-write cycle.
// ---------------------------------------------------------------------------

/// One file that contributes a graph fragment: C# (defs, refs, member names),
/// markup (`x:Class`/`x:Name`, `.resw` keys -- names only) or TS/JS
/// (imports, exported declarations, call/JSX/dispatch references).
#[derive(Debug, Clone)]
pub struct GraphFile {
    /// The rel value.
    pub rel: String,
    /// The mtime value.
    pub mtime: i64,
}

#[derive(Debug)]
/// Represents `RebuildOutcome`.
pub enum RebuildOutcome {
    /// Represents `NotRebuilt`.
    NotRebuilt,
    /// Represents `Rebuilt`.
    Rebuilt(Graph),
}

/// Whether the graph.json already on disk was written at the CURRENT schema
/// version. Reads the first 64 bytes and compares the literal
/// `{"schema_version":N,` prefix rather than deserializing: `schema_version`
/// is the first key `Graph` serializes, the artifact can be tens of
/// megabytes, and this runs on the fast path whose whole point is not opening
/// it. Anything else -- an older version, an unreadable or truncated file --
/// answers false and costs a rebuild, which is the safe direction.
fn graph_schema_is_current(root: &Path) -> bool {
    let Ok(mut file) = fs::File::open(graph_json_path(root)) else {
        return false;
    };
    let mut head = [0u8; 64];
    let mut filled = 0;
    while filled < head.len() {
        match file.read(&mut head[filled..]) {
            Ok(0) => break,
            Ok(n) => filled += n,
            Err(_) => return false,
        }
    }
    head[..filled].starts_with(format!("{{\"schema_version\":{GRAPH_SCHEMA_VERSION},").as_bytes())
}

// Mirrors the model's units into the staleness sidecar. No model means the
// repo declares no `.csproj`, and then the file must NOT exist: an empty
// `[]` left behind would be indistinguishable from "no model" on the read
// side, and the sidecar's whole job is telling those two apart.
fn write_project_units(
    root: &Path,
    model: Option<&crate::project::ProjectModel>,
) -> io::Result<()> {
    match model {
        Some(m) => atomic_write_json(&project_units_path(root), &crate::project::graph_units(m)),
        None => {
            let path = project_units_path(root);
            match fs::remove_file(&path) {
                Ok(()) => Ok(()),
                Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
                Err(e) => Err(e),
            }
        }
    }
}

/// `fresh_fragments`: fragments this run's extractor produced for files that
/// needed reparsing (the same set that got a fresh purpose signature in the
/// real `devscout map` flow -- `mapcmd::map_repo` assembles it). `changed`: from the
/// caller's own `indexIsStale`-equivalent check against `csFiles`, passed in
/// rather than recomputed so the unchanged path never opens any graph file.
/// `model`: the repo's discovered `.csproj` projects, or `None` when it
/// declares none -- serialized into `graph.units` and mirrored into the
/// `project_units_path` staleness sidecar. The caller is expected to have
/// already folded `project::sidecar_differs` into `changed`; this function
/// only writes the sidecar, it never decides on it.
pub fn rebuild_graph(
    root: &Path,
    graph_files: &[GraphFile],
    fresh_fragments: &HashMap<String, AnyFragment>,
    changed: bool,
    model: Option<&crate::project::ProjectModel>,
) -> io::Result<RebuildOutcome> {
    if !changed && graph_json_path(root).exists() && graph_schema_is_current(root) {
        return Ok(RebuildOutcome::NotRebuilt);
    }

    let cache = read_fragments_cache(root);
    // Split at the door: the two shapes share no field beyond
    // `defs`, and letting one resolver see the other's names would resolve a
    // C# type reference onto a same-named TypeScript const. Built as two vecs
    // here rather than one mixed vec split later so no fragment is cloned a
    // third time on the rebuild path.
    let mut merged_cs: Vec<(String, Fragment)> = Vec::new();
    let mut merged_ts: Vec<(String, extract::TsFragment)> = Vec::new();
    let mut new_cache: OrderedMap<FragmentCacheEntry> = OrderedMap::new();
    for f in graph_files {
        let fragment = match cache.get(&f.rel) {
            Some(entry) if entry.mtime == f.mtime => Some(entry.fragment.clone()),
            _ => fresh_fragments.get(&f.rel).cloned(),
        };
        let Some(fragment) = fragment else { continue };
        match &fragment {
            AnyFragment::Cs(c) => merged_cs.push((f.rel.clone(), c.clone())),
            AnyFragment::Ts(t) => merged_ts.push((f.rel.clone(), t.clone())),
        }
        new_cache.insert(
            f.rel.clone(),
            FragmentCacheEntry {
                mtime: f.mtime,
                fragment,
            },
        );
    }

    let graph = crate::resolve::resolve_graph_with_model(root, &merged_cs, &merged_ts, model);
    write_graph(root, &graph)?;
    write_project_units(root, model)?;
    write_fragments_cache(root, &new_cache)?;
    write_fragments_index(root, &new_cache)?;
    remove_superseded_caches(root);
    Ok(RebuildOutcome::Rebuilt(graph))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_dir(label: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("scout-graph-test-{label}-{nanos}"));
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    // --- OrderedMap: order + round-trip -------------------------------

    #[test]
    fn ordered_map_preserves_insertion_order_through_json_round_trip() {
        let mut m: OrderedMap<i64> = OrderedMap::new();
        m.insert("z.cs".to_string(), 3);
        m.insert("a.cs".to_string(), 1);
        m.insert("m.cs".to_string(), 2);
        let json = serde_json::to_string(&m).unwrap();
        assert_eq!(json, r#"{"z.cs":3,"a.cs":1,"m.cs":2}"#);

        let reparsed: OrderedMap<i64> = serde_json::from_str(&json).unwrap();
        let keys: Vec<&String> = reparsed.iter().map(|(k, _)| k).collect();
        assert_eq!(keys, vec!["z.cs", "a.cs", "m.cs"]);
    }

    #[test]
    fn ordered_map_insert_overwrite_keeps_original_position() {
        let mut m: OrderedMap<i64> = OrderedMap::new();
        m.insert("a".to_string(), 1);
        m.insert("b".to_string(), 2);
        m.insert("a".to_string(), 99);
        let keys: Vec<&String> = m.iter().map(|(k, _)| k).collect();
        assert_eq!(keys, vec!["a", "b"]);
        assert_eq!(m.get("a"), Some(&99));
    }

    // --- Percent1: number-shaped formatting -------------------------

    #[test]
    fn percent1_whole_value_serializes_without_decimal_point() {
        let p = Percent1::from_ratio(2, 10); // 20.0 -> "20"
        assert_eq!(serde_json::to_string(&p).unwrap(), "20");
    }

    #[test]
    fn percent1_fractional_value_serializes_with_one_decimal_digit() {
        let p = Percent1::from_ratio(1, 3); // 33.333... -> round to 33.3
        assert_eq!(serde_json::to_string(&p).unwrap(), "33.3");
    }

    #[test]
    fn percent1_zero_denominator_is_zero() {
        assert_eq!(Percent1::from_ratio(0, 0), Percent1::zero());
        assert_eq!(serde_json::to_string(&Percent1::zero()).unwrap(), "0");
    }

    // --- FragDef's new keys, appended last, omitted when empty ----------------------

    fn frag_def(
        methods: &[&str],
        properties: &[&str],
        fields: &[&str],
        method_returns: &[(&str, &str)],
        extension_methods: &[(&str, &str, usize, i64)],
    ) -> FragDef {
        frag_def_with_bases(
            methods,
            properties,
            fields,
            method_returns,
            extension_methods,
            &[],
        )
    }

    fn frag_def_with_bases(
        methods: &[&str],
        properties: &[&str],
        fields: &[&str],
        method_returns: &[(&str, &str)],
        extension_methods: &[(&str, &str, usize, i64)],
        bases: &[&str],
    ) -> FragDef {
        let mut mr = OrderedMap::new();
        for (k, v) in method_returns {
            mr.insert((*k).to_string(), (*v).to_string());
        }
        FragDef {
            id: "App.Facts.Widget".into(),
            name: "Widget".into(),
            namespace: "App.Facts".into(),
            kind: "class".into(),
            line: 3,
            methods: methods.iter().map(|s| s.to_string()).collect(),
            properties: properties.iter().map(|s| s.to_string()).collect(),
            fields: fields.iter().map(|s| s.to_string()).collect(),
            method_returns: mr,
            extension_methods: extension_methods
                .iter()
                .map(|(n, t, lo, hi)| FragExtensionMethod {
                    name: (*n).to_string(),
                    this_type: (*t).to_string(),
                    arity_min: *lo,
                    arity_max: *hi,
                    this_args: None,
                })
                .collect(),
            bases: bases.iter().map(|s| s.to_string()).collect(),
            type_params: Vec::new(),
            base_generic_args: OrderedMap::new(),
            property_types: OrderedMap::new(),
            field_types: OrderedMap::new(),
            method_return_args: OrderedMap::new(),
            non_public_methods: Vec::new(),
            method_arities: OrderedMap::new(),
            method_params: OrderedMap::new(),
            test_methods: Vec::new(),
            end_line: 0,
        }
    }

    #[test]
    fn frag_def_appends_properties_fields_and_method_returns_last_in_that_order() {
        let json = serde_json::to_string(&frag_def(
            &["GetAsync"],
            &["Prefix"],
            &["_log"],
            &[("GetAsync", "Task")],
            &[],
        ))
        .unwrap();
        assert_eq!(
            json,
            r#"{"id":"App.Facts.Widget","name":"Widget","namespace":"App.Facts","kind":"class","line":3,"methods":["GetAsync"],"properties":["Prefix"],"fields":["_log"],"methodReturns":{"GetAsync":"Task"}}"#
        );
    }

    #[test]
    fn frag_def_omits_all_three_new_keys_when_the_type_declares_none_of_them() {
        let json = serde_json::to_string(&frag_def(&["Go"], &[], &[], &[], &[])).unwrap();
        assert_eq!(
            json,
            r#"{"id":"App.Facts.Widget","name":"Widget","namespace":"App.Facts","kind":"class","line":3,"methods":["Go"]}"#,
            "pre-stage-2 bytes preserved exactly"
        );
    }

    // --- extensionMethods lands AFTER methodReturns, entry keys
    // in (name, thisType, arityMin, arityMax, thisArgs) order, omitted when
    // empty; `bases` lands after extensionMethods -------------------------

    #[test]
    fn frag_def_appends_extension_methods_after_method_returns_with_the_arity_range_last() {
        let json = serde_json::to_string(&frag_def(
            &["Go"],
            &["Prefix"],
            &["_log"],
            &[("Go", "Task")],
            &[
                ("Render", "Widget", 0, 0),
                ("Render", "Widget", 2, 3),
                ("Trim", "string", 0, -1),
            ],
        ))
        .unwrap();
        assert_eq!(
            json,
            r#"{"id":"App.Facts.Widget","name":"Widget","namespace":"App.Facts","kind":"class","line":3,"methods":["Go"],"properties":["Prefix"],"fields":["_log"],"methodReturns":{"Go":"Task"},"extensionMethods":[{"name":"Render","thisType":"Widget","arityMin":0,"arityMax":0},{"name":"Render","thisType":"Widget","arityMin":2,"arityMax":3},{"name":"Trim","thisType":"string","arityMin":0,"arityMax":-1}]}"#
        );
    }

    #[test]
    fn frag_def_this_args_lands_after_arity_max_and_bases_after_extension_methods() {
        let mut d = frag_def_with_bases(
            &["Go"],
            &[],
            &[],
            &[],
            &[("Each", "List", 0, 0)],
            &["BaseWidget", "IWidget"],
        );
        d.extension_methods[0].this_args = Some(vec!["Widget".into()]);
        let json = serde_json::to_string(&d).unwrap();
        assert_eq!(
            json,
            r#"{"id":"App.Facts.Widget","name":"Widget","namespace":"App.Facts","kind":"class","line":3,"methods":["Go"],"extensionMethods":[{"name":"Each","thisType":"List","arityMin":0,"arityMax":0,"thisArgs":["Widget"]}],"bases":["BaseWidget","IWidget"]}"#
        );
        let reparsed: FragDef = serde_json::from_str(&json).unwrap();
        assert_eq!(
            reparsed.bases,
            vec!["BaseWidget".to_string(), "IWidget".to_string()]
        );
        assert_eq!(
            reparsed.extension_methods[0].this_args,
            Some(vec!["Widget".to_string()])
        );
    }

    #[test]
    fn frag_def_omits_bases_when_the_type_lists_none() {
        let json = serde_json::to_string(&frag_def(&["Go"], &[], &[], &[], &[])).unwrap();
        assert!(
            !json.contains("bases"),
            "an empty base list must be omitted entirely: {json}"
        );
        let reparsed: FragDef = serde_json::from_str(&json).unwrap();
        assert!(
            reparsed.bases.is_empty(),
            "an absent key reads back as \"lists none\""
        );
    }

    // --- test-coverage stage: testMethods lands AFTER bases, omitted when
    // the type declares no tests ------------------------------------------

    #[test]
    fn frag_def_appends_test_methods_last_after_bases() {
        let mut d = frag_def_with_bases(&["Go"], &[], &[], &[], &[], &["BaseWidget"]);
        d.test_methods = vec!["TotalsAnEmptyOrder".into(), "TotalsALineItem".into()];
        let json = serde_json::to_string(&d).unwrap();
        assert_eq!(
            json,
            r#"{"id":"App.Facts.Widget","name":"Widget","namespace":"App.Facts","kind":"class","line":3,"methods":["Go"],"bases":["BaseWidget"],"testMethods":["TotalsAnEmptyOrder","TotalsALineItem"]}"#
        );
        let reparsed: FragDef = serde_json::from_str(&json).unwrap();
        assert_eq!(
            reparsed.test_methods,
            vec![
                "TotalsAnEmptyOrder".to_string(),
                "TotalsALineItem".to_string()
            ]
        );
    }

    #[test]
    fn frag_def_omits_test_methods_when_the_type_declares_no_tests() {
        let json = serde_json::to_string(&frag_def(&["Go"], &[], &[], &[], &[])).unwrap();
        assert!(
            !json.contains("testMethods"),
            "pre-stage bytes preserved exactly: {json}"
        );
        let reparsed: FragDef = serde_json::from_str(&json).unwrap();
        assert!(
            reparsed.test_methods.is_empty(),
            "an absent key reads back as \"declares no tests\""
        );
    }

    #[test]
    fn frag_def_omits_extension_methods_when_the_type_declares_none() {
        let json =
            serde_json::to_string(&frag_def(&["Go"], &[], &[], &[("Go", "Task")], &[])).unwrap();
        assert!(
            !json.contains("extensionMethods"),
            "pre-stage-3 bytes preserved exactly: {json}"
        );
        let reparsed: FragDef = serde_json::from_str(&json).unwrap();
        assert!(
            reparsed.extension_methods.is_empty(),
            "an absent key reads back as \"declares none\""
        );
    }

    #[test]
    fn frag_def_method_returns_serializes_in_first_declaration_order_not_sorted() {
        // A BTreeMap here would emit Alpha before Zebra -- the required order
        // is insertion (first-declaration) order.
        let json = serde_json::to_string(&frag_def(
            &[],
            &[],
            &[],
            &[("Zebra", "Z"), ("Alpha", "A")],
            &[],
        ))
        .unwrap();
        assert!(
            json.ends_with(r#""methodReturns":{"Zebra":"Z","Alpha":"A"}}"#),
            "insertion order, not sorted: {json}"
        );
        let reparsed: FragDef = serde_json::from_str(&json).unwrap();
        let keys: Vec<&String> = reparsed.method_returns.iter().map(|(k, _)| k).collect();
        assert_eq!(
            keys,
            vec!["Zebra", "Alpha"],
            "and the order survives a round trip"
        );
    }

    // --- propertyTypes lands AFTER testMethods, omitted when the
    // type declares no typed property ---------------------------------------

    #[test]
    fn frag_def_appends_property_types_last_after_test_methods() {
        let mut d =
            frag_def_with_bases(&["Go"], &["Dial", "Slots"], &[], &[], &[], &["BaseWidget"]);
        d.test_methods = vec!["TotalsALineItem".into()];
        d.property_types.insert(
            "Dial".into(),
            FragFact {
                type_name: "Gauge".into(),
                args: None,
            },
        );
        d.property_types.insert(
            "Slots".into(),
            FragFact {
                type_name: "Toolbox".into(),
                args: Some(vec!["Gadget".into()]),
            },
        );
        let json = serde_json::to_string(&d).unwrap();
        assert_eq!(
            json,
            r#"{"id":"App.Facts.Widget","name":"Widget","namespace":"App.Facts","kind":"class","line":3,"methods":["Go"],"properties":["Dial","Slots"],"bases":["BaseWidget"],"testMethods":["TotalsALineItem"],"propertyTypes":{"Dial":{"type":"Gauge"},"Slots":{"type":"Toolbox","args":["Gadget"]}}}"#
        );
        let reparsed: FragDef = serde_json::from_str(&json).unwrap();
        let keys: Vec<&String> = reparsed.property_types.iter().map(|(k, _)| k).collect();
        assert_eq!(
            keys,
            vec!["Dial", "Slots"],
            "source order survives a round trip, like methodReturns"
        );
    }

    #[test]
    fn frag_def_omits_property_types_when_no_property_carries_a_fact() {
        let json = serde_json::to_string(&frag_def(&["Go"], &["Label"], &[], &[], &[])).unwrap();
        assert!(
            !json.contains("propertyTypes"),
            "pre-propertyTypes bytes preserved exactly: {json}"
        );
        let reparsed: FragDef = serde_json::from_str(&json).unwrap();
        assert!(
            reparsed.property_types.is_empty(),
            "an absent key reads back as \"no property vouches for a type\""
        );
    }

    // --- FragRef's receiverType then argCount, appended
    // after generic in that order ------------------------------------------

    fn frag_ref(generic: bool, receiver_type: Option<&str>, arg_count: Option<usize>) -> FragRef {
        FragRef {
            kind: "uses-member".into(),
            name: "repo".into(),
            qualified: None,
            member: Some("Save".into()),
            line: 7,
            namespace: Some("App.Shape".into()),
            type_arg_count: None,
            generic,
            receiver_type: receiver_type.map(String::from),
            arg_count,
            receiver_args: None,
            outer_types: Vec::new(),
            args: None,
            receiver_property_owner: None,
            receiver_call_owner: None,
            receiver_call_member: None,
            receiver_base: false,
            receiver_awaited: false,
            receiver_local: false,
            receiver_lambda: None,
        }
    }

    #[test]
    fn frag_ref_receiver_args_is_appended_last_after_arg_count() {
        let r = FragRef {
            receiver_args: Some(vec!["FutureState".into(), "*".into()]),
            ..frag_ref(false, Some("Binder"), Some(1))
        };
        let json = serde_json::to_string(&r).unwrap();
        assert_eq!(
            json,
            r#"{"kind":"uses-member","name":"repo","member":"Save","line":7,"namespace":"App.Shape","receiverType":"Binder","argCount":1,"receiverArgs":["FutureState","*"]}"#
        );
        let reparsed: FragRef = serde_json::from_str(&json).unwrap();
        assert_eq!(
            reparsed.receiver_args,
            Some(vec!["FutureState".to_string(), "*".to_string()])
        );
    }

    #[test]
    fn frag_ref_receiver_type_then_arg_count_are_appended_last_after_generic() {
        let json = serde_json::to_string(&frag_ref(true, Some("IRepo"), Some(2))).unwrap();
        assert_eq!(
            json,
            r#"{"kind":"uses-member","name":"repo","member":"Save","line":7,"namespace":"App.Shape","generic":true,"receiverType":"IRepo","argCount":2}"#
        );
    }

    #[test]
    fn frag_ref_arg_count_zero_still_serializes_it() {
        // The guard is presence (argCount may be 0), never truthiness -- a
        // zero-argument call is a real call and its 0 is what matches an
        // arity-0 extension.
        let json = serde_json::to_string(&frag_ref(false, Some("IRepo"), Some(0))).unwrap();
        assert!(
            json.ends_with(r#""receiverType":"IRepo","argCount":0}"#),
            "argCount 0 must survive: {json}"
        );
    }

    #[test]
    fn frag_ref_without_a_fact_keeps_its_pre_stage_2_bytes() {
        let json = serde_json::to_string(&frag_ref(false, None, None)).unwrap();
        assert_eq!(
            json,
            r#"{"kind":"uses-member","name":"repo","member":"Save","line":7,"namespace":"App.Shape"}"#
        );
        let reparsed: FragRef = serde_json::from_str(&json).unwrap();
        assert_eq!(
            reparsed.receiver_type, None,
            "an absent key reads back as no fact"
        );
        assert_eq!(
            reparsed.arg_count, None,
            "and an absent argCount reads back as \"not a call\""
        );
        assert_eq!(
            reparsed.receiver_args, None,
            "and an absent receiverArgs reads back as \"not generic\""
        );
    }

    // --- Def: also_in omission ------------------------------------------

    #[test]
    fn def_without_also_in_omits_the_key() {
        let d = Def {
            id: "Ns.Type".into(),
            name: "Type".into(),
            namespace: "Ns".into(),
            kind: "class".into(),
            file: "Ns/Type.cs".into(),
            line: 3,
            methods: vec![],
            test_methods: vec![],
            also_in: vec![],
            end_line: 0,
        };
        let json = serde_json::to_string(&d).unwrap();
        assert!(
            !json.contains("also_in"),
            "empty also_in must be omitted: {json}"
        );
    }

    #[test]
    fn def_end_line_serializes_last_and_defaults_when_absent() {
        let mut d = Def {
            id: "Ns.Type".into(),
            name: "Type".into(),
            namespace: "Ns".into(),
            kind: "class".into(),
            file: "Ns/Type.cs".into(),
            line: 3,
            methods: vec![],
            test_methods: vec![],
            also_in: vec![],
            end_line: 0,
        };
        assert!(!serde_json::to_string(&d).unwrap().contains("endLine"));
        d.end_line = 9;
        assert!(serde_json::to_string(&d)
            .unwrap()
            .ends_with(",\"endLine\":9}"));
    }

    #[test]
    fn def_with_also_in_includes_it_after_methods() {
        let d = Def {
            id: "Ns.Type".into(),
            name: "Type".into(),
            namespace: "Ns".into(),
            kind: "class".into(),
            file: "Ns/Type.cs".into(),
            line: 3,
            methods: vec!["M".into()],
            test_methods: vec![],
            also_in: vec![AlsoIn {
                file: "Ns/Type.Extra.cs".into(),
                line: 5,
            }],
            end_line: 0,
        };
        let json = serde_json::to_string(&d).unwrap();
        let methods_pos = json.find("\"methods\"").unwrap();
        let also_in_pos = json.find("\"also_in\"").unwrap();
        assert!(
            methods_pos < also_in_pos,
            "also_in must come after methods: {json}"
        );
    }

    // --- test-coverage stage: the def ROW keeps testMethods, between
    // methods and also_in ---------------------------------------------------

    #[test]
    fn def_row_places_test_methods_between_methods_and_also_in() {
        let d = Def {
            id: "Ns.TypeTests".into(),
            name: "TypeTests".into(),
            namespace: "Ns".into(),
            kind: "class".into(),
            file: "Ns/TypeTests.cs".into(),
            line: 3,
            methods: vec!["M".into()],
            test_methods: vec!["Fact1".into()],
            also_in: vec![AlsoIn {
                file: "Ns/TypeTests.Extra.cs".into(),
                line: 5,
            }],
            end_line: 0,
        };
        let json = serde_json::to_string(&d).unwrap();
        assert_eq!(
            json,
            r#"{"id":"Ns.TypeTests","name":"TypeTests","namespace":"Ns","kind":"class","file":"Ns/TypeTests.cs","line":3,"methods":["M"],"testMethods":["Fact1"],"also_in":[{"file":"Ns/TypeTests.Extra.cs","line":5}]}"#
        );
    }

    #[test]
    fn def_row_omits_test_methods_when_the_def_declares_no_tests() {
        let d = Def {
            id: "Ns.Type".into(),
            name: "Type".into(),
            namespace: "Ns".into(),
            kind: "class".into(),
            file: "Ns/Type.cs".into(),
            line: 3,
            methods: vec!["M".into()],
            test_methods: vec![],
            also_in: vec![],
            end_line: 0,
        };
        let json = serde_json::to_string(&d).unwrap();
        assert!(
            !json.contains("testMethods"),
            "empty testMethods must be omitted: {json}"
        );
    }

    // --- test-coverage stage: stats gains test_def_count, LAST -------------

    #[test]
    fn stats_appends_test_def_count_last_and_always_writes_it() {
        let stats = Stats {
            def_count: 2,
            file_count: 1,
            edges_by_kind: EdgesByKind::default(),
            ambiguous_count: 0,
            ambiguous_pct: Percent1::zero(),
            unresolved_external_count: 0,
            heuristic_edge_count: 0,
            test_def_count: 0,
            heuristic_by_tier: HeuristicByTier::default(),
            ts: None,
        };
        let json = serde_json::to_string(&stats).unwrap();
        assert!(
            json.ends_with(
                r#""heuristic_edge_count":0,"test_def_count":0,"heuristic_by_tier":{"ext":0,"guess":0}}"#
            ),
            "heuristic_by_tier is LAST, after test_def_count, and both its keys are always written: {json}"
        );
    }

    /// The same append-last rule for a TS repo, which is the only tree where
    /// the two optional tail keys can both appear: `ts` was added first and
    /// `heuristic_by_tier` after it, so `heuristic_by_tier` still ends the
    /// block and `ts` sits between it and `test_def_count`. A reader diffing a
    /// TS graph against an older one sees each new fact appended, never
    /// inserted ahead of an older key.
    #[test]
    fn stats_keeps_heuristic_by_tier_last_even_when_a_ts_block_is_present() {
        let stats = Stats {
            def_count: 0,
            file_count: 0,
            edges_by_kind: EdgesByKind::default(),
            ambiguous_count: 0,
            ambiguous_pct: Percent1::zero(),
            unresolved_external_count: 0,
            heuristic_edge_count: 0,
            test_def_count: 0,
            heuristic_by_tier: HeuristicByTier::default(),
            ts: Some(crate::tsgraph::TsStats {
                ts_file_count: 1,
                ts_def_count: 2,
                external_import_count: 3,
                unresolved_ref_count: 4,
            }),
        };
        let json = serde_json::to_string(&stats).unwrap();
        assert!(
            json.ends_with(concat!(
                r#""test_def_count":0,"#,
                r#""ts":{"ts_file_count":1,"ts_def_count":2,"external_import_count":3,"unresolved_ref_count":4},"#,
                r#""heuristic_by_tier":{"ext":0,"guess":0}}"#
            )),
            "key order must be test_def_count, ts, heuristic_by_tier: {json}"
        );
    }

    // --- Edge: shape-per-kind, tag first ---------------------------------

    #[test]
    fn imports_edge_has_target_not_to() {
        let e = Edge::Imports {
            from_file: "F.cs".into(),
            from_line: 1,
            target: "System".into(),
        };
        let json = serde_json::to_string(&e).unwrap();
        assert_eq!(
            json,
            r#"{"kind":"imports","from_file":"F.cs","from_line":1,"target":"System"}"#
        );
    }

    #[test]
    fn uses_type_edge_shape() {
        let e = Edge::UsesType {
            from_file: "F.cs".into(),
            from_line: 1,
            to: "Ns.T".into(),
            to_file: "Ns/T.cs".into(),
            heuristic: false,
        };
        let json = serde_json::to_string(&e).unwrap();
        assert_eq!(
            json,
            r#"{"kind":"uses-type","from_file":"F.cs","from_line":1,"to":"Ns.T","to_file":"Ns/T.cs"}"#
        );
    }

    // The serialized shape in one assertion: `heuristic` is the LAST key, it
    // appears only when set, and a precise edge of the same kind is
    // byte-for-byte what it was before the tag existed.
    #[test]
    fn heuristic_flag_is_appended_last_and_omitted_when_false() {
        let precise = Edge::UsesMember {
            from_file: "F.cs".into(),
            from_line: 1,
            to: "Ns.T".into(),
            to_file: "Ns/T.cs".into(),
            heuristic: false,
            tier: None,
            member: None,
        };
        assert_eq!(
            serde_json::to_string(&precise).unwrap(),
            r#"{"kind":"uses-member","from_file":"F.cs","from_line":1,"to":"Ns.T","to_file":"Ns/T.cs"}"#
        );
        let guess = Edge::UsesMember {
            from_file: "F.cs".into(),
            from_line: 1,
            to: "Ns.T".into(),
            to_file: "Ns/T.cs".into(),
            heuristic: true,
            tier: Some(HeuristicTier::Guess),
            member: Some("M".into()),
        };
        assert_eq!(
            serde_json::to_string(&guess).unwrap(),
            r#"{"kind":"uses-member","from_file":"F.cs","from_line":1,"to":"Ns.T","to_file":"Ns/T.cs","heuristic":true,"tier":"guess","member":"M"}"#
        );
        let ext = Edge::UsesMember {
            from_file: "F.cs".into(),
            from_line: 1,
            to: "Ns.T".into(),
            to_file: "Ns/T.cs".into(),
            heuristic: true,
            tier: Some(HeuristicTier::Ext),
            member: Some("M".into()),
        };
        assert_eq!(
            serde_json::to_string(&ext).unwrap(),
            r#"{"kind":"uses-member","from_file":"F.cs","from_line":1,"to":"Ns.T","to_file":"Ns/T.cs","heuristic":true,"tier":"ext","member":"M"}"#
        );
        // And it reads back: an edge written by either runtime round-trips
        // with the flag intact, absent meaning precise -- and now with its
        // tier and member intact too, which is what makes an older graph.json
        // (neither key written) still parse, as two `None`s.
        assert_eq!(
            serde_json::from_str::<Edge>(&serde_json::to_string(&guess).unwrap()).unwrap(),
            guess
        );
        assert_eq!(
            serde_json::from_str::<Edge>(&serde_json::to_string(&ext).unwrap()).unwrap(),
            ext
        );
        assert_eq!(
            serde_json::from_str::<Edge>(&serde_json::to_string(&precise).unwrap()).unwrap(),
            precise
        );
    }

    // The append ORDER, pinned on its own: `heuristic`, then `tier`, then
    // `member`, each omitted when it has nothing to say. A precise edge that
    // does name its member -- which is every precise uses-member edge the
    // resolver emits -- carries `member` and nothing else, so its bytes gain
    // exactly one key over the pre-tier shape.
    #[test]
    fn uses_member_edge_appends_tier_then_member_after_heuristic_and_omits_both_when_precise() {
        let precise = Edge::uses_member(
            "F.cs".into(),
            1,
            "Ns.T".into(),
            "Ns/T.cs".into(),
            Some("M".into()),
            None,
        );
        assert_eq!(
            serde_json::to_string(&precise).unwrap(),
            r#"{"kind":"uses-member","from_file":"F.cs","from_line":1,"to":"Ns.T","to_file":"Ns/T.cs","member":"M"}"#
        );
        assert!(!precise.is_heuristic(), "no tier means no guess");
        assert_eq!(precise.tier(), None);

        for (tier, word) in [(HeuristicTier::Ext, "ext"), (HeuristicTier::Guess, "guess")] {
            let e = Edge::uses_member(
                "F.cs".into(),
                1,
                "Ns.T".into(),
                "Ns/T.cs".into(),
                Some("M".into()),
                Some(tier),
            );
            assert_eq!(
                serde_json::to_string(&e).unwrap(),
                format!(
                    r#"{{"kind":"uses-member","from_file":"F.cs","from_line":1,"to":"Ns.T","to_file":"Ns/T.cs","heuristic":true,"tier":"{word}","member":"M"}}"#
                ),
                "heuristic, then tier, then member"
            );
            // The constructor is what makes the flag and the tier one fact:
            // pass a tier and the edge is a guess, pass none and it is not.
            assert!(e.is_heuristic());
            assert_eq!(e.tier(), Some(tier));
        }

        // The two kinds that carry the flag but no tier answer `None` rather
        // than guessing on the reader's behalf.
        assert_eq!(
            Edge::UsesType {
                from_file: "F.cs".into(),
                from_line: 1,
                to: "Ns.T".into(),
                to_file: "Ns/T.cs".into(),
                heuristic: true,
            }
            .tier(),
            None
        );
    }

    #[test]
    fn ambiguous_edge_shape() {
        let e = Edge::Ambiguous {
            origin: "uses-type".into(),
            from_file: "F.cs".into(),
            from_line: 4,
            raw: "Money".into(),
            candidates: vec![Candidate {
                id: "A.Money".into(),
                file: "A/Money.cs".into(),
            }],
            candidate_count: 2,
        };
        let json = serde_json::to_string(&e).unwrap();
        assert_eq!(
            json,
            r#"{"kind":"ambiguous","origin":"uses-type","from_file":"F.cs","from_line":4,"raw":"Money","candidates":[{"id":"A.Money","file":"A/Money.cs"}],"candidate_count":2}"#
        );
    }

    // --- graph.json: `units` is appended after `names` --------------------

    fn empty_stats() -> Stats {
        Stats {
            def_count: 0,
            file_count: 0,
            edges_by_kind: EdgesByKind::default(),
            ambiguous_count: 0,
            ambiguous_pct: Percent1::zero(),
            unresolved_external_count: 0,
            heuristic_edge_count: 0,
            test_def_count: 0,
            heuristic_by_tier: HeuristicByTier::default(),
            ts: None,
        }
    }

    // The two halves of the `units` contract in one place: a graph whose
    // repo declares no project must serialize with NO `units` key at all
    // (that is what keeps every csproj-less tree byte-identical to what it
    // was), and one that does must carry `units` LAST -- after `names` --
    // with each row keyed `id`, `name`, `refs`, `test` in that order and the
    // last two omitted at their empty/false value. Byte literals on purpose:
    // a golden recomputed by the code under test proves nothing.
    #[test]
    fn graph_omits_units_when_empty_and_appends_them_after_names_otherwise() {
        let mut g = Graph {
            schema_version: GRAPH_SCHEMA_VERSION,
            built_at_head: None,
            defs: Vec::new(),
            edges: Vec::new(),
            stats: empty_stats(),
            names: vec![GraphName {
                name: "A".to_string(),
                kind: "class".to_string(),
                file: "A/A.cs".to_string(),
                line: 1,
                owner: String::new(),
            }],
            units: Vec::new(),
        };

        const WITHOUT_UNITS: &str = concat!(
            r#"{"schema_version":2,"built_at_head":null,"defs":[],"edges":[],"stats":{"def_count":0,"#,
            r#""file_count":0,"edges_by_kind":{"inherits":0,"uses-type":0,"imports":0,"uses-member":0,"#,
            r#""ctor-di":0},"ambiguous_count":0,"ambiguous_pct":0,"unresolved_external_count":0,"#,
            r#""heuristic_edge_count":0,"test_def_count":0,"heuristic_by_tier":{"ext":0,"guess":0}},"#,
            r#""names":[{"name":"A","kind":"class","file":"A/A.cs","line":1}]}"#,
        );
        assert_eq!(
            serde_json::to_string(&g).unwrap(),
            WITHOUT_UNITS,
            "an empty unit list must not emit a `units` key at all"
        );

        g.units = vec![
            GraphUnit {
                id: "A/A.csproj".to_string(),
                name: "A".to_string(),
                refs: vec!["B/B.csproj".to_string()],
                test: false,
            },
            GraphUnit {
                id: "B/B.csproj".to_string(),
                name: "B".to_string(),
                refs: Vec::new(),
                test: false,
            },
            GraphUnit {
                id: "T/T.Tests.csproj".to_string(),
                name: "T.Tests".to_string(),
                refs: vec!["A/A.csproj".to_string()],
                test: true,
            },
        ];

        const WITH_UNITS: &str = concat!(
            r#""names":[{"name":"A","kind":"class","file":"A/A.cs","line":1}],"#,
            r#""units":[{"id":"A/A.csproj","name":"A","refs":["B/B.csproj"]},"#,
            r#"{"id":"B/B.csproj","name":"B"},"#,
            r#"{"id":"T/T.Tests.csproj","name":"T.Tests","refs":["A/A.csproj"],"test":true}]}"#,
        );
        let json = serde_json::to_string(&g).unwrap();
        assert_eq!(
            json,
            format!(
                "{}{}",
                WITHOUT_UNITS
                    .strip_suffix(
                        r#""names":[{"name":"A","kind":"class","file":"A/A.cs","line":1}]}"#
                    )
                    .unwrap(),
                WITH_UNITS
            ),
            "`units` is appended after `names` and changes nothing before it"
        );

        // And a graph.json written before `units` existed still reads back --
        // the field defaults rather than failing the parse.
        let reparsed: Graph = serde_json::from_str(WITHOUT_UNITS).unwrap();
        assert!(reparsed.units.is_empty());
        let round_tripped: Graph = serde_json::from_str(&json).unwrap();
        assert_eq!(round_tripped.units, g.units);
    }

    // --- Stats: fixed edges_by_kind order ---------------------------------

    #[test]
    fn edges_by_kind_field_order_is_fixed_not_alphabetical() {
        let s = EdgesByKind {
            inherits: 1,
            uses_type: 2,
            imports: 3,
            uses_member: 4,
            ctor_di: 5,
            ..Default::default()
        };
        let json = serde_json::to_string(&s).unwrap();
        assert_eq!(
            json,
            r#"{"inherits":1,"uses-type":2,"imports":3,"uses-member":4,"ctor-di":5}"#
        );
    }

    // --- The cache holds two fragment shapes -------------------

    // The untagged discrimination is what keeps one cache file able to hold
    // both shapes: read the wrong arm and a whole repo's fragments come back
    // silently empty. Both directions are pinned here, on the exact
    // serialized bytes.
    #[test]
    fn any_fragment_round_trips_both_shapes_and_never_reads_one_as_the_other() {
        let cs = AnyFragment::Cs(Fragment {
            defs: Vec::new(),
            usings: Vec::new(),
            refs: Vec::new(),
            names: Vec::new(),
        });
        let cs_json = serde_json::to_string(&cs).unwrap();
        assert_eq!(cs_json, r#"{"defs":[],"usings":[],"refs":[],"names":[]}"#);
        assert!(matches!(
            serde_json::from_str::<AnyFragment>(&cs_json).unwrap(),
            AnyFragment::Cs(_)
        ));

        let ts = AnyFragment::Ts(extract::TsFragment {
            ts: 1,
            defs: vec![extract::TsFragmentDef {
                name: "x".into(),
                kind: "const".into(),
                line: 1,
                end_line: 1,
            }],
            imports: Vec::new(),
            reexports: Vec::new(),
            refs: Vec::new(),
            default: None,
        });
        let ts_json = serde_json::to_string(&ts).unwrap();
        assert_eq!(
            ts_json,
            r#"{"ts":1,"defs":[{"name":"x","kind":"const","line":1,"endLine":1}],"imports":[],"reexports":[],"refs":[]}"#
        );
        assert!(matches!(
            serde_json::from_str::<AnyFragment>(&ts_json).unwrap(),
            AnyFragment::Ts(_)
        ));
        assert_eq!(
            serde_json::from_str::<AnyFragment>(&ts_json).unwrap(),
            ts,
            "and round-trips to the same value"
        );
    }

    // The four TS counts land AFTER `ctor-di`, in this order, and
    // only when the repo carries a TS fragment at all: a C#-only repo's stats
    // block keeps the exact bytes the assertion above pins.
    #[test]
    fn edges_by_kind_appends_the_four_ts_counts_after_ctor_di_when_present() {
        let s = EdgesByKind {
            inherits: 1,
            uses_type: 2,
            imports: 3,
            uses_member: 4,
            ctor_di: 5,
            import: Some(6),
            call: Some(7),
            jsx_use: Some(8),
            dispatch: Some(9),
        };
        let json = serde_json::to_string(&s).unwrap();
        assert_eq!(
            json,
            r#"{"inherits":1,"uses-type":2,"imports":3,"uses-member":4,"ctor-di":5,"import":6,"call":7,"jsx-use":8,"dispatch":9}"#
        );
    }

    // --- atomic writes: crash-sim -----------------------------------

    #[test]
    fn atomic_write_leaves_target_intact_when_only_a_stray_tmp_exists() {
        let dir = temp_dir("atomic-crash");
        let target = dir.join("graph.json");
        fs::write(&target, b"{\"old\":true}").unwrap();
        // Simulate a crashed prior write: a tmp file was created but the
        // process died before the rename -- the target must be completely
        // unaffected by the stray file's mere presence.
        fs::write(dir.join(".graph.json.tmp.99999.7"), b"GARBAGE-PARTIAL").unwrap();
        assert_eq!(fs::read_to_string(&target).unwrap(), "{\"old\":true}");
    }

    #[test]
    fn atomic_write_replaces_target_and_leaves_no_tmp_file_behind() {
        let dir = temp_dir("atomic-clean");
        let target = dir.join("graph.json");
        fs::write(&target, b"{\"old\":true}").unwrap();
        atomic_write_bytes(&target, b"{\"new\":true}").unwrap();
        assert_eq!(fs::read_to_string(&target).unwrap(), "{\"new\":true}");
        let leftover: Vec<_> = fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
            .collect();
        assert!(
            leftover.is_empty(),
            "no tmp file should remain: {leftover:?}"
        );
    }

    #[test]
    fn atomic_write_creates_parent_directories() {
        let dir = temp_dir("atomic-mkdir");
        let target = dir.join("nested").join("deeper").join("graph.json");
        atomic_write_bytes(&target, b"{}").unwrap();
        assert_eq!(fs::read_to_string(&target).unwrap(), "{}");
    }

    // --- rebuild_graph: unchanged path never touches the graph -----------

    #[test]
    fn rebuild_graph_skips_when_unchanged_and_graph_already_exists() {
        let dir = temp_dir("rebuild-unchanged");
        fs::create_dir_all(graph_dir(&dir)).unwrap();
        fs::write(graph_json_path(&dir), b"{\"schema_version\":2,\"built_at_head\":null,\"defs\":[],\"edges\":[],\"stats\":{\"def_count\":0,\"file_count\":0,\"edges_by_kind\":{\"inherits\":0,\"uses-type\":0,\"imports\":0,\"uses-member\":0},\"ambiguous_count\":0,\"ambiguous_pct\":0,\"unresolved_external_count\":0}}").unwrap();
        let outcome = rebuild_graph(&dir, &[], &HashMap::new(), false, None).unwrap();
        assert!(matches!(outcome, RebuildOutcome::NotRebuilt));
    }

    // The other half of that fast path: "nothing changed" is not enough on
    // its own. A graph.json written by a build that predates the current
    // schema is missing facts every reader now expects, so it is rebuilt
    // even though not one fragment moved -- the ONLY thing separating this
    // case from the one above is the version in its first bytes.
    #[test]
    fn rebuild_graph_rebuilds_when_the_existing_graph_carries_an_older_schema_version() {
        let dir = temp_dir("rebuild-old-schema");
        fs::create_dir_all(graph_dir(&dir)).unwrap();
        fs::write(graph_json_path(&dir), b"{\"schema_version\":1,\"built_at_head\":null,\"defs\":[],\"edges\":[],\"stats\":{\"def_count\":0,\"file_count\":0,\"edges_by_kind\":{\"inherits\":0,\"uses-type\":0,\"imports\":0,\"uses-member\":0},\"ambiguous_count\":0,\"ambiguous_pct\":0,\"unresolved_external_count\":0}}").unwrap();
        let outcome = rebuild_graph(&dir, &[], &HashMap::new(), false, None).unwrap();
        let RebuildOutcome::Rebuilt(graph) = outcome else {
            panic!("an older-schema graph must be rebuilt on the unchanged path");
        };
        assert_eq!(graph.schema_version, GRAPH_SCHEMA_VERSION);
        assert!(
            fs::read_to_string(graph_json_path(&dir))
                .unwrap()
                .starts_with(r#"{"schema_version":2,"#),
            "and the rebuilt artifact carries the current version on disk"
        );
    }

    // A truncated or unreadable artifact answers the same way an older one
    // does -- rebuild -- rather than being trusted or panicking.
    #[test]
    fn rebuild_graph_rebuilds_when_the_existing_graph_is_too_short_to_carry_a_version() {
        let dir = temp_dir("rebuild-truncated");
        fs::create_dir_all(graph_dir(&dir)).unwrap();
        fs::write(graph_json_path(&dir), b"{").unwrap();
        assert!(!graph_schema_is_current(&dir));
        assert!(matches!(
            rebuild_graph(&dir, &[], &HashMap::new(), false, None).unwrap(),
            RebuildOutcome::Rebuilt(_)
        ));
    }

    #[test]
    fn rebuild_graph_reuses_a_cached_fragment_at_matching_mtime() {
        let dir = temp_dir("rebuild-cache-hit");
        let fragment = Fragment {
            defs: vec![FragDef {
                id: "A".into(),
                name: "A".into(),
                namespace: "".into(),
                kind: "class".into(),
                line: 1,
                methods: vec![],
                properties: vec![],
                fields: vec![],
                method_returns: OrderedMap::new(),
                extension_methods: vec![],
                bases: vec![],
                type_params: vec![],
                base_generic_args: OrderedMap::new(),
                test_methods: vec![],
                property_types: OrderedMap::new(),
                field_types: OrderedMap::new(),
                method_return_args: OrderedMap::new(),
                non_public_methods: vec![],
                method_arities: OrderedMap::new(),
                method_params: OrderedMap::new(),
                end_line: 1,
            }],
            usings: vec![],
            refs: vec![],
            names: vec![],
        };
        // First build: nothing cached, comes from fresh_fragments.
        let mut fresh = HashMap::new();
        fresh.insert("A.cs".to_string(), AnyFragment::Cs(fragment.clone()));
        let graph_files = vec![GraphFile {
            rel: "A.cs".to_string(),
            mtime: 111,
        }];
        let first = rebuild_graph(&dir, &graph_files, &fresh, true, None).unwrap();
        assert!(matches!(first, RebuildOutcome::Rebuilt(_)));

        // Second build: same mtime, EMPTY fresh_fragments -- must reuse the
        // cache, not silently drop the file from the graph.
        let empty: HashMap<String, AnyFragment> = HashMap::new();
        let second = rebuild_graph(&dir, &graph_files, &empty, true, None).unwrap();
        match second {
            RebuildOutcome::Rebuilt(g) => {
                assert_eq!(g.defs.len(), 1, "cached fragment must still be used")
            }
            RebuildOutcome::NotRebuilt => panic!("changed=true must always rebuild"),
        }
    }

    // --- The v13 cache generation --------------------------

    #[test]
    fn rebuild_graph_writes_the_v13_caches_and_deletes_every_superseded_generation() {
        let dir = temp_dir("rebuild-v13");
        fs::create_dir_all(graph_dir(&dir)).unwrap();
        // The v9 pair joined this list when fragments gained def
        // `typeParams`/`baseGenericArgs` and the `ctor-param` ref kind, so a v9
        // fragment read back today carries none and every ctor-DI fact would be
        // missing from the graph. The v10 pair joined when a markup
        // fragment gained the `x:Class` def and its element/binding refs, so a
        // v10 markup fragment read back carries names only and every XAML
        // declaration and instantiation would be missing from the graph. The v11
        // pair joined when a `.ts/.tsx/.js/.jsx` file gained a reference
        // fragment where it previously had none at all, so a v11 cache read back
        // would leave every TS/JS rel looking like a file the worker never saw.
        // This side records no TS fragment yet, but the cache generation is
        // shared -- two writers putting two generations into one git dir would
        // have each delete the other's cache on every map. The v12 pair joined
        // when defs gained propertyTypes and refs
        // gained receiverPropertyOwner and the receiverCallOwner/
        // receiverCallMember pair, so a v12 fragment read back carries none and
        // every property hop and every var-from-invocation receiver would
        // silently stay unresolved.
        assert_eq!(SUPERSEDED_CACHE_FILES.len(), 34, "v1..v17 pairs");
        for stale in SUPERSEDED_CACHE_FILES {
            fs::write(graph_dir(&dir).join(stale), b"{}").unwrap();
        }

        let fragment = Fragment {
            defs: vec![FragDef {
                id: "App.A".into(),
                name: "A".into(),
                namespace: "App".into(),
                kind: "class".into(),
                line: 1,
                methods: vec![],
                properties: vec![],
                fields: vec![],
                method_returns: OrderedMap::new(),
                extension_methods: vec![],
                bases: vec![],
                type_params: vec![],
                base_generic_args: OrderedMap::new(),
                test_methods: vec![],
                property_types: OrderedMap::new(),
                field_types: OrderedMap::new(),
                method_return_args: OrderedMap::new(),
                non_public_methods: vec![],
                method_arities: OrderedMap::new(),
                method_params: OrderedMap::new(),
                end_line: 1,
            }],
            usings: vec![],
            refs: vec![],
            names: vec![],
        };
        let mut fresh = HashMap::new();
        fresh.insert("src/A.cs".to_string(), AnyFragment::Cs(fragment));
        let graph_files = vec![GraphFile {
            rel: "src/A.cs".to_string(),
            mtime: 222,
        }];
        rebuild_graph(&dir, &graph_files, &fresh, true, None).unwrap();

        assert!(
            graph_dir(&dir).join("fragments-v18.json").exists(),
            "the v18 payload cache is what gets written"
        );
        assert!(
            graph_dir(&dir).join("fragments-index-v18.json").exists(),
            "and its mtime-only index alongside it"
        );
        for stale in SUPERSEDED_CACHE_FILES {
            assert!(
                !graph_dir(&dir).join(stale).exists(),
                "{stale} must be deleted -- rename IS the invalidation"
            );
        }
    }

    // --- The v18 cache generation --------------------------

    #[test]
    fn fragments_cache_v18_supersedes_v17() {
        let dir = temp_dir("fragments-cache-v18-paths");
        assert_eq!(
            fragments_cache_path(&dir),
            graph_dir(&dir).join("fragments-v18.json")
        );
        assert_eq!(
            fragments_index_path(&dir),
            graph_dir(&dir).join("fragments-index-v18.json")
        );
        assert!(
            SUPERSEDED_CACHE_FILES.contains(&"fragments-v17.json"),
            "v17 joined the superseded list when the v18 bump landed"
        );
        assert!(
            SUPERSEDED_CACHE_FILES.contains(&"fragments-index-v17.json"),
            "its index pairs with it, same as every other generation"
        );

        let dir = temp_dir("rebuild-v18");
        fs::create_dir_all(graph_dir(&dir)).unwrap();
        fs::write(graph_dir(&dir).join("fragments-v17.json"), b"{}").unwrap();
        fs::write(graph_dir(&dir).join("fragments-index-v17.json"), b"{}").unwrap();

        let fragment = Fragment {
            defs: vec![],
            usings: vec![],
            refs: vec![],
            names: vec![],
        };
        let mut fresh = HashMap::new();
        fresh.insert("src/A.cs".to_string(), AnyFragment::Cs(fragment));
        let graph_files = vec![GraphFile {
            rel: "src/A.cs".to_string(),
            mtime: 1,
        }];
        rebuild_graph(&dir, &graph_files, &fresh, true, None).unwrap();

        assert!(graph_dir(&dir).join("fragments-v18.json").exists());
        assert!(graph_dir(&dir).join("fragments-index-v18.json").exists());
        assert!(
            !graph_dir(&dir).join("fragments-v17.json").exists(),
            "the v17 pair is deleted -- rename IS the invalidation"
        );
        assert!(!graph_dir(&dir).join("fragments-index-v16.json").exists());
    }

    // --- v8: FragRef's outerTypes, appended last -----------------------------

    #[test]
    fn frag_ref_outer_types_is_appended_last_after_receiver_args() {
        let r = FragRef {
            receiver_args: Some(vec!["FutureState".into()]),
            outer_types: vec!["Outer".into(), "Inner".into()],
            ..frag_ref(false, Some("Binder"), Some(1))
        };
        let json = serde_json::to_string(&r).unwrap();
        assert_eq!(
            json,
            r#"{"kind":"uses-member","name":"repo","member":"Save","line":7,"namespace":"App.Shape","receiverType":"Binder","argCount":1,"receiverArgs":["FutureState"],"outerTypes":["Outer","Inner"]}"#
        );
        let reparsed: FragRef = serde_json::from_str(&json).unwrap();
        assert_eq!(
            reparsed.outer_types,
            vec!["Outer".to_string(), "Inner".to_string()]
        );
    }

    // --- The two chain facts, appended after outerTypes ----

    #[test]
    fn frag_ref_property_owner_and_call_pair_are_appended_last_and_omitted_when_absent() {
        let hop = FragRef {
            qualified: Some("head.Dial".into()),
            name: "Dial".into(),
            receiver_property_owner: Some("Widget".into()),
            ..frag_ref(false, None, Some(0))
        };
        assert_eq!(
            serde_json::to_string(&hop).unwrap(),
            r#"{"kind":"uses-member","name":"Dial","qualified":"head.Dial","member":"Save","line":7,"namespace":"App.Shape","argCount":0,"receiverPropertyOwner":"Widget"}"#
        );

        let from_call = FragRef {
            receiver_call_owner: Some("Factory".into()),
            receiver_call_member: Some("Make".into()),
            ..frag_ref(false, None, Some(0))
        };
        assert_eq!(
            serde_json::to_string(&from_call).unwrap(),
            r#"{"kind":"uses-member","name":"repo","member":"Save","line":7,"namespace":"App.Shape","argCount":0,"receiverCallOwner":"Factory","receiverCallMember":"Make"}"#
        );

        // An older cached fragment carries neither key, and absent must
        // read back as "no chain fact" -- which is what leaves such a ref
        // exactly where it was before this generation.
        let plain = serde_json::to_string(&frag_ref(false, Some("Binder"), Some(1))).unwrap();
        assert!(
            !plain.contains("receiverPropertyOwner") && !plain.contains("receiverCall"),
            "{plain}"
        );
        let reparsed: FragRef = serde_json::from_str(&plain).unwrap();
        assert_eq!(reparsed.receiver_property_owner, None);
        assert_eq!(reparsed.receiver_call_owner, None);
        assert_eq!(reparsed.receiver_call_member, None);
    }

    #[test]
    fn frag_ref_an_empty_or_absent_outer_types_serializes_to_nothing_and_reads_back_empty() {
        let json = serde_json::to_string(&frag_ref(false, None, None)).unwrap();
        assert!(
            !json.contains("outerTypes"),
            "a namespace-level ref keeps its exact pre-v8 bytes: {json}"
        );
        // A pre-v8 cached fragment has no key at all, and absent must mean the
        // same thing as empty -- which is what keeps it off the nested step.
        let pre_v8: FragRef = serde_json::from_str(
            r#"{"kind":"uses-type","name":"Widget","line":3,"namespace":"App.Core"}"#,
        )
        .unwrap();
        assert!(pre_v8.outer_types.is_empty());
    }

    // --- v18: FragDef's methodParams and FragRef's receiverLambda -----------

    #[test]
    fn fragment_round_trip_keeps_method_params_and_receiver_lambda() {
        let mut method_params = OrderedMap::new();
        method_params.insert(
            "Register".to_string(),
            vec![
                vec!["Action<Options>".to_string()],
                vec!["string".to_string(), "Func<Options,bool>".to_string()],
            ],
        );
        let d = FragDef {
            method_params: method_params.clone(),
            ..frag_def(&[], &[], &[], &[], &[])
        };
        let d_json = serde_json::to_string(&d).unwrap();
        assert!(
            d_json.ends_with(
                r#""methodParams":{"Register":[["Action<Options>"],["string","Func<Options,bool>"]]}}"#
            ),
            "methodParams is appended last, after methodArities: {d_json}"
        );
        let d_reparsed: FragDef = serde_json::from_str(&d_json).unwrap();
        assert_eq!(d_reparsed.method_params, method_params);

        // Absent when empty, and an absent key deserializes back to empty --
        // the safe default for every fragment cached before this field
        // existed.
        let d_plain_json = serde_json::to_string(&frag_def(&[], &[], &[], &[], &[])).unwrap();
        assert!(!d_plain_json.contains("methodParams"), "{d_plain_json}");
        let d_plain_reparsed: FragDef = serde_json::from_str(&d_plain_json).unwrap();
        assert!(d_plain_reparsed.method_params.is_empty());

        let slot = FragLambdaSlot {
            owner: "Registrar".to_string(),
            member: "Register".to_string(),
            arg_count: 1,
            arg_index: 0,
            arity: 1,
            index: 0,
        };
        let r = FragRef {
            receiver_lambda: Some(slot.clone()),
            ..frag_ref(false, None, None)
        };
        let r_json = serde_json::to_string(&r).unwrap();
        assert!(
            r_json.ends_with(
                r#""receiverLambda":{"owner":"Registrar","member":"Register","argCount":1,"argIndex":0,"arity":1,"index":0}}"#
            ),
            "receiverLambda is appended last, after receiverLocal: {r_json}"
        );
        let r_reparsed: FragRef = serde_json::from_str(&r_json).unwrap();
        assert_eq!(r_reparsed.receiver_lambda, Some(slot));

        // Absent when `None`, and an absent key deserializes back to `None`.
        let r_plain_json = serde_json::to_string(&frag_ref(false, None, None)).unwrap();
        assert!(!r_plain_json.contains("receiverLambda"), "{r_plain_json}");
        let r_plain_reparsed: FragRef = serde_json::from_str(&r_plain_json).unwrap();
        assert_eq!(r_plain_reparsed.receiver_lambda, None);
    }
}