symforge 8.13.0

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini 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
/// LiveIndex persistence: serialize on shutdown, load on startup.
///
/// Uses postcard (compact binary) for fast round-trips.
/// Atomic write (tmp → rename) to prevent corruption on crash.
/// Background verification corrects stale entries after loading a snapshot.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};
use tracing::{info, warn};

use crate::domain::{FileClassification, LanguageId, ReferenceRecord, SymbolRecord};
use crate::live_index::store::{
    CircuitBreakerState, IndexLoadSource, IndexedFile, LiveIndex, ParseStatus, SnapshotVerifyState,
    normalize_root,
};
use crate::paths;

// ── Constants ─────────────────────────────────────────────────────────────────

use crate::domain::ParseDiagnostic;

const CURRENT_VERSION: u32 = 4;
const INDEX_FILENAME: &str = "index.bin";
const INDEX_TMP_FILENAME: &str = "index.bin.tmp";
pub const SNAPSHOT_RESET_SCOPE_LABEL: &str = ".symforge/index.bin,.symforge/index.bin.tmp";
pub const CHECKPOINT_INTERVAL_ENV: &str = "SYMFORGE_CHECKPOINT_INTERVAL_SECS";
pub const MIN_CHECKPOINT_INTERVAL_SECS: u64 = 30;
pub const MAX_CHECKPOINT_INTERVAL_SECS: u64 = 3600;
static SNAPSHOT_WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

// ── Snapshot types ────────────────────────────────────────────────────────────

/// Serializable snapshot of all per-file data in a `LiveIndex`.
///
/// Does NOT include non-serializable fields (Instant, AtomicUsize, RwLock).
/// Reverse index and trigram index are rebuilt from snapshot on load.
#[derive(Serialize, Deserialize)]
pub struct IndexSnapshot {
    pub version: u32,
    pub files: HashMap<String, IndexedFileSnapshot>,
}

/// Serializable snapshot of a single indexed file.
#[derive(Serialize, Deserialize, Clone)]
pub struct IndexedFileSnapshot {
    pub relative_path: String,
    pub language: LanguageId,
    pub classification: FileClassification,
    pub content: Vec<u8>,
    pub symbols: Vec<SymbolRecord>,
    pub parse_status: ParseStatus,
    pub parse_diagnostic: Option<ParseDiagnostic>,
    pub byte_len: u64,
    pub content_hash: String,
    pub references: Vec<ReferenceRecord>,
    pub alias_map: HashMap<String, String>,
    /// Seconds since UNIX epoch of the file's last modification time at index time.
    /// Used by `stat_check_files_from_view` for mtime comparison.
    pub mtime_secs: u64,
}

// ── Result type for stat checking ─────────────────────────────────────────────

/// Result of a stat-based freshness check of the loaded index.
pub struct StatCheckResult {
    /// Files whose on-disk mtime or size differs from the indexed values.
    pub changed: Vec<String>,
    /// Files in the index that no longer exist on disk.
    pub deleted: Vec<String>,
    /// Files on disk that are not in the index (new since snapshot was taken).
    pub new_files: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotResetReport {
    removed: Vec<PathBuf>,
    missing: Vec<PathBuf>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotWriteReport {
    pub path: PathBuf,
    pub bytes: usize,
    pub files: usize,
}

impl SnapshotResetReport {
    pub fn removed_count(&self) -> usize {
        self.removed.len()
    }

    pub fn missing_count(&self) -> usize {
        self.missing.len()
    }
}

// ── Public API ─────────────────────────────────────────────────────────────────

/// Serialize `index` to `index.bin` inside the project's data directory.
///
/// Uses an atomic write pattern (write to tmp, then rename) so a crash during
/// write never leaves a partially-written file.
///
/// Returns `Ok(())` on success. Non-fatal — caller logs and continues.
pub fn serialize_index(index: &LiveIndex, project_root: &Path) -> anyhow::Result<()> {
    let snapshot_input = capture_snapshot_build_input(index);
    serialize_captured_snapshot(snapshot_input, project_root).map(|_| ())
}

fn capture_snapshot_build_input(index: &LiveIndex) -> SnapshotBuildInput {
    SnapshotBuildInput {
        files: index.files.clone(),
    }
}

fn serialize_captured_snapshot(
    snapshot_input: SnapshotBuildInput,
    project_root: &Path,
) -> anyhow::Result<SnapshotWriteReport> {
    let snapshot = build_snapshot(snapshot_input, project_root);
    write_snapshot(snapshot, project_root)
}

pub fn serialize_shared_index(
    shared: &crate::live_index::store::SharedIndex,
    project_root: &Path,
) -> anyhow::Result<()> {
    checkpoint_shared_index(shared, project_root).map(|_| ())
}

pub fn checkpoint_shared_index(
    shared: &crate::live_index::store::SharedIndex,
    project_root: &Path,
) -> anyhow::Result<SnapshotWriteReport> {
    let snapshot_input = {
        let guard = shared.read();
        capture_snapshot_build_input(&guard)
    };
    serialize_captured_snapshot(snapshot_input, project_root)
}

pub fn checkpoint_interval_from_value(value: Option<&str>) -> Option<Duration> {
    let raw = value?.trim();
    if raw.is_empty()
        || raw == "0"
        || raw.eq_ignore_ascii_case("false")
        || raw.eq_ignore_ascii_case("off")
        || raw.eq_ignore_ascii_case("disabled")
    {
        return None;
    }

    let seconds = raw.parse::<u64>().ok()?;
    if seconds == 0 {
        return None;
    }

    Some(Duration::from_secs(seconds.clamp(
        MIN_CHECKPOINT_INTERVAL_SECS,
        MAX_CHECKPOINT_INTERVAL_SECS,
    )))
}

pub fn checkpoint_interval_from_env() -> Option<Duration> {
    checkpoint_interval_from_value(std::env::var(CHECKPOINT_INTERVAL_ENV).ok().as_deref())
}

pub fn reset_snapshot_state(project_root: &Path) -> anyhow::Result<SnapshotResetReport> {
    let dir = paths::resolve_symforge_dir(project_root);
    let targets = [dir.join(INDEX_FILENAME), dir.join(INDEX_TMP_FILENAME)];
    let mut removed = Vec::new();
    let mut missing = Vec::new();

    for target in targets {
        match std::fs::remove_file(&target) {
            Ok(()) => removed.push(target),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => missing.push(target),
            Err(error) => {
                return Err(anyhow::anyhow!(
                    "removing snapshot reset target {}: {}",
                    target.display(),
                    error
                ));
            }
        }
    }

    Ok(SnapshotResetReport { removed, missing })
}

// ── Team artifact (Program 015 S1a, C-S1A-005) — index.bin.zst export/import ──
//
// contracts/team-artifact.md (frozen 2026-06-30). Promoted in place from the
// SP-0B spike (former `spike_build_compressed` / `spike_compress_snapshot` /
// `spike_import_compressed` / `SpikeArtifactReport`, previously gated behind
// `cbm-spike` — see research.md § SP-0B): one implementation, no parallel
// spike-only path.
//
// R-14 (no secret leak): every function below only (de)serializes the
// snapshot already captured from `LiveIndex` — the same in-memory data
// `serialize_index` writes to `index.bin`. Nothing here re-walks the
// filesystem, so the artifact can never contain a path the discovery walk
// (`src/discovery/mod.rs`, `.gitignore` + hidden-file aware) had excluded.

/// Bare filename of the compressed team-artifact snapshot under `.symforge/`.
pub const ARTIFACT_FILENAME: &str = "index.bin.zst";
/// Bare filename of the artifact's sidecar metadata (content_hash etc.).
pub const ARTIFACT_METADATA_FILENAME: &str = "artifact.json";
const ARTIFACT_TMP_FILENAME: &str = "index.bin.zst.tmp";
/// Compression level for `checkpoint_now(export_artifact=true)` — the only
/// export path wired this sprint (contracts/team-artifact.md § Tiers, Best).
/// The Fast tier (level 3, watcher/periodic checkpoint) is part of the frozen
/// contract's tier vocabulary but has no caller yet — no sprint task wires a
/// background artifact export, so adding it now would be untested, unreachable
/// code. Add a `Fast` level constant + call site when that lands.
const ARTIFACT_BEST_ZSTD_LEVEL: i32 = 9;

/// Report of a completed team-artifact export ([`export_artifact`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArtifactExportReport {
    pub path: PathBuf,
    pub metadata_path: PathBuf,
    pub files: usize,
    pub raw_bytes: usize,
    pub compressed_bytes: usize,
    pub content_hash: String,
}

/// Per-file `content_hash` verification report for one in-memory zstd
/// export/import round trip (no disk I/O). Used by real-repo-scale regression
/// coverage (`tests/team_artifact_calibration.rs`) that must not touch a live
/// project's own `.symforge/` directory.
pub struct ArtifactRoundTripReport {
    pub files: usize,
    pub matched: usize,
    /// `"<path>: <before> != <after>"` (or `"<path>: missing"`) per failure.
    pub mismatches: Vec<String>,
    pub raw_bytes: usize,
    pub compressed_bytes: usize,
}

/// Build the snapshot, postcard-serialize, and zstd-compress it in memory.
/// Returns `(snapshot, raw_bytes, compressed_bytes)`.
fn build_compressed_snapshot(
    index: &LiveIndex,
    project_root: &Path,
) -> anyhow::Result<(IndexSnapshot, Vec<u8>, Vec<u8>)> {
    let snapshot = build_snapshot(capture_snapshot_build_input(index), project_root);
    let raw = postcard::to_stdvec(&snapshot)?;
    let compressed = zstd::encode_all(raw.as_slice(), ARTIFACT_BEST_ZSTD_LEVEL)?;
    Ok((snapshot, raw, compressed))
}

/// Compress the current snapshot to in-memory `index.bin.zst` bytes (no disk
/// I/O). Building block for [`export_artifact`] and round-trip regression
/// coverage.
pub fn compress_snapshot(index: &LiveIndex, project_root: &Path) -> anyhow::Result<Vec<u8>> {
    Ok(build_compressed_snapshot(index, project_root)?.2)
}

/// Decompress zstd-compressed artifact bytes to raw postcard bytes (no
/// postcard decode, no disk I/O). Kept separate from postcard decode because
/// the Import flow (contracts/team-artifact.md) verifies `content_hash`
/// against these raw bytes *before* deserializing.
pub fn decompress_artifact_bytes(compressed: &[u8]) -> anyhow::Result<Vec<u8>> {
    zstd::decode_all(compressed).map_err(|e| anyhow::anyhow!("zstd decode failed: {e}"))
}

/// Full in-memory round trip: build -> zstd compress -> decompress ->
/// deserialize, then verify every per-file `content_hash` survived
/// byte-exact. No disk I/O — safe to run against a live project's own index
/// (see `tests/team_artifact_calibration.rs`).
pub fn artifact_round_trip_report(
    index: &LiveIndex,
    project_root: &Path,
) -> anyhow::Result<ArtifactRoundTripReport> {
    let (before, raw, compressed) = build_compressed_snapshot(index, project_root)?;
    let decompressed = decompress_artifact_bytes(&compressed)?;
    let after: IndexSnapshot = postcard::from_bytes(&decompressed)?;

    let mut matched = 0usize;
    let mut mismatches = Vec::new();
    for (path, bf) in &before.files {
        match after.files.get(path) {
            Some(af) if af.content_hash == bf.content_hash => matched += 1,
            Some(af) => mismatches.push(format!(
                "{path}: {} != {}",
                bf.content_hash, af.content_hash
            )),
            None => mismatches.push(format!("{path}: missing after round-trip")),
        }
    }

    Ok(ArtifactRoundTripReport {
        files: before.files.len(),
        matched,
        mismatches,
        raw_bytes: raw.len(),
        compressed_bytes: compressed.len(),
    })
}

/// Export the current index as the Best-tier `.symforge/index.bin.zst` team
/// artifact plus its `artifact.json` sidecar, and ensure the `.gitattributes`
/// `*.zst merge=ours` hint (A-US2-04) exists at `project_root`. Atomic write
/// (tmp -> rename), mirroring [`write_snapshot`].
pub fn export_artifact(
    index: &LiveIndex,
    project_root: &Path,
) -> anyhow::Result<ArtifactExportReport> {
    let (snapshot, raw, compressed) = build_compressed_snapshot(index, project_root)?;
    let file_count = snapshot.files.len();
    let content_hash = crate::hash::digest_hex(&raw);

    let dir = paths::ensure_symforge_dir(project_root)?;
    let final_path = dir.join(ARTIFACT_FILENAME);
    let tmp_path = dir.join(ARTIFACT_TMP_FILENAME);
    std::fs::write(&tmp_path, &compressed).map_err(|e| {
        anyhow::anyhow!("writing team artifact tmp at {}: {}", tmp_path.display(), e)
    })?;
    std::fs::rename(&tmp_path, &final_path).map_err(|e| {
        anyhow::anyhow!(
            "renaming team artifact {} -> {}: {}",
            tmp_path.display(),
            final_path.display(),
            e
        )
    })?;

    let metadata_path = dir.join(ARTIFACT_METADATA_FILENAME);
    let metadata = serde_json::json!({
        "content_hash": content_hash,
        "raw_bytes": raw.len(),
        "compressed_bytes": compressed.len(),
        "files": file_count,
    });
    std::fs::write(&metadata_path, serde_json::to_vec_pretty(&metadata)?).map_err(|e| {
        anyhow::anyhow!(
            "writing team artifact metadata at {}: {}",
            metadata_path.display(),
            e
        )
    })?;

    ensure_gitattributes_merge_hint(project_root)?;

    info!(
        bytes = compressed.len(),
        files = file_count,
        path = %final_path.display(),
        "team artifact exported"
    );

    Ok(ArtifactExportReport {
        path: final_path,
        metadata_path,
        files: file_count,
        raw_bytes: raw.len(),
        compressed_bytes: compressed.len(),
        content_hash,
    })
}

/// Ensure `project_root/.gitattributes` carries the `*.zst merge=ours` hint
/// (contracts/team-artifact.md § Paths) so merging the shared artifact always
/// keeps the current branch's copy instead of a line-diff conflict on binary
/// content. Idempotent: appends only if the line is not already present;
/// preserves any existing file content byte-for-byte otherwise.
fn ensure_gitattributes_merge_hint(project_root: &Path) -> anyhow::Result<()> {
    const HINT_LINE: &str = "*.zst merge=ours";
    let path = project_root.join(".gitattributes");
    let existing = std::fs::read_to_string(&path).unwrap_or_default();
    if existing.lines().any(|line| line.trim() == HINT_LINE) {
        return Ok(());
    }
    let mut updated = existing;
    if !updated.is_empty() && !updated.ends_with('\n') {
        updated.push('\n');
    }
    updated.push_str(HINT_LINE);
    updated.push('\n');
    std::fs::write(&path, updated)
        .map_err(|e| anyhow::anyhow!("writing .gitattributes at {}: {}", path.display(), e))?;
    Ok(())
}

/// Read the `content_hash` field out of an `artifact.json` sidecar, if it
/// parses. Returns `None` when the sidecar is missing, is invalid JSON, or
/// lacks the field. Per contracts/team-artifact.md § Integrity failure, the
/// caller ([`import_artifact`]) treats `None` as an integrity failure: the
/// artifact's `content_hash` cannot be verified, so it is quarantined and the
/// daemon falls back to a full index build rather than trusting an
/// unverifiable payload.
fn read_artifact_content_hash(metadata_path: &Path) -> Option<String> {
    let bytes = std::fs::read(metadata_path).ok()?;
    let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
    value.get("content_hash")?.as_str().map(str::to_string)
}

/// Import the team artifact (`.symforge/index.bin.zst`) per
/// contracts/team-artifact.md § Import flow: decompress, verify
/// `content_hash` against the `artifact.json` sidecar, then deserialize. The
/// returned snapshot rehydrates via the same `snapshot_to_live_index` +
/// stat-check path an `index.bin` load already uses (see `load_snapshot`).
///
/// Any integrity failure (corrupt zstd frame, hash mismatch, corrupt
/// postcard, version mismatch) quarantines the artifact under
/// `.symforge/quarantine/artifacts/` and returns `None`, so the caller falls
/// back to a full cold re-index (contract § Integrity failure).
fn import_artifact(project_root: &Path) -> Option<IndexSnapshot> {
    let dir = paths::resolve_symforge_dir(project_root);
    let artifact_path = dir.join(ARTIFACT_FILENAME);
    let metadata_path = dir.join(ARTIFACT_METADATA_FILENAME);

    let compressed = std::fs::read(&artifact_path).ok()?;

    let raw = match decompress_artifact_bytes(&compressed) {
        Ok(raw) => raw,
        Err(e) => {
            warn!("failed to decompress team artifact (corrupt zst?): {e}");
            try_quarantine_bad_artifact(
                project_root,
                &artifact_path,
                &metadata_path,
                &compressed,
                "zstd-decode-error",
                e.to_string(),
            );
            return None;
        }
    };

    // contracts/team-artifact.md § Import flow requires "verify content_hash"
    // BEFORE loading. A missing/unparseable sidecar means the hash cannot be
    // verified — reachable when a crash (or partial checkout) lands between
    // `export_artifact`'s artifact rename and its separate, non-atomic sidecar
    // write. Do NOT silently trust an unverifiable payload: treat it as an
    // integrity failure (§ Integrity failure), quarantine, and fall back to a
    // full index build.
    let Some(expected_hash) = read_artifact_content_hash(&metadata_path) else {
        warn!(
            path = %artifact_path.display(),
            metadata_path = %metadata_path.display(),
            "team artifact sidecar missing or unparseable — content_hash unverifiable; quarantining and falling back to a full index build"
        );
        try_quarantine_bad_artifact(
            project_root,
            &artifact_path,
            &metadata_path,
            &compressed,
            "missing-sidecar",
            format!(
                "artifact.json missing or unparseable at {}",
                metadata_path.display()
            ),
        );
        return None;
    };

    let actual_hash = crate::hash::digest_hex(&raw);
    if actual_hash != expected_hash {
        warn!(
            "team artifact content_hash mismatch (expected {expected_hash}, got {actual_hash}) — quarantining"
        );
        try_quarantine_bad_artifact(
            project_root,
            &artifact_path,
            &metadata_path,
            &compressed,
            "content-hash-mismatch",
            format!("expected {expected_hash}, got {actual_hash}"),
        );
        return None;
    }

    match postcard::from_bytes::<IndexSnapshot>(&raw) {
        Ok(snapshot) if snapshot.version == CURRENT_VERSION => Some(snapshot),
        Ok(snapshot) => {
            warn!(
                "team artifact snapshot version mismatch: got {}, expected {} — will cold re-index",
                snapshot.version, CURRENT_VERSION
            );
            try_quarantine_bad_artifact(
                project_root,
                &artifact_path,
                &metadata_path,
                &compressed,
                "version-mismatch",
                format!(
                    "snapshot version {}, expected {}",
                    snapshot.version, CURRENT_VERSION
                ),
            );
            None
        }
        Err(e) => {
            warn!("failed to deserialize team artifact (corrupt postcard?): {e}");
            try_quarantine_bad_artifact(
                project_root,
                &artifact_path,
                &metadata_path,
                &compressed,
                "postcard-decode-error",
                e.to_string(),
            );
            None
        }
    }
}

fn quarantine_bad_artifact(
    project_root: &Path,
    artifact_path: &Path,
    metadata_path: &Path,
    compressed_bytes: &[u8],
    reason: &str,
    detail: String,
) -> anyhow::Result<PathBuf> {
    let dir = paths::ensure_artifact_quarantine_dir(project_root)?;
    let hash = crate::hash::digest_hex(compressed_bytes);
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    let name = format!(
        "{}-{:09}-{}-{}",
        now.as_secs(),
        now.subsec_nanos(),
        &hash[..16],
        reason
    );
    let quarantine_path = dir.join(format!("{name}.zst"));
    let metadata_out_path = dir.join(format!("{name}.json"));

    std::fs::write(&quarantine_path, compressed_bytes).map_err(|e| {
        anyhow::anyhow!(
            "writing quarantined team artifact at {}: {}",
            quarantine_path.display(),
            e
        )
    })?;

    let quarantine_metadata = serde_json::json!({
        "source_path": artifact_path.to_string_lossy(),
        "quarantine_path": quarantine_path.to_string_lossy(),
        "reason": reason,
        "detail": detail,
        "sha256": hash,
        "bytes": compressed_bytes.len(),
        "quarantined_at_unix_seconds": now.as_secs(),
        "quarantined_at_unix_nanos": now.subsec_nanos(),
    });
    let metadata_bytes = serde_json::to_vec_pretty(&quarantine_metadata)?;
    std::fs::write(&metadata_out_path, metadata_bytes).map_err(|e| {
        anyhow::anyhow!(
            "writing team artifact quarantine metadata at {}: {}",
            metadata_out_path.display(),
            e
        )
    })?;

    // Remove the bad artifact (+ its sidecar) so a later cold start does not
    // retry the same corrupt artifact forever.
    match std::fs::remove_file(artifact_path) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => warn!(
            path = %artifact_path.display(),
            "failed to remove bad team artifact after quarantine: {error}"
        ),
    }
    let _ = std::fs::remove_file(metadata_path);

    Ok(quarantine_path)
}

fn try_quarantine_bad_artifact(
    project_root: &Path,
    artifact_path: &Path,
    metadata_path: &Path,
    compressed_bytes: &[u8],
    reason: &str,
    detail: String,
) {
    match quarantine_bad_artifact(
        project_root,
        artifact_path,
        metadata_path,
        compressed_bytes,
        reason,
        detail,
    ) {
        Ok(quarantine_path) => warn!(
            path = %artifact_path.display(),
            quarantine_path = %quarantine_path.display(),
            reason = reason,
            "bad team artifact quarantined"
        ),
        Err(error) => warn!(
            path = %artifact_path.display(),
            reason = reason,
            "failed to quarantine bad team artifact: {error}"
        ),
    }
}

fn write_snapshot(
    snapshot: IndexSnapshot,
    project_root: &Path,
) -> anyhow::Result<SnapshotWriteReport> {
    // Serialize with postcard
    let bytes = postcard::to_stdvec(&snapshot)?;
    let file_count = snapshot.files.len();

    let _write_guard = SNAPSHOT_WRITE_LOCK
        .lock()
        .map_err(|_| anyhow::anyhow!("snapshot write lock poisoned"))?;
    let dir = paths::ensure_symforge_dir(project_root)?;

    // Atomic write: tmp file then rename
    let final_path = dir.join(INDEX_FILENAME);
    let tmp_path = dir.join(INDEX_TMP_FILENAME);

    std::fs::write(&tmp_path, &bytes).map_err(|e| {
        anyhow::anyhow!(
            "writing index snapshot tmp at {}: {}",
            tmp_path.display(),
            e
        )
    })?;
    std::fs::rename(&tmp_path, &final_path).map_err(|e| {
        anyhow::anyhow!(
            "renaming index snapshot {} -> {}: {}",
            tmp_path.display(),
            final_path.display(),
            e
        )
    })?;

    info!(
        bytes = bytes.len(),
        files = file_count,
        path = %final_path.display(),
        "index serialized to project data dir"
    );

    Ok(SnapshotWriteReport {
        path: final_path,
        bytes: bytes.len(),
        files: file_count,
    })
}

fn quarantine_bad_snapshot(
    project_root: &Path,
    snapshot_path: &Path,
    bytes: &[u8],
    reason: &str,
    detail: String,
) -> anyhow::Result<PathBuf> {
    let dir = paths::ensure_index_snapshot_quarantine_dir(project_root)?;
    let hash = crate::hash::digest_hex(bytes);
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    let name = format!(
        "{}-{:09}-{}-{}",
        now.as_secs(),
        now.subsec_nanos(),
        &hash[..16],
        reason
    );
    let quarantine_path = dir.join(format!("{name}.bin"));
    let metadata_path = dir.join(format!("{name}.json"));

    std::fs::write(&quarantine_path, bytes).map_err(|e| {
        anyhow::anyhow!(
            "writing quarantined index snapshot at {}: {}",
            quarantine_path.display(),
            e
        )
    })?;

    let metadata = serde_json::json!({
        "source_path": snapshot_path.to_string_lossy(),
        "quarantine_path": quarantine_path.to_string_lossy(),
        "reason": reason,
        "detail": detail,
        "sha256": hash,
        "bytes": bytes.len(),
        "quarantined_at_unix_seconds": now.as_secs(),
        "quarantined_at_unix_nanos": now.subsec_nanos(),
    });
    let metadata_bytes = serde_json::to_vec_pretty(&metadata)?;
    std::fs::write(&metadata_path, metadata_bytes).map_err(|e| {
        anyhow::anyhow!(
            "writing index snapshot quarantine metadata at {}: {}",
            metadata_path.display(),
            e
        )
    })?;

    match std::fs::remove_file(snapshot_path) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => warn!(
            path = %snapshot_path.display(),
            quarantine_path = %quarantine_path.display(),
            "failed to remove active bad index snapshot after quarantine: {error}"
        ),
    }

    Ok(quarantine_path)
}

fn try_quarantine_bad_snapshot(
    project_root: &Path,
    snapshot_path: &Path,
    bytes: &[u8],
    reason: &str,
    detail: String,
) {
    match quarantine_bad_snapshot(project_root, snapshot_path, bytes, reason, detail) {
        Ok(quarantine_path) => warn!(
            path = %snapshot_path.display(),
            quarantine_path = %quarantine_path.display(),
            reason = reason,
            "bad index snapshot quarantined"
        ),
        Err(error) => warn!(
            path = %snapshot_path.display(),
            reason = reason,
            "failed to quarantine bad index snapshot: {error}"
        ),
    }
}

/// Load an `IndexSnapshot` from the project's data directory.
///
/// Returns `None` (not panic) on:
/// - file not found (first run or crash)
/// - version mismatch (schema upgrade)
/// - corrupt / truncated bytes
pub fn load_snapshot(project_root: &Path) -> Option<IndexSnapshot> {
    let path = paths::resolve_symforge_dir(project_root).join(INDEX_FILENAME);

    let bytes = match std::fs::read(&path) {
        Ok(b) => b,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            // contracts/team-artifact.md § Import flow: index.bin missing but a
            // team-shared index.bin.zst artifact may be present — import it
            // instead of dropping straight to a full cold re-index. Absent
            // artifact too (the common first-run case) falls through to `None`.
            return import_artifact(project_root);
        }
        Err(_) => {
            // Any other read failure (permissions, etc.) is the pre-existing
            // "give up, caller re-indexes" behavior.
            return None;
        }
    };

    let snapshot: IndexSnapshot = match postcard::from_bytes(&bytes) {
        Ok(s) => s,
        Err(e) => {
            warn!("failed to deserialize index snapshot (corrupt?): {e}");
            try_quarantine_bad_snapshot(
                project_root,
                &path,
                &bytes,
                "deserialize-error",
                e.to_string(),
            );
            return None;
        }
    };

    if snapshot.version != CURRENT_VERSION {
        warn!(
            "index snapshot version mismatch: got {}, expected {} — will re-index",
            snapshot.version, CURRENT_VERSION
        );
        try_quarantine_bad_snapshot(
            project_root,
            &path,
            &bytes,
            "version-mismatch",
            format!(
                "snapshot version {}, expected {}",
                snapshot.version, CURRENT_VERSION
            ),
        );
        return None;
    }

    Some(snapshot)
}

/// Rehydrate a `LiveIndex` from a persisted snapshot.
///
/// `project_root` is the filesystem root the snapshot was taken from; it is
/// recorded as the index's normalized `indexed_root` so a later project switch
/// triggers a root-mismatch reload (see `SymForgeServer::ensure_local_index`).
/// The snapshot wire format itself does not carry the root, so the caller
/// supplies it — the same root passed to [`load_snapshot`].
pub fn snapshot_to_live_index(snapshot: IndexSnapshot, project_root: &Path) -> LiveIndex {
    let mut files: HashMap<String, Arc<IndexedFile>> = HashMap::with_capacity(snapshot.files.len());

    for (path, snap_file) in snapshot.files {
        let indexed_file = IndexedFile {
            relative_path: snap_file.relative_path,
            language: snap_file.language,
            classification: snap_file.classification,
            content: snap_file.content,
            symbols: snap_file.symbols,
            parse_status: snap_file.parse_status,
            parse_diagnostic: snap_file.parse_diagnostic,
            byte_len: snap_file.byte_len,
            content_hash: snap_file.content_hash,
            references: snap_file.references,
            alias_map: snap_file.alias_map,
            mtime_secs: snap_file.mtime_secs,
        };
        files.insert(path, Arc::new(indexed_file));
    }

    let trigram_index = super::trigram::TrigramIndex::build_from_files(&files);

    let mut index = LiveIndex {
        files,
        loaded_at: Instant::now(),
        loaded_at_system: SystemTime::now(),
        load_duration: Duration::ZERO,
        cb_state: CircuitBreakerState::new(0.20),
        is_empty: false,
        load_source: IndexLoadSource::SnapshotRestore,
        snapshot_verify_state: SnapshotVerifyState::Pending,
        reverse_index: HashMap::new(),
        files_by_basename: HashMap::new(),
        files_by_dir_component: HashMap::new(),
        trigram_index,
        gitignore: None,
        skipped_files: Vec::new(),
        coupling_store: None,
        local_empty_reason: Arc::new(parking_lot::RwLock::new(None)),
        // A snapshot-restored index serves a real project; record its root so a
        // project switch invalidates it the same way a freshly loaded one does.
        indexed_root: Some(normalize_root(project_root)),
    };
    index.rebuild_reverse_index();
    index.rebuild_path_indices();
    index
}

/// Stat-check all files in the index against disk to find changed/deleted/new files.
///
/// Compares `byte_len` and `mtime_secs` stored in the snapshot against current
/// filesystem metadata. Files with differing size or mtime are in `changed`.
/// Files with `ENOENT` go to `deleted`. Files on disk not in the index go to `new_files`.
fn stat_check_files_from_view(
    verify_view: &VerifyIndexView,
    snapshot_mtimes: &HashMap<String, u64>,
    root: &Path,
) -> StatCheckResult {
    let known_paths: std::collections::HashSet<&str> = verify_view
        .files
        .iter()
        .map(|file| file.relative_path.as_str())
        .collect();
    let mut changed = Vec::new();
    let mut deleted = Vec::new();

    // Check each indexed file against disk
    for file in &verify_view.files {
        let abs_path = root.join(
            file.relative_path
                .replace('/', std::path::MAIN_SEPARATOR_STR),
        );
        match std::fs::metadata(&abs_path) {
            Ok(meta) => {
                let on_disk_size = meta.len();
                let on_disk_mtime = meta
                    .modified()
                    .ok()
                    .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
                    .map(|d| d.as_secs())
                    .unwrap_or(0);

                let stored_mtime = snapshot_mtimes
                    .get(&file.relative_path)
                    .copied()
                    .unwrap_or(0);

                if on_disk_size != file.byte_len || on_disk_mtime != stored_mtime {
                    changed.push(file.relative_path.clone());
                }
            }
            Err(_) => {
                // File gone
                deleted.push(file.relative_path.clone());
            }
        }
    }

    // Find new files (on disk but not in index)
    let new_files = match crate::discovery::discover_files(root) {
        Ok(discovered) => discovered
            .into_iter()
            .filter(|df| !known_paths.contains(df.relative_path.as_str()))
            .map(|df| df.relative_path)
            .collect(),
        Err(e) => {
            warn!("stat_check_files: discover_files failed: {e}");
            Vec::new()
        }
    };

    StatCheckResult {
        changed,
        deleted,
        new_files,
    }
}

/// Select approximately `sample_pct` of files and check their content hashes.
///
/// Returns paths of files whose on-disk content hash differs from the index.
/// Default: 10% (pass 0.10).
fn spot_verify_sample_from_view(
    verify_view: &VerifyIndexView,
    root: &Path,
    sample_pct: f64,
) -> Vec<String> {
    if verify_view.files.is_empty() {
        return Vec::new();
    }

    // Deterministic pseudo-random sample: every Nth file
    let total = verify_view.files.len();
    let sample_size = ((total as f64 * sample_pct).ceil() as usize)
        .max(1)
        .min(total);
    let step = total.checked_div(sample_size).unwrap_or(1);
    let step = step.max(1);

    let mut mismatches = Vec::new();

    for file in verify_view.files.iter().step_by(step) {
        let abs_path = root.join(
            file.relative_path
                .replace('/', std::path::MAIN_SEPARATOR_STR),
        );
        let bytes = match std::fs::read(&abs_path) {
            Ok(b) => b,
            Err(_) => continue,
        };

        let on_disk_hash = crate::hash::digest_hex(&bytes);
        if on_disk_hash != file.content_hash {
            mismatches.push(file.relative_path.clone());
        }
    }

    mismatches
}

// ── FrecencyStore init hook ───────────────────────────────────────────────────

/// Open the per-workspace `FrecencyStore` and apply the graduated HEAD-change
/// reset policy at session startup.
///
/// Startup persistence is gated on the persistent collection policy. With
/// `SYMFORGE_FRECENCY` unset (the default session policy), this is a no-op and
/// the database is never touched at boot.
///
/// With persistent collection enabled:
///
/// 1. Open the SQLite store at `<project_root>/.symforge/frecency.db`,
///    creating the file and parent directory if missing.
/// 2. Look up the stored HEAD SHA from the previous session.
/// 3. Resolve the current HEAD via `git2`. If the project is not a git
///    repository (or git otherwise fails), silently no-op — the feature must
///    not break the tool it hooks into.
/// 4. Compute the commit distance between stored and current HEAD. A transient
///    `Err` here aborts the cycle and preserves the stored HEAD so the next
///    session retries; `Ok(None)` signals "unrelated history / branch change"
///    which the policy correctly maps to a zero reset.
/// 5. Apply the graduated policy via [`FrecencyStore::reset_or_halve_on_head_change`],
///    which also persists `current_head` as the new stored HEAD.
///
/// Any error along the happy path is silently dropped: a bad store, a git read
/// failure, or a SQLite transaction failure must never crash the live-index
/// boot path. The next session retries.
///
/// Spec: §"Reset-on-HEAD-change: graduated, not binary" on
/// `[[SymForge Frecency-Weighted File Ranking]]`.
pub fn init_frecency_store(project_root: &Path) {
    // Hook registration is unconditional — the hook body resolves collection
    // policy at call time, so a test that flips `SYMFORGE_FRECENCY` after boot
    // still sees edits follow the current policy.
    crate::live_index::frecency::ensure_bump_hook_registered();
    if crate::live_index::frecency::collection_policy_from_env()
        != crate::capability::FrecencyCollectionPolicy::Persistent
    {
        return;
    }
    let db_path = crate::live_index::frecency::frecency_db_path(project_root);
    let _ = run_frecency_init(&db_path, project_root);
}

/// Body of [`init_frecency_store`] with the env-flag check stripped out.
///
/// Split so unit tests can drive the work against a known db path + git repo
/// without process-wide env mutation.
fn run_frecency_init(db_path: &Path, repo_root: &Path) -> Result<(), String> {
    let store =
        crate::live_index::frecency::FrecencyStore::open(db_path).map_err(|e| e.to_string())?;
    store.apply_head_reset_policy(repo_root)
}

// ── Private helpers ───────────────────────────────────────────────────────────

#[derive(Clone)]
pub(crate) struct SnapshotBuildInput {
    files: HashMap<String, Arc<IndexedFile>>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct VerifyFileView {
    relative_path: String,
    byte_len: u64,
    content_hash: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct VerifyIndexView {
    files: Vec<VerifyFileView>,
}

fn capture_verify_view(index: &LiveIndex) -> VerifyIndexView {
    let mut files: Vec<VerifyFileView> = index
        .files
        .iter()
        .map(|(path, file)| VerifyFileView {
            relative_path: path.clone(),
            byte_len: file.byte_len,
            content_hash: file.content_hash.clone(),
        })
        .collect();
    files.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
    VerifyIndexView { files }
}

/// Convert captured live-index data to `IndexSnapshot`.
fn build_snapshot(snapshot_input: SnapshotBuildInput, project_root: &Path) -> IndexSnapshot {
    let mut snap_files = HashMap::with_capacity(snapshot_input.files.len());

    for (path, file) in snapshot_input.files {
        // Try to get mtime from disk for the snapshot
        let abs_path = project_root.join(path.replace('/', std::path::MAIN_SEPARATOR_STR));
        let mtime_secs = std::fs::metadata(&abs_path)
            .ok()
            .and_then(|m| m.modified().ok())
            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
            .map(|d| d.as_secs())
            .unwrap_or(0);

        snap_files.insert(
            path.clone(),
            IndexedFileSnapshot {
                relative_path: file.relative_path.clone(),
                language: file.language.clone(),
                classification: file.classification,
                content: file.content.clone(),
                symbols: file.symbols.clone(),
                parse_status: file.parse_status.clone(),
                parse_diagnostic: file.parse_diagnostic.clone(),
                byte_len: file.byte_len,
                content_hash: file.content_hash.clone(),
                references: file.references.clone(),
                alias_map: file.alias_map.clone(),
                mtime_secs,
            },
        );
    }

    IndexSnapshot {
        version: CURRENT_VERSION,
        files: snap_files,
    }
}

/// Background task: verify a loaded index against disk and re-parse stale files.
///
/// Run after `snapshot_to_live_index` to bring the index to current disk state.
/// Non-blocking for queries — writes are protected by the index's RwLock.
pub async fn background_verify(
    index: crate::live_index::store::SharedIndex,
    root: std::path::PathBuf,
    snapshot_mtimes: HashMap<String, u64>,
) {
    index.mark_snapshot_verify_running();

    // 1. Stat-check all files (fast: just metadata reads)
    let verify_view = {
        let guard = index.read();
        capture_verify_view(&guard)
    };
    let stat_result = stat_check_files_from_view(&verify_view, &snapshot_mtimes, &root);

    let changed_count = stat_result.changed.len();
    let deleted_count = stat_result.deleted.len();
    let new_count = stat_result.new_files.len();

    // 2. Remove deleted files
    if !stat_result.deleted.is_empty() {
        for path in &stat_result.deleted {
            index.remove_file(path);
        }
    }

    // 3. Re-parse changed files
    let to_reparse: Vec<String> = stat_result
        .changed
        .into_iter()
        .chain(stat_result.new_files)
        .collect();

    for rel_path in &to_reparse {
        let abs_path = root.join(rel_path.replace('/', std::path::MAIN_SEPARATOR_STR));
        let bytes = match std::fs::read(&abs_path) {
            Ok(b) => b,
            Err(e) => {
                warn!("background_verify: failed to read {rel_path}: {e}");
                continue;
            }
        };

        // Detect language from path
        let ext = std::path::Path::new(rel_path)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");
        let language = match crate::domain::LanguageId::from_extension(ext) {
            Some(lang) => lang,
            None => continue,
        };

        let result = crate::parsing::process_file_with_classification(
            rel_path,
            &bytes,
            language,
            FileClassification::for_code_path(rel_path),
        );
        let mtime_secs = std::fs::metadata(&abs_path)
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let indexed_file = IndexedFile::from_parse_result(result, bytes).with_mtime(mtime_secs);

        index.update_file(rel_path.clone(), indexed_file);
    }

    // 4. Spot-verify sample (10%) for content hash mismatches
    let verify_view = {
        let guard = index.read();
        capture_verify_view(&guard)
    };
    let spot_mismatches = spot_verify_sample_from_view(&verify_view, &root, 0.10);

    let spot_count = spot_mismatches.len();

    // Re-parse spot-check mismatches
    for rel_path in &spot_mismatches {
        let abs_path = root.join(rel_path.replace('/', std::path::MAIN_SEPARATOR_STR));
        let bytes = match std::fs::read(&abs_path) {
            Ok(b) => b,
            Err(e) => {
                warn!("background_verify spot-check: failed to read {rel_path}: {e}");
                continue;
            }
        };

        let ext = std::path::Path::new(rel_path)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");
        let language = match crate::domain::LanguageId::from_extension(ext) {
            Some(lang) => lang,
            None => continue,
        };

        let result = crate::parsing::process_file_with_classification(
            rel_path,
            &bytes,
            language,
            FileClassification::for_code_path(rel_path),
        );
        let mtime_secs = std::fs::metadata(&abs_path)
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let indexed_file = IndexedFile::from_parse_result(result, bytes).with_mtime(mtime_secs);

        index.update_file(rel_path.clone(), indexed_file);
    }

    index.mark_snapshot_verify_completed(spot_mismatches);

    info!(
        "background verify complete: {} changed, {} deleted, {} new, {} spot-check mismatches",
        changed_count, deleted_count, new_count, spot_count
    );
}

// ── Unit tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{LanguageId, ReferenceKind, ReferenceRecord, SymbolKind, SymbolRecord};
    use crate::live_index::store::{
        IndexLoadSource, IndexedFile, ParseStatus, SnapshotVerifyState,
    };
    use std::collections::HashMap;
    use std::sync::Arc;
    use std::time::{Duration, Instant, SystemTime};
    use tempfile::TempDir;

    mod git_test_helpers {
        include!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/src/git/test_helpers.rs"
        ));
    }

    // ── Helpers ───────────────────────────────────────────────────────────────

    fn make_symbol(name: &str) -> SymbolRecord {
        let byte_range = (0, 10);
        SymbolRecord {
            name: name.to_string(),
            kind: SymbolKind::Function,
            depth: 0,
            sort_order: 0,
            byte_range,
            item_byte_range: Some(byte_range),
            line_range: (0, 1),
            doc_byte_range: None,
        }
    }

    fn make_reference(name: &str) -> ReferenceRecord {
        ReferenceRecord {
            name: name.to_string(),
            qualified_name: None,
            kind: ReferenceKind::Call,
            byte_range: (5, 10),
            line_range: (0, 0),
            enclosing_symbol_index: None,
        }
    }

    fn make_indexed_file(path: &str, content: &[u8]) -> IndexedFile {
        let mut alias_map = HashMap::new();
        alias_map.insert("Alias".to_string(), "Original".to_string());
        IndexedFile {
            relative_path: path.to_string(),
            language: LanguageId::Rust,
            classification: crate::domain::FileClassification::for_code_path(path),
            content: content.to_vec(),
            symbols: vec![make_symbol("my_func")],
            parse_status: ParseStatus::Parsed,
            parse_diagnostic: None,
            byte_len: content.len() as u64,
            content_hash: crate::hash::digest_hex(content),
            references: vec![make_reference("other_func")],
            alias_map,
            mtime_secs: 0,
        }
    }

    fn make_live_index_with_files(files: Vec<(&str, &[u8])>) -> LiveIndex {
        let mut file_map: HashMap<String, Arc<IndexedFile>> = HashMap::new();
        for (path, content) in files {
            file_map.insert(path.to_string(), Arc::new(make_indexed_file(path, content)));
        }
        let trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&file_map);
        let mut index = LiveIndex {
            files: file_map,
            loaded_at: Instant::now(),
            loaded_at_system: SystemTime::now(),
            load_duration: Duration::ZERO,
            cb_state: CircuitBreakerState::new(0.20),
            is_empty: false,
            load_source: IndexLoadSource::FreshLoad,
            snapshot_verify_state: SnapshotVerifyState::NotNeeded,
            reverse_index: HashMap::new(),
            files_by_basename: HashMap::new(),
            files_by_dir_component: HashMap::new(),
            trigram_index,
            gitignore: None,
            skipped_files: Vec::new(),
            coupling_store: None,
            local_empty_reason: Arc::new(parking_lot::RwLock::new(None)),
            indexed_root: None,
        };
        index.rebuild_reverse_index();
        index.rebuild_path_indices();
        index
    }

    // ── Round-trip tests ──────────────────────────────────────────────────────

    #[test]
    fn test_round_trip_preserves_files_symbols_references_content() {
        let tmp = TempDir::new().unwrap();
        let content = b"fn my_func() { other_func(); }";
        let index =
            make_live_index_with_files(vec![("tests/generated/main.generated.rs", content)]);

        // Serialize
        serialize_index(&index, tmp.path()).expect("serialize should succeed");

        // Load
        let snapshot = load_snapshot(tmp.path()).expect("snapshot should load");
        let loaded = snapshot_to_live_index(snapshot, tmp.path());

        // Verify
        assert_eq!(loaded.files.len(), 1);
        let file = loaded
            .files
            .get("tests/generated/main.generated.rs")
            .expect("file should be present");
        assert_eq!(file.content, content);
        assert_eq!(file.symbols.len(), 1);
        assert_eq!(file.symbols[0].name, "my_func");
        assert_eq!(file.references.len(), 1);
        assert_eq!(file.references[0].name, "other_func");
        assert!(file.classification.is_code());
        assert!(file.classification.is_test);
        assert!(file.classification.is_generated);
        assert_eq!(
            file.alias_map.get("Alias").map(|s| s.as_str()),
            Some("Original")
        );
    }

    #[test]
    fn test_round_trip_preserves_crlf_bytes_and_hash() {
        let tmp = TempDir::new().unwrap();
        let content = b"fn my_func() {\r\n    other_func();\r\n}\r\n";
        let index =
            make_live_index_with_files(vec![("tests/generated/main.generated.rs", content)]);

        serialize_index(&index, tmp.path()).expect("serialize should succeed");

        let snapshot = load_snapshot(tmp.path()).expect("snapshot should load");
        let loaded = snapshot_to_live_index(snapshot, tmp.path());
        let file = loaded
            .files
            .get("tests/generated/main.generated.rs")
            .expect("file should be present");

        assert_eq!(file.content, content);
        assert_eq!(file.byte_len, content.len() as u64);
        assert_eq!(file.content_hash, crate::hash::digest_hex(content));
    }

    #[test]
    fn test_round_trip_empty_index() {
        let tmp = TempDir::new().unwrap();
        let index = make_live_index_with_files(vec![]);

        serialize_index(&index, tmp.path()).expect("serialize empty index should succeed");

        let snapshot = load_snapshot(tmp.path()).expect("snapshot should load");
        let loaded = snapshot_to_live_index(snapshot, tmp.path());

        assert_eq!(loaded.files.len(), 0);
    }

    #[test]
    fn test_snapshot_to_live_index_marks_snapshot_restore_pending_verify() {
        let tmp = TempDir::new().unwrap();
        let index = make_live_index_with_files(vec![("src/main.rs", b"fn main() {}")]);

        serialize_index(&index, tmp.path()).expect("serialize should succeed");
        let snapshot = load_snapshot(tmp.path()).expect("snapshot should load");
        let loaded = snapshot_to_live_index(snapshot, tmp.path());

        assert_eq!(loaded.load_source(), IndexLoadSource::SnapshotRestore);
        assert_eq!(loaded.snapshot_verify_state(), SnapshotVerifyState::Pending);
    }

    #[tokio::test]
    async fn test_background_verify_marks_snapshot_verify_completed() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("src").join("main.rs");
        std::fs::create_dir_all(file_path.parent().unwrap()).unwrap();
        std::fs::write(&file_path, b"fn main() {}\n").unwrap();

        let index = make_live_index_with_files(vec![("src/main.rs", b"fn main() {}\n")]);
        serialize_index(&index, tmp.path()).expect("serialize should succeed");

        let snapshot = load_snapshot(tmp.path()).expect("snapshot should load");
        let snapshot_mtimes = snapshot
            .files
            .iter()
            .map(|(path, file)| (path.clone(), file.mtime_secs))
            .collect::<HashMap<_, _>>();
        let loaded = snapshot_to_live_index(snapshot, tmp.path());
        let shared = crate::live_index::SharedIndexHandle::shared(loaded);

        {
            let guard = shared.read();
            assert_eq!(guard.load_source(), IndexLoadSource::SnapshotRestore);
            assert_eq!(guard.snapshot_verify_state(), SnapshotVerifyState::Pending);
        }

        let before = shared.published_state();
        assert_eq!(before.file_count, 1);
        assert_eq!(before.partial_parse_count, 0);
        assert_eq!(before.failed_count, 0);

        background_verify(shared.clone(), tmp.path().to_path_buf(), snapshot_mtimes).await;

        let guard = shared.read();
        assert_eq!(guard.load_source(), IndexLoadSource::SnapshotRestore);
        assert_eq!(
            guard.snapshot_verify_state(),
            SnapshotVerifyState::completed_without_mismatches()
        );
        drop(guard);

        let published = shared.published_state();
        assert_eq!(
            published.snapshot_verify_state,
            SnapshotVerifyState::completed_without_mismatches()
        );
        assert!(
            published.generation >= 2,
            "expected published generation to advance through verify transitions"
        );
        assert_eq!(published.file_count, before.file_count);
        assert_eq!(published.partial_parse_count, before.partial_parse_count);
        assert_eq!(published.failed_count, before.failed_count);
    }

    #[tokio::test]
    async fn test_background_verify_deleted_file_changes_published_counts() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("src").join("main.rs");
        std::fs::create_dir_all(file_path.parent().unwrap()).unwrap();
        std::fs::write(&file_path, b"fn main() {}\n").unwrap();

        let index = make_live_index_with_files(vec![("src/main.rs", b"fn main() {}\n")]);
        serialize_index(&index, tmp.path()).expect("serialize should succeed");

        let snapshot = load_snapshot(tmp.path()).expect("snapshot should load");
        let snapshot_mtimes = snapshot
            .files
            .iter()
            .map(|(path, file)| (path.clone(), file.mtime_secs))
            .collect::<HashMap<_, _>>();
        let loaded = snapshot_to_live_index(snapshot, tmp.path());
        let shared = crate::live_index::SharedIndexHandle::shared(loaded);

        let before = shared.published_state();
        assert_eq!(before.file_count, 1);
        assert_eq!(before.partial_parse_count, 0);
        assert_eq!(before.failed_count, 0);

        std::fs::remove_file(&file_path).expect("remove indexed file");
        background_verify(shared.clone(), tmp.path().to_path_buf(), snapshot_mtimes).await;

        let published = shared.published_state();
        assert!(
            published.generation >= 2,
            "expected published generation to advance through verify transitions"
        );
        assert_eq!(
            published.snapshot_verify_state,
            SnapshotVerifyState::completed_without_mismatches()
        );
        assert_eq!(published.file_count, 0);
        assert_eq!(published.parsed_count, 0);
        assert_eq!(published.partial_parse_count, 0);
        assert_eq!(published.failed_count, 0);
    }

    #[tokio::test]
    async fn test_background_verify_records_spot_verify_mismatch_paths() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("src").join("main.rs");
        std::fs::create_dir_all(file_path.parent().unwrap()).unwrap();
        std::fs::write(&file_path, b"fn alt1() {}\n").unwrap();
        let disk_mtime = std::fs::metadata(&file_path)
            .and_then(|meta| meta.modified())
            .ok()
            .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|duration| duration.as_secs())
            .unwrap_or(0);

        let mut index = make_live_index_with_files(vec![("src/main.rs", b"fn main() {}\n")]);
        index.files.insert(
            "src/main.rs".to_string(),
            Arc::new(make_indexed_file("src/main.rs", b"fn main() {}\n").with_mtime(disk_mtime)),
        );
        serialize_index(&index, tmp.path()).expect("serialize should succeed");

        let snapshot = load_snapshot(tmp.path()).expect("snapshot should load");
        let snapshot_mtimes = snapshot
            .files
            .iter()
            .map(|(path, file)| (path.clone(), file.mtime_secs))
            .collect::<HashMap<_, _>>();
        let loaded = snapshot_to_live_index(snapshot, tmp.path());
        let shared = crate::live_index::SharedIndexHandle::shared(loaded);

        background_verify(shared.clone(), tmp.path().to_path_buf(), snapshot_mtimes).await;

        let published = shared.published_state();
        match &published.snapshot_verify_state {
            SnapshotVerifyState::Completed(report) => {
                assert_eq!(report.mismatch_count, 1);
                assert_eq!(report.mismatched_paths, vec!["src/main.rs".to_string()]);
                assert_eq!(report.omitted_path_count(), 0);
            }
            other => panic!("expected completed snapshot verify report, got {other:?}"),
        }
    }

    #[test]
    fn test_build_snapshot_resolves_mtime_against_project_root() {
        let tmp = TempDir::new().unwrap();
        let project_root = tmp.path().join("project");
        let file_path = project_root.join("src").join("main.rs");
        std::fs::create_dir_all(file_path.parent().unwrap()).unwrap();
        std::fs::write(&file_path, b"fn main() {}\n").unwrap();

        let index = make_live_index_with_files(vec![("src/main.rs", b"fn main() {}\n")]);
        let snapshot = build_snapshot(capture_snapshot_build_input(&index), &project_root);

        let expected_mtime = std::fs::metadata(&file_path)
            .unwrap()
            .modified()
            .unwrap()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        assert_eq!(
            snapshot.files.get("src/main.rs").unwrap().mtime_secs,
            expected_mtime
        );
    }

    #[test]
    fn test_capture_verify_view_sorts_paths() {
        let index = make_live_index_with_files(vec![
            ("src/z.rs", b"fn z() {}\n"),
            ("src/a.rs", b"fn a() {}\n"),
            ("src/m.rs", b"fn m() {}\n"),
        ]);

        let view = capture_verify_view(&index);
        let paths: Vec<&str> = view
            .files
            .iter()
            .map(|file| file.relative_path.as_str())
            .collect();

        assert_eq!(paths, vec!["src/a.rs", "src/m.rs", "src/z.rs"]);
    }

    #[test]
    fn test_round_trip_multiple_files() {
        let tmp = TempDir::new().unwrap();
        let index = make_live_index_with_files(vec![
            ("a.rs", b"fn alpha() {}"),
            ("b.rs", b"fn beta() {}"),
            ("c.py", b"def gamma(): pass"),
        ]);

        serialize_index(&index, tmp.path()).expect("serialize should succeed");

        let snapshot = load_snapshot(tmp.path()).expect("snapshot should load");
        let loaded = snapshot_to_live_index(snapshot, tmp.path());

        assert_eq!(loaded.files.len(), 3);
        assert!(loaded.files.contains_key("a.rs"));
        assert!(loaded.files.contains_key("b.rs"));
        assert!(loaded.files.contains_key("c.py"));
    }

    #[test]
    fn test_round_trip_preserves_parse_status_variants() {
        let tmp = TempDir::new().unwrap();
        let mut file_map: HashMap<String, Arc<IndexedFile>> = HashMap::new();

        let partial_diagnostic = crate::domain::ParseDiagnostic {
            parser: "toml_edit".to_string(),
            message: "missing closing quote".to_string(),
            line: Some(4),
            column: Some(17),
            byte_span: Some((43, 56)),
            fallback_used: true,
        };
        let failed_diagnostic = crate::domain::ParseDiagnostic {
            parser: "toml_edit".to_string(),
            message: "invalid table header".to_string(),
            line: Some(1),
            column: Some(2),
            byte_span: Some((0, 8)),
            fallback_used: false,
        };

        file_map.insert(
            "ok.rs".to_string(),
            Arc::new(IndexedFile {
                relative_path: "ok.rs".to_string(),
                language: LanguageId::Rust,
                classification: crate::domain::FileClassification::for_code_path("ok.rs"),
                content: b"fn foo() {}".to_vec(),
                symbols: vec![],
                parse_status: ParseStatus::Parsed,
                parse_diagnostic: None,
                byte_len: 11,
                content_hash: "hash1".to_string(),
                references: vec![],
                alias_map: HashMap::new(),
                mtime_secs: 0,
            }),
        );

        file_map.insert(
            "partial.toml".to_string(),
            Arc::new(IndexedFile {
                relative_path: "partial.toml".to_string(),
                language: LanguageId::Toml,
                classification: crate::domain::FileClassification::for_code_path("partial.toml"),
                content: b"[package]\nname = \"symforge\"\ninvalid = \"unterminated\n".to_vec(),
                symbols: vec![],
                parse_status: ParseStatus::PartialParse {
                    warning: partial_diagnostic.summary(),
                },
                parse_diagnostic: Some(partial_diagnostic.clone()),
                byte_len: 52,
                content_hash: "hash2".to_string(),
                references: vec![],
                alias_map: HashMap::new(),
                mtime_secs: 0,
            }),
        );

        file_map.insert(
            "fail.toml".to_string(),
            Arc::new(IndexedFile {
                relative_path: "fail.toml".to_string(),
                language: LanguageId::Toml,
                classification: crate::domain::FileClassification::for_code_path("fail.toml"),
                content: b"[invalid\nno closing".to_vec(),
                symbols: vec![],
                parse_status: ParseStatus::Failed {
                    error: failed_diagnostic.summary(),
                },
                parse_diagnostic: Some(failed_diagnostic.clone()),
                byte_len: 19,
                content_hash: "hash3".to_string(),
                references: vec![],
                alias_map: HashMap::new(),
                mtime_secs: 0,
            }),
        );

        let trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&file_map);
        let mut index = LiveIndex {
            files: file_map,
            loaded_at: Instant::now(),
            loaded_at_system: SystemTime::now(),
            load_duration: Duration::ZERO,
            cb_state: CircuitBreakerState::new(0.20),
            is_empty: false,
            load_source: IndexLoadSource::FreshLoad,
            snapshot_verify_state: SnapshotVerifyState::NotNeeded,
            reverse_index: HashMap::new(),
            files_by_basename: HashMap::new(),
            files_by_dir_component: HashMap::new(),
            trigram_index,
            gitignore: None,
            skipped_files: Vec::new(),
            coupling_store: None,
            local_empty_reason: Arc::new(parking_lot::RwLock::new(None)),
            indexed_root: None,
        };
        index.rebuild_reverse_index();
        index.rebuild_path_indices();

        serialize_index(&index, tmp.path()).expect("serialize should succeed");
        let snapshot = load_snapshot(tmp.path()).expect("load should succeed");
        let loaded = snapshot_to_live_index(snapshot, tmp.path());

        assert_eq!(
            loaded.files.get("ok.rs").unwrap().parse_status,
            ParseStatus::Parsed
        );

        let partial = loaded.files.get("partial.toml").unwrap();
        assert!(matches!(
            partial.parse_status,
            ParseStatus::PartialParse { .. }
        ));
        assert_eq!(partial.parse_diagnostic, Some(partial_diagnostic));

        let failed = loaded.files.get("fail.toml").unwrap();
        assert!(matches!(failed.parse_status, ParseStatus::Failed { .. }));
        assert_eq!(failed.parse_diagnostic, Some(failed_diagnostic));
    }

    // ── Format pin: query equivalence across persist → restore ────────────────

    // Tripwire: bumping the persisted-index format version MUST be a deliberate
    // decision. If this assertion fails, the format is changing — stop and
    // escalate per `.octogent/tentacles/live-index/CONTEXT.md` §No-surprise rule.
    #[test]
    fn test_persist_format_version_is_pinned() {
        assert_eq!(
            CURRENT_VERSION, 4,
            "persist format version changed — a format bump breaks every existing \
             user's .symforge/index.bin and requires orchestrator approval"
        );
    }

    /// Round-trip regression on a non-trivial index spanning 3 languages, a
    /// cross-file reference, and a partial-parse diagnostic. Asserts that a
    /// representative set of public query functions returns identical results
    /// before and after `persist → restore`. This is the contract that protects
    /// existing users from silent format regressions.
    #[test]
    fn test_round_trip_preserves_query_equivalence_multilang_xref_partial() {
        use crate::domain::{ReferenceKind, SymbolKind};

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

        // ── Build a non-trivial index ─────────────────────────────────────────
        // Rust file: defines `my_func`, calls `other_func` (xref into Python).
        let rust_content = b"fn my_func() { other_func(); }";
        let rust_symbol = SymbolRecord {
            name: "my_func".to_string(),
            kind: SymbolKind::Function,
            depth: 0,
            sort_order: 0,
            byte_range: (0, 11),
            item_byte_range: Some((0, 30)),
            line_range: (0, 0),
            doc_byte_range: None,
        };
        let rust_xref = ReferenceRecord {
            name: "other_func".to_string(),
            qualified_name: None,
            kind: ReferenceKind::Call,
            byte_range: (15, 25),
            line_range: (0, 0),
            enclosing_symbol_index: Some(0),
        };

        // Python file: defines `other_func`. Carries a partial-parse diagnostic.
        let python_content = b"def other_func():\n    pass\n";
        let python_symbol = SymbolRecord {
            name: "other_func".to_string(),
            kind: SymbolKind::Function,
            depth: 0,
            sort_order: 0,
            byte_range: (0, 17),
            item_byte_range: Some((0, 27)),
            line_range: (0, 1),
            doc_byte_range: None,
        };
        let python_diagnostic = crate::domain::ParseDiagnostic {
            parser: "tree_sitter_python".to_string(),
            message: "unterminated decorator".to_string(),
            line: Some(1),
            column: Some(0),
            byte_span: Some((0, 3)),
            fallback_used: true,
        };

        // TypeScript file: defines `render`, no xrefs, parses cleanly.
        let ts_content = b"export function render(): void {}";
        let ts_symbol = SymbolRecord {
            name: "render".to_string(),
            kind: SymbolKind::Function,
            depth: 0,
            sort_order: 0,
            byte_range: (7, 29),
            item_byte_range: Some((0, 33)),
            line_range: (0, 0),
            doc_byte_range: None,
        };

        let mut alias_map = HashMap::new();
        alias_map.insert("Map".to_string(), "HashMap".to_string());

        let rust_file = IndexedFile {
            relative_path: "src/foo.rs".to_string(),
            language: LanguageId::Rust,
            classification: crate::domain::FileClassification::for_code_path("src/foo.rs"),
            content: rust_content.to_vec(),
            symbols: vec![rust_symbol],
            parse_status: ParseStatus::Parsed,
            parse_diagnostic: None,
            byte_len: rust_content.len() as u64,
            content_hash: crate::hash::digest_hex(rust_content),
            references: vec![rust_xref],
            alias_map,
            mtime_secs: 0,
        };
        let python_file = IndexedFile {
            relative_path: "src/bar.py".to_string(),
            language: LanguageId::Python,
            classification: crate::domain::FileClassification::for_code_path("src/bar.py"),
            content: python_content.to_vec(),
            symbols: vec![python_symbol],
            parse_status: ParseStatus::PartialParse {
                warning: python_diagnostic.summary(),
            },
            parse_diagnostic: Some(python_diagnostic),
            byte_len: python_content.len() as u64,
            content_hash: crate::hash::digest_hex(python_content),
            references: vec![],
            alias_map: HashMap::new(),
            mtime_secs: 0,
        };
        let ts_file = IndexedFile {
            relative_path: "src/baz.ts".to_string(),
            language: LanguageId::TypeScript,
            classification: crate::domain::FileClassification::for_code_path("src/baz.ts"),
            content: ts_content.to_vec(),
            symbols: vec![ts_symbol],
            parse_status: ParseStatus::Parsed,
            parse_diagnostic: None,
            byte_len: ts_content.len() as u64,
            content_hash: crate::hash::digest_hex(ts_content),
            references: vec![],
            alias_map: HashMap::new(),
            mtime_secs: 0,
        };

        let mut file_map: HashMap<String, Arc<IndexedFile>> = HashMap::new();
        file_map.insert("src/foo.rs".to_string(), Arc::new(rust_file));
        file_map.insert("src/bar.py".to_string(), Arc::new(python_file));
        file_map.insert("src/baz.ts".to_string(), Arc::new(ts_file));

        let trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&file_map);
        let mut before = LiveIndex {
            files: file_map,
            loaded_at: Instant::now(),
            loaded_at_system: SystemTime::now(),
            load_duration: Duration::ZERO,
            cb_state: CircuitBreakerState::new(0.20),
            is_empty: false,
            load_source: IndexLoadSource::FreshLoad,
            snapshot_verify_state: SnapshotVerifyState::NotNeeded,
            reverse_index: HashMap::new(),
            files_by_basename: HashMap::new(),
            files_by_dir_component: HashMap::new(),
            trigram_index,
            gitignore: None,
            skipped_files: Vec::new(),
            coupling_store: None,
            local_empty_reason: Arc::new(parking_lot::RwLock::new(None)),
            indexed_root: None,
        };
        before.rebuild_reverse_index();
        before.rebuild_path_indices();

        // ── Persist, then restore ─────────────────────────────────────────────
        serialize_index(&before, tmp.path()).expect("serialize should succeed");

        // Tripwire on the serialized version field itself.
        let raw = std::fs::read(tmp.path().join(".symforge").join("index.bin")).unwrap();
        let decoded: IndexSnapshot =
            postcard::from_bytes(&raw).expect("persisted snapshot decodes");
        assert_eq!(
            decoded.version, CURRENT_VERSION,
            "serialized snapshot must carry CURRENT_VERSION"
        );

        let snapshot = load_snapshot(tmp.path()).expect("snapshot should load");
        let after = snapshot_to_live_index(snapshot, tmp.path());

        // ── Query equivalence ────────────────────────────────────────────────

        // Scalars
        assert_eq!(before.file_count(), after.file_count(), "file_count");
        assert_eq!(before.symbol_count(), after.symbol_count(), "symbol_count");

        // all_files() — sorted equivalence
        let mut before_all: Vec<(String, IndexedFile)> = before
            .all_files()
            .map(|(p, f)| (p.clone(), f.clone()))
            .collect();
        let mut after_all: Vec<(String, IndexedFile)> = after
            .all_files()
            .map(|(p, f)| (p.clone(), f.clone()))
            .collect();
        before_all.sort_by(|a, b| a.0.cmp(&b.0));
        after_all.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(before_all.len(), after_all.len(), "all_files len");
        for ((bp, bf), (ap, af)) in before_all.iter().zip(after_all.iter()) {
            assert_eq!(bp, ap, "all_files path");
            assert_eq!(bf.content, af.content, "content for {bp}");
            assert_eq!(bf.content_hash, af.content_hash, "hash for {bp}");
            assert_eq!(bf.language, af.language, "language for {bp}");
            assert_eq!(bf.symbols, af.symbols, "symbols for {bp}");
            assert_eq!(bf.references, af.references, "references for {bp}");
            assert_eq!(bf.parse_status, af.parse_status, "parse_status for {bp}");
            assert_eq!(
                bf.parse_diagnostic, af.parse_diagnostic,
                "parse_diagnostic for {bp}"
            );
            assert_eq!(bf.alias_map, af.alias_map, "alias_map for {bp}");
            assert_eq!(
                bf.classification, af.classification,
                "classification for {bp}"
            );
        }

        // Per-file: get_file + symbols_for_file
        for path in ["src/foo.rs", "src/bar.py", "src/baz.ts"] {
            let b = before.get_file(path).expect("before file present");
            let a = after.get_file(path).expect("after file present");
            assert_eq!(b.content, a.content, "get_file content {path}");
            assert_eq!(
                before.symbols_for_file(path),
                after.symbols_for_file(path),
                "symbols_for_file {path}"
            );
        }

        // Path indices rebuilt identically
        for basename in ["foo.rs", "bar.py", "baz.ts"] {
            assert_eq!(
                before.find_files_by_basename(basename),
                after.find_files_by_basename(basename),
                "find_files_by_basename {basename}"
            );
        }
        assert_eq!(
            before.find_files_by_dir_component("src"),
            after.find_files_by_dir_component("src"),
            "find_files_by_dir_component src"
        );

        // Cross-reference survives the round-trip (reverse index rebuilt from
        // persisted references).
        let before_refs: Vec<(String, ReferenceRecord)> = before
            .find_references_for_name("other_func", None, true)
            .into_iter()
            .map(|(p, r)| (p.to_string(), r.clone()))
            .collect();
        let after_refs: Vec<(String, ReferenceRecord)> = after
            .find_references_for_name("other_func", None, true)
            .into_iter()
            .map(|(p, r)| (p.to_string(), r.clone()))
            .collect();
        assert_eq!(before_refs.len(), 1, "one xref before round-trip");
        assert_eq!(before_refs, after_refs, "find_references_for_name xref");

        // Health stats: partial/failed breakdown and file/symbol counts.
        let bh = before.health_stats();
        let ah = after.health_stats();
        assert_eq!(bh.file_count, ah.file_count, "health file_count");
        assert_eq!(bh.symbol_count, ah.symbol_count, "health symbol_count");
        assert_eq!(bh.parsed_count, ah.parsed_count, "health parsed_count");
        assert_eq!(
            bh.partial_parse_count, ah.partial_parse_count,
            "health partial_parse_count"
        );
        assert_eq!(bh.failed_count, ah.failed_count, "health failed_count");
        assert_eq!(
            bh.partial_parse_files, ah.partial_parse_files,
            "health partial_parse_files"
        );
        assert_eq!(bh.failed_files, ah.failed_files, "health failed_files");
        assert_eq!(
            bh.partial_parse_count, 1,
            "test setup must include one partial-parse file"
        );

        // Repo outline: same files, languages, symbol counts.
        let bo = before.capture_repo_outline_view();
        let ao = after.capture_repo_outline_view();
        assert_eq!(bo.total_files, ao.total_files, "outline total_files");
        assert_eq!(bo.total_symbols, ao.total_symbols, "outline total_symbols");
        assert_eq!(bo.files, ao.files, "outline files");
    }

    // ── Version mismatch / corrupt data tests ─────────────────────────────────

    fn quarantine_files_with_extension(root: &Path, extension: &str) -> Vec<PathBuf> {
        let dir = paths::resolve_index_snapshot_quarantine_dir(root);
        let mut files = match std::fs::read_dir(&dir) {
            Ok(entries) => entries
                .map(|entry| entry.unwrap().path())
                .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some(extension))
                .collect::<Vec<_>>(),
            Err(_) => Vec::new(),
        };
        files.sort();
        files
    }

    #[test]
    fn test_version_mismatch_quarantines_snapshot_and_returns_none() {
        let tmp = TempDir::new().unwrap();

        // Build a snapshot with a wrong version and serialize it manually
        let snapshot = IndexSnapshot {
            version: 999,
            files: HashMap::new(),
        };
        let bytes = postcard::to_stdvec(&snapshot).unwrap();
        let dir = tmp.path().join(".symforge");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("index.bin"), &bytes).unwrap();

        // load_snapshot must return None, not panic
        let result = load_snapshot(tmp.path());
        assert!(result.is_none(), "version mismatch must return None");

        let quarantine_bins = quarantine_files_with_extension(tmp.path(), "bin");
        assert_eq!(
            quarantine_bins.len(),
            1,
            "version mismatch should preserve the snapshot in quarantine"
        );
        assert_eq!(
            std::fs::read(&quarantine_bins[0]).unwrap(),
            bytes,
            "quarantine must preserve original version-mismatched bytes"
        );
        assert!(
            !dir.join("index.bin").exists(),
            "version-mismatched active snapshot should be removed after quarantine"
        );
        let quarantine_metadata = quarantine_files_with_extension(tmp.path(), "json");
        assert_eq!(quarantine_metadata.len(), 1);
        let metadata: serde_json::Value =
            serde_json::from_slice(&std::fs::read(&quarantine_metadata[0]).unwrap()).unwrap();
        assert_eq!(metadata["reason"], "version-mismatch");
        assert_eq!(metadata["sha256"], crate::hash::digest_hex(&bytes));
    }

    #[test]
    fn test_corrupt_bytes_quarantined_and_returns_none_no_panic() {
        let tmp = TempDir::new().unwrap();

        // Write random garbage
        let dir = tmp.path().join(".symforge");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("index.bin"),
            b"not valid postcard data xyzzy 12345",
        )
        .unwrap();

        let result = load_snapshot(tmp.path());
        assert!(
            result.is_none(),
            "corrupt bytes must return None, not panic"
        );

        let quarantine_bins = quarantine_files_with_extension(tmp.path(), "bin");
        assert_eq!(
            quarantine_bins.len(),
            1,
            "corrupt bytes should be preserved in quarantine"
        );
        assert_eq!(
            std::fs::read(&quarantine_bins[0]).unwrap(),
            b"not valid postcard data xyzzy 12345",
            "quarantine must preserve original corrupt bytes"
        );
        assert!(
            !dir.join("index.bin").exists(),
            "corrupt active snapshot should be removed after quarantine"
        );
        let quarantine_metadata = quarantine_files_with_extension(tmp.path(), "json");
        assert_eq!(quarantine_metadata.len(), 1);
        let metadata: serde_json::Value =
            serde_json::from_slice(&std::fs::read(&quarantine_metadata[0]).unwrap()).unwrap();
        assert_eq!(metadata["reason"], "deserialize-error");
    }

    #[test]
    fn test_truncated_bytes_quarantined_and_returns_none_no_panic() {
        let tmp = TempDir::new().unwrap();

        // Serialize a real snapshot, then truncate it to half
        let index = make_live_index_with_files(vec![("a.rs", b"fn foo() {}")]);
        serialize_index(&index, tmp.path()).expect("serialize should succeed");

        let bin_path = tmp.path().join(".symforge").join("index.bin");
        let full_bytes = std::fs::read(&bin_path).unwrap();
        let truncated = &full_bytes[..full_bytes.len() / 2];
        std::fs::write(&bin_path, truncated).unwrap();

        let result = load_snapshot(tmp.path());
        assert!(
            result.is_none(),
            "truncated bytes must return None, not panic"
        );

        let quarantine_bins = quarantine_files_with_extension(tmp.path(), "bin");
        assert_eq!(
            quarantine_bins.len(),
            1,
            "truncated bytes should be preserved in quarantine"
        );
        assert_eq!(std::fs::read(&quarantine_bins[0]).unwrap(), truncated);
    }

    #[test]
    fn test_missing_file_returns_none() {
        let tmp = TempDir::new().unwrap();
        // No .symforge/index.bin exists
        let result = load_snapshot(tmp.path());
        assert!(result.is_none(), "missing file must return None");
        assert!(
            quarantine_files_with_extension(tmp.path(), "bin").is_empty(),
            "missing first-run snapshot should not create quarantine artifacts"
        );
    }

    // ── stat_check_files_from_view tests ──────────────────────────────────────

    #[test]
    fn test_stat_check_identifies_changed_file_by_size() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("a.rs");
        std::fs::write(&file_path, b"fn foo() {}").unwrap();

        // Build index with wrong byte_len to simulate a changed file
        let mut file_map: HashMap<String, Arc<IndexedFile>> = HashMap::new();
        file_map.insert(
            "a.rs".to_string(),
            Arc::new(IndexedFile {
                relative_path: "a.rs".to_string(),
                language: LanguageId::Rust,
                classification: crate::domain::FileClassification::for_code_path("a.rs"),
                content: b"fn foo() {}".to_vec(),
                symbols: vec![],
                parse_status: ParseStatus::Parsed,
                parse_diagnostic: None,
                byte_len: 999, // wrong size — simulates change
                content_hash: "old_hash".to_string(),
                references: vec![],
                alias_map: HashMap::new(),
                mtime_secs: 0,
            }),
        );
        let trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&file_map);
        let mut index = LiveIndex {
            files: file_map,
            loaded_at: Instant::now(),
            loaded_at_system: SystemTime::now(),
            load_duration: Duration::ZERO,
            cb_state: CircuitBreakerState::new(0.20),
            is_empty: false,
            load_source: IndexLoadSource::FreshLoad,
            snapshot_verify_state: SnapshotVerifyState::NotNeeded,
            reverse_index: HashMap::new(),
            files_by_basename: HashMap::new(),
            files_by_dir_component: HashMap::new(),
            trigram_index,
            gitignore: None,
            skipped_files: Vec::new(),
            coupling_store: None,
            local_empty_reason: Arc::new(parking_lot::RwLock::new(None)),
            indexed_root: None,
        };
        index.rebuild_reverse_index();
        index.rebuild_path_indices();

        // mtime from disk
        let mtime = std::fs::metadata(&file_path)
            .unwrap()
            .modified()
            .unwrap()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let mut mtimes: HashMap<String, u64> = HashMap::new();
        mtimes.insert("a.rs".to_string(), mtime);

        let result = stat_check_files_from_view(&capture_verify_view(&index), &mtimes, tmp.path());
        assert!(
            result.changed.contains(&"a.rs".to_string()),
            "changed by size mismatch"
        );
        assert!(result.deleted.is_empty());
    }

    #[test]
    fn test_stat_check_identifies_deleted_file() {
        let tmp = TempDir::new().unwrap();

        // Index has a file that doesn't exist on disk
        let mut file_map: HashMap<String, Arc<IndexedFile>> = HashMap::new();
        file_map.insert(
            "ghost.rs".to_string(),
            Arc::new(IndexedFile {
                relative_path: "ghost.rs".to_string(),
                language: LanguageId::Rust,
                classification: crate::domain::FileClassification::for_code_path("ghost.rs"),
                content: b"fn ghost() {}".to_vec(),
                symbols: vec![],
                parse_status: ParseStatus::Parsed,
                parse_diagnostic: None,
                byte_len: 13,
                content_hash: "hash".to_string(),
                references: vec![],
                alias_map: HashMap::new(),
                mtime_secs: 0,
            }),
        );
        let trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&file_map);
        let mut index = LiveIndex {
            files: file_map,
            loaded_at: Instant::now(),
            loaded_at_system: SystemTime::now(),
            load_duration: Duration::ZERO,
            cb_state: CircuitBreakerState::new(0.20),
            is_empty: false,
            load_source: IndexLoadSource::FreshLoad,
            snapshot_verify_state: SnapshotVerifyState::NotNeeded,
            reverse_index: HashMap::new(),
            files_by_basename: HashMap::new(),
            files_by_dir_component: HashMap::new(),
            trigram_index,
            gitignore: None,
            skipped_files: Vec::new(),
            coupling_store: None,
            local_empty_reason: Arc::new(parking_lot::RwLock::new(None)),
            indexed_root: None,
        };
        index.rebuild_reverse_index();
        index.rebuild_path_indices();

        let result =
            stat_check_files_from_view(&capture_verify_view(&index), &HashMap::new(), tmp.path());
        assert!(
            result.deleted.contains(&"ghost.rs".to_string()),
            "missing file should be in deleted"
        );
    }

    #[test]
    fn test_stat_check_identifies_new_file() {
        let tmp = TempDir::new().unwrap();
        // Write a file on disk that's not in the index
        std::fs::write(tmp.path().join("new.rs"), b"fn new_func() {}").unwrap();

        // Empty index
        let index = make_live_index_with_files(vec![]);

        let result =
            stat_check_files_from_view(&capture_verify_view(&index), &HashMap::new(), tmp.path());
        assert!(
            result.new_files.contains(&"new.rs".to_string()),
            "new file should be detected"
        );
    }

    // ── spot_verify_sample tests ──────────────────────────────────────────────

    #[test]
    fn test_spot_verify_catches_content_hash_mismatch() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("a.rs");
        // On-disk content is different from what's in the index
        std::fs::write(&file_path, b"fn modified() {}").unwrap();

        let mut file_map: HashMap<String, Arc<IndexedFile>> = HashMap::new();
        file_map.insert(
            "a.rs".to_string(),
            Arc::new(IndexedFile {
                relative_path: "a.rs".to_string(),
                language: LanguageId::Rust,
                classification: crate::domain::FileClassification::for_code_path("a.rs"),
                content: b"fn original() {}".to_vec(), // old content
                symbols: vec![],
                parse_status: ParseStatus::Parsed,
                parse_diagnostic: None,
                byte_len: 16,
                content_hash: crate::hash::digest_hex(b"fn original() {}"), // stale hash
                references: vec![],
                alias_map: HashMap::new(),
                mtime_secs: 0,
            }),
        );
        let trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&file_map);
        let mut index = LiveIndex {
            files: file_map,
            loaded_at: Instant::now(),
            loaded_at_system: SystemTime::now(),
            load_duration: Duration::ZERO,
            cb_state: CircuitBreakerState::new(0.20),
            is_empty: false,
            load_source: IndexLoadSource::FreshLoad,
            snapshot_verify_state: SnapshotVerifyState::NotNeeded,
            reverse_index: HashMap::new(),
            files_by_basename: HashMap::new(),
            files_by_dir_component: HashMap::new(),
            trigram_index,
            gitignore: None,
            skipped_files: Vec::new(),
            coupling_store: None,
            local_empty_reason: Arc::new(parking_lot::RwLock::new(None)),
            indexed_root: None,
        };
        index.rebuild_reverse_index();
        index.rebuild_path_indices();

        // Sample 100% to ensure the file is included
        let mismatches =
            spot_verify_sample_from_view(&capture_verify_view(&index), tmp.path(), 1.0);
        assert!(
            mismatches.contains(&"a.rs".to_string()),
            "hash mismatch should be detected"
        );
    }

    #[test]
    fn test_spot_verify_no_mismatch_when_hashes_match() {
        let tmp = TempDir::new().unwrap();
        let content = b"fn current() {}";
        let file_path = tmp.path().join("a.rs");
        std::fs::write(&file_path, content).unwrap();

        let hash = crate::hash::digest_hex(content);
        let mut file_map: HashMap<String, Arc<IndexedFile>> = HashMap::new();
        file_map.insert(
            "a.rs".to_string(),
            Arc::new(IndexedFile {
                relative_path: "a.rs".to_string(),
                language: LanguageId::Rust,
                classification: crate::domain::FileClassification::for_code_path("a.rs"),
                content: content.to_vec(),
                symbols: vec![],
                parse_status: ParseStatus::Parsed,
                parse_diagnostic: None,
                byte_len: content.len() as u64,
                content_hash: hash,
                references: vec![],
                alias_map: HashMap::new(),
                mtime_secs: 0,
            }),
        );
        let trigram_index = crate::live_index::trigram::TrigramIndex::build_from_files(&file_map);
        let mut index = LiveIndex {
            files: file_map,
            loaded_at: Instant::now(),
            loaded_at_system: SystemTime::now(),
            load_duration: Duration::ZERO,
            cb_state: CircuitBreakerState::new(0.20),
            is_empty: false,
            load_source: IndexLoadSource::FreshLoad,
            snapshot_verify_state: SnapshotVerifyState::NotNeeded,
            reverse_index: HashMap::new(),
            files_by_basename: HashMap::new(),
            files_by_dir_component: HashMap::new(),
            trigram_index,
            gitignore: None,
            skipped_files: Vec::new(),
            coupling_store: None,
            local_empty_reason: Arc::new(parking_lot::RwLock::new(None)),
            indexed_root: None,
        };
        index.rebuild_reverse_index();
        index.rebuild_path_indices();

        let mismatches =
            spot_verify_sample_from_view(&capture_verify_view(&index), tmp.path(), 1.0);
        assert!(mismatches.is_empty(), "no mismatch when hash is current");
    }

    #[test]
    fn test_spot_verify_empty_index_returns_empty() {
        let tmp = TempDir::new().unwrap();
        let index = make_live_index_with_files(vec![]);
        let mismatches =
            spot_verify_sample_from_view(&capture_verify_view(&index), tmp.path(), 0.10);
        assert!(mismatches.is_empty(), "empty index returns empty vec");
    }

    // ── Snapshot atomicity test ───────────────────────────────────────────────

    #[test]
    fn test_serialize_creates_symforge_dir() {
        let tmp = TempDir::new().unwrap();
        let index = make_live_index_with_files(vec![("src/lib.rs", b"fn lib() {}")]);

        serialize_index(&index, tmp.path()).expect("serialize should succeed");

        assert!(
            tmp.path().join(".symforge").join("index.bin").exists(),
            ".symforge/index.bin should be created"
        );
    }

    #[test]
    fn test_reset_snapshot_state_deletes_only_snapshot_scope() {
        let tmp = TempDir::new().unwrap();
        let symforge_dir = tmp.path().join(".symforge");
        let source_dir = tmp.path().join("src");
        std::fs::create_dir_all(&symforge_dir).expect("create .symforge");
        std::fs::create_dir_all(&source_dir).expect("create source dir");
        std::fs::write(source_dir.join("lib.rs"), "fn source_file() {}\n").expect("write source");
        std::fs::write(symforge_dir.join("index.bin"), b"stale snapshot").expect("write snapshot");
        std::fs::write(symforge_dir.join("index.bin.tmp"), b"stale tmp").expect("write tmp");
        std::fs::write(symforge_dir.join("frecency.db"), b"unrelated").expect("write sentinel");

        let report = reset_snapshot_state(tmp.path()).expect("reset snapshot state");

        assert_eq!(report.removed_count(), 2);
        assert!(!symforge_dir.join("index.bin").exists());
        assert!(!symforge_dir.join("index.bin.tmp").exists());
        assert!(
            symforge_dir.join("frecency.db").exists(),
            "reset must preserve unrelated .symforge state"
        );
        assert!(
            source_dir.join("lib.rs").exists(),
            "reset must never delete source files"
        );
    }

    // ── FrecencyStore init hook tests ─────────────────────────────────────────

    use crate::live_index::frecency::{FRECENCY_FLAG_ENV, FrecencyStore};
    use std::path::PathBuf;
    use std::sync::Mutex as StdMutex;

    // Serialize tests that mutate FRECENCY_FLAG_ENV so a parallel runner (or a
    // sibling test that forgets to clear) cannot interleave env transitions.
    static FRECENCY_ENV_LOCK: StdMutex<()> = StdMutex::new(());

    #[allow(unsafe_code)] // test-only flag helper runs under FRECENCY_ENV_LOCK.
    fn clear_frecency_flag() {
        // SAFETY: callers hold FRECENCY_ENV_LOCK and tests run with
        // --test-threads=1 per the project test policy.
        unsafe { std::env::remove_var(FRECENCY_FLAG_ENV) };
    }

    /// Commit `count` empty-tree commits to the repo at `root`, parenting each
    /// on the last commit of `HEAD`. Returns the SHA of the final commit.
    fn make_commits(root: &Path, count: usize, base_msg: &str) -> String {
        let repo = git2::Repository::open(root).expect("open test repo");
        let sig = git2::Signature::now("t", "t@x").expect("sig");
        let tree_id = {
            let mut idx = repo.index().expect("index");
            idx.write_tree().expect("write tree")
        };
        let tree = repo.find_tree(tree_id).expect("find tree");
        let mut head = repo
            .head()
            .expect("head")
            .peel_to_commit()
            .expect("peel head");
        for i in 0..count {
            let oid = git_test_helpers::commit_head_with_retry(
                &repo,
                &sig,
                &sig,
                &format!("{base_msg} {i}"),
                &tree,
                &[&head],
            );
            head = repo.find_commit(oid).expect("find commit");
        }
        head.id().to_string()
    }

    /// Initialize a repo at `root` with one root commit. Returns that SHA.
    fn init_repo_with_root_commit(root: &Path) -> String {
        let repo = git2::Repository::init(root).expect("init");
        let sig = git2::Signature::now("t", "t@x").expect("sig");
        let tree_id = {
            let mut idx = repo.index().expect("index");
            idx.write_tree().expect("write tree")
        };
        let tree = repo.find_tree(tree_id).expect("find tree");
        let oid = git_test_helpers::commit_head_with_retry(&repo, &sig, &sig, "root", &tree, &[]);
        oid.to_string()
    }

    #[test]
    fn init_frecency_store_is_noop_when_flag_unset() {
        let _g = FRECENCY_ENV_LOCK.lock().unwrap();
        clear_frecency_flag();
        let tmp = TempDir::new().unwrap();
        init_frecency_store(tmp.path());
        assert!(
            !crate::live_index::frecency::frecency_db_path(tmp.path()).exists(),
            "init must not create the frecency database when flag is unset"
        );
        assert!(
            !tmp.path().join(paths::SYMFORGE_DIR_NAME).exists(),
            "init must not create the .symforge directory when flag is unset"
        );
    }

    #[test]
    fn run_frecency_init_is_noop_when_project_root_is_not_a_repo() {
        // A path with no .git ancestry must degrade gracefully: the DB may be
        // opened (migrate is cheap), but no reset policy can apply since there
        // is no HEAD to read. We assert no last_head gets stored.
        let tmp = TempDir::new().unwrap();
        let db_path = tmp.path().join("frecency.db");
        run_frecency_init(&db_path, tmp.path()).expect("init returns Ok on missing repo");
        let store = FrecencyStore::open(&db_path).unwrap();
        assert_eq!(
            store.last_head().unwrap(),
            None,
            "no HEAD should be recorded when the project root is not a git repo"
        );
    }

    #[test]
    fn run_frecency_init_records_head_on_first_session() {
        let tmp = TempDir::new().unwrap();
        let sha = init_repo_with_root_commit(tmp.path());
        let db_path = tmp.path().join("frecency.db");
        run_frecency_init(&db_path, tmp.path()).expect("init ok");
        let store = FrecencyStore::open(&db_path).unwrap();
        assert_eq!(store.last_head().unwrap().as_deref(), Some(sha.as_str()));
    }

    #[test]
    fn run_frecency_init_is_noop_when_head_unchanged() {
        let tmp = TempDir::new().unwrap();
        let sha = init_repo_with_root_commit(tmp.path());
        let db_path = tmp.path().join("frecency.db");
        // Seed: stored_head matches current, some bumps already exist.
        {
            let store = FrecencyStore::open(&db_path).unwrap();
            store.bump(&[PathBuf::from("src/a.rs")], 0).unwrap();
            store.bump(&[PathBuf::from("src/a.rs")], 0).unwrap();
            store
                .reset_or_halve_on_head_change(None, &sha, None)
                .unwrap();
        }
        run_frecency_init(&db_path, tmp.path()).expect("init ok");
        let store = FrecencyStore::open(&db_path).unwrap();
        assert_eq!(
            store.score(Path::new("src/a.rs"), 0).unwrap(),
            2.0,
            "same-HEAD init must not reset hit counts"
        );
        assert_eq!(store.last_head().unwrap().as_deref(), Some(sha.as_str()));
    }

    #[test]
    fn run_frecency_init_halves_at_100_commits() {
        let tmp = TempDir::new().unwrap();
        let first = init_repo_with_root_commit(tmp.path());
        let db_path = tmp.path().join("frecency.db");
        {
            let store = FrecencyStore::open(&db_path).unwrap();
            for _ in 0..10 {
                store.bump(&[PathBuf::from("src/a.rs")], 0).unwrap();
            }
            store
                .reset_or_halve_on_head_change(None, &first, None)
                .unwrap();
        }
        let _new_head = make_commits(tmp.path(), 100, "advance");
        run_frecency_init(&db_path, tmp.path()).expect("init ok");
        let store = FrecencyStore::open(&db_path).unwrap();
        assert_eq!(
            store.score(Path::new("src/a.rs"), 0).unwrap(),
            5.0,
            "100 commits falls into the 50..=500 band and must halve"
        );
    }

    #[test]
    fn run_frecency_init_zeros_above_500_commits() {
        let tmp = TempDir::new().unwrap();
        let first = init_repo_with_root_commit(tmp.path());
        let db_path = tmp.path().join("frecency.db");
        {
            let store = FrecencyStore::open(&db_path).unwrap();
            for _ in 0..10 {
                store.bump(&[PathBuf::from("src/a.rs")], 0).unwrap();
            }
            store
                .reset_or_halve_on_head_change(None, &first, None)
                .unwrap();
        }
        let _new_head = make_commits(tmp.path(), 501, "advance");
        run_frecency_init(&db_path, tmp.path()).expect("init ok");
        let store = FrecencyStore::open(&db_path).unwrap();
        assert_eq!(
            store.score(Path::new("src/a.rs"), 0).unwrap(),
            0.0,
            ">500 commits must zero hit counts"
        );
    }

    #[allow(unsafe_code)] // test-only flag mutation runs under FRECENCY_ENV_LOCK.
    #[test]
    fn init_frecency_store_with_flag_on_wires_boot_policy() {
        let _g = FRECENCY_ENV_LOCK.lock().unwrap();
        let tmp = TempDir::new().unwrap();
        let sha = init_repo_with_root_commit(tmp.path());
        // SAFETY: test holds FRECENCY_ENV_LOCK; tests are --test-threads=1.
        unsafe { std::env::set_var(FRECENCY_FLAG_ENV, "1") };
        init_frecency_store(tmp.path());
        clear_frecency_flag();
        let db_path = crate::live_index::frecency::frecency_db_path(tmp.path());
        assert!(
            db_path.exists(),
            "flag=1 init must create the frecency database"
        );
        let store = FrecencyStore::open(&db_path).unwrap();
        assert_eq!(
            store.last_head().unwrap().as_deref(),
            Some(sha.as_str()),
            "flag=1 init must record current HEAD"
        );
    }

    #[test]
    fn test_serialize_idempotent() {
        let tmp = TempDir::new().unwrap();
        let index = make_live_index_with_files(vec![("a.rs", b"fn a() {}")]);

        // Serialize twice — should succeed both times (no leftover .tmp)
        serialize_index(&index, tmp.path()).expect("first serialize should succeed");
        serialize_index(&index, tmp.path()).expect("second serialize should succeed");

        assert!(tmp.path().join(".symforge").join("index.bin").exists());
        // No tmp file should remain
        assert!(!tmp.path().join(".symforge").join("index.bin.tmp").exists());
    }

    // ── Team artifact tests (Program 015 S1a, C-S1A-005) ──────────────────────

    #[test]
    fn test_export_artifact_writes_metadata_and_gitattributes_hint() {
        let tmp = TempDir::new().unwrap();
        let index =
            make_live_index_with_files(vec![("a.rs", b"fn a() {}"), ("b.rs", b"fn b() {}")]);

        let report = export_artifact(&index, tmp.path()).expect("export should succeed");
        assert_eq!(report.files, 2);
        assert!(report.path.exists(), "index.bin.zst should exist");
        assert!(report.metadata_path.exists(), "artifact.json should exist");
        assert_eq!(report.path.file_name().unwrap(), ARTIFACT_FILENAME);

        let metadata: serde_json::Value =
            serde_json::from_slice(&std::fs::read(&report.metadata_path).unwrap()).unwrap();
        assert_eq!(metadata["content_hash"], report.content_hash);
        assert_eq!(metadata["files"], 2);

        // A-US2-04: .gitattributes carries the merge=ours hint.
        let gitattributes = std::fs::read_to_string(tmp.path().join(".gitattributes")).unwrap();
        assert!(
            gitattributes
                .lines()
                .any(|line| line.trim() == "*.zst merge=ours"),
            "expected *.zst merge=ours hint, got: {gitattributes:?}"
        );

        // Idempotent: exporting again must not duplicate the gitattributes hint.
        export_artifact(&index, tmp.path()).expect("second export should succeed");
        let gitattributes_again =
            std::fs::read_to_string(tmp.path().join(".gitattributes")).unwrap();
        assert_eq!(
            gitattributes_again.matches("merge=ours").count(),
            1,
            "repeat export must not duplicate the gitattributes hint"
        );
    }

    #[test]
    fn test_artifact_round_trip_is_byte_exact_and_preserves_content_hash() {
        let tmp = TempDir::new().unwrap();
        let index = make_live_index_with_files(vec![
            ("src/foo.rs", b"fn foo() { bar(); }"),
            ("src/bar.py", b"def bar():\n    pass\n"),
        ]);

        let (before, raw, compressed) =
            build_compressed_snapshot(&index, tmp.path()).expect("build compressed snapshot");
        let decompressed = decompress_artifact_bytes(&compressed).expect("decompress");
        let after: IndexSnapshot = postcard::from_bytes(&decompressed).expect("decode postcard");

        // SP-0B caveat (a), adapted: `IndexSnapshot.files` is a `HashMap`, so
        // re-serializing the *deserialized* snapshot is not guaranteed to
        // reproduce the original bytes (HashMap iteration order is not part
        // of its API contract, even for identical logical content). The
        // property that IS deterministic — and is the real "whole-snapshot
        // byte-exact" guarantee this artifact needs — is the zstd round trip
        // itself: decompression must reproduce the exact pre-compression
        // postcard bytes.
        assert_eq!(
            decompressed, raw,
            "zstd decompress must reproduce the pre-compression postcard bytes exactly"
        );

        for (path, before_file) in &before.files {
            let after_file = after
                .files
                .get(path)
                .expect("file present after round trip");
            assert_eq!(after_file.content_hash, before_file.content_hash);
        }
    }

    #[test]
    fn test_load_snapshot_imports_artifact_when_bin_missing() {
        let tmp = TempDir::new().unwrap();
        let index = make_live_index_with_files(vec![("src/main.rs", b"fn main() {}")]);

        export_artifact(&index, tmp.path()).expect("export should succeed");
        assert!(
            !tmp.path().join(".symforge").join("index.bin").exists(),
            "only the .zst artifact should exist for this scenario"
        );

        let snapshot = load_snapshot(tmp.path()).expect("load_snapshot should import the artifact");
        let file = snapshot
            .files
            .get("src/main.rs")
            .expect("imported snapshot should contain the file");
        assert_eq!(file.content_hash, crate::hash::digest_hex(b"fn main() {}"));
    }

    #[test]
    fn test_load_snapshot_quarantines_corrupt_artifact_and_returns_none() {
        let tmp = TempDir::new().unwrap();
        let index = make_live_index_with_files(vec![("src/main.rs", b"fn main() {}")]);
        export_artifact(&index, tmp.path()).expect("export should succeed");

        let artifact_path = tmp.path().join(".symforge").join(ARTIFACT_FILENAME);
        let good = std::fs::read(&artifact_path).unwrap();
        std::fs::write(&artifact_path, &good[..good.len() / 2]).unwrap();

        let result = load_snapshot(tmp.path());
        assert!(
            result.is_none(),
            "corrupt artifact must fall back to a full re-index, not partial-serve"
        );
        assert!(
            !artifact_path.exists(),
            "corrupt artifact should be removed from the active path after quarantine"
        );

        let quarantine_dir = paths::resolve_artifact_quarantine_dir(tmp.path());
        let quarantined: Vec<_> = std::fs::read_dir(&quarantine_dir)
            .expect("quarantine dir should exist")
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().and_then(|ext| ext.to_str()) == Some("zst"))
            .collect();
        assert_eq!(
            quarantined.len(),
            1,
            "corrupt artifact should be quarantined under .symforge/quarantine/artifacts/"
        );
    }

    #[test]
    fn test_load_snapshot_quarantines_artifact_with_missing_sidecar() {
        // The artifact and its sidecar are written non-atomically
        // (export_artifact: rename the .zst, then a separate std::fs::write of
        // artifact.json). A crash between them — or a partial checkout that
        // picked up the .zst but not the .json — leaves a VALID compressed
        // artifact with NO sidecar. content_hash is then unverifiable, so the
        // import path must quarantine and fall back, not silently trust it.
        let tmp = TempDir::new().unwrap();
        let index = make_live_index_with_files(vec![("src/main.rs", b"fn main() {}")]);
        export_artifact(&index, tmp.path()).expect("export should succeed");

        let artifact_path = tmp.path().join(".symforge").join(ARTIFACT_FILENAME);
        let metadata_path = tmp
            .path()
            .join(".symforge")
            .join(ARTIFACT_METADATA_FILENAME);
        std::fs::remove_file(&metadata_path).expect("remove sidecar");
        assert!(
            artifact_path.exists(),
            "artifact bytes remain valid — only the sidecar is gone"
        );

        let result = load_snapshot(tmp.path());
        assert!(
            result.is_none(),
            "a valid artifact with a missing sidecar must NOT be silently trusted; \
             content_hash is unverifiable, so import must quarantine and fall back"
        );
        assert!(
            !artifact_path.exists(),
            "unverifiable artifact should be removed from the active path after quarantine"
        );

        let quarantine_dir = paths::resolve_artifact_quarantine_dir(tmp.path());
        let quarantined: Vec<_> = std::fs::read_dir(&quarantine_dir)
            .expect("quarantine dir should exist")
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().and_then(|ext| ext.to_str()) == Some("zst"))
            .collect();
        assert_eq!(
            quarantined.len(),
            1,
            "missing-sidecar artifact should be quarantined under .symforge/quarantine/artifacts/"
        );

        let quarantine_json: Vec<_> = std::fs::read_dir(&quarantine_dir)
            .expect("quarantine dir should exist")
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().and_then(|ext| ext.to_str()) == Some("json"))
            .collect();
        assert_eq!(quarantine_json.len(), 1);
        let metadata: serde_json::Value =
            serde_json::from_slice(&std::fs::read(quarantine_json[0].path()).unwrap()).unwrap();
        assert_eq!(
            metadata["reason"], "missing-sidecar",
            "quarantine metadata must record the missing-sidecar integrity failure"
        );
    }
}