agent-file-tools 0.42.0

Agent File Tools — tree-sitter powered code analysis for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};

use rusqlite::Connection;

use crate::db::backups::BackupRow;
use crate::error::AftError;
use sha2::{Digest, Sha256};

pub const DEFAULT_MAX_UNDO_DEPTH: usize = 20;
#[cfg(test)]
const MAX_UNDO_DEPTH: usize = DEFAULT_MAX_UNDO_DEPTH;
const V2_FORMAT_VERSION: &str = "v2";
const MAX_RESTORE_OPERATION_LOCK_RETRIES: usize = 32;

#[cfg(test)]
type RestoreBeforeLockHook = (String, Box<dyn FnMut(usize) -> bool + Send>);

#[cfg(test)]
static RESTORE_BEFORE_LOCK_HOOK: Mutex<Option<RestoreBeforeLockHook>> = Mutex::new(None);

#[cfg(test)]
fn set_restore_before_lock_hook_for_tests(
    session: &str,
    hook: impl FnMut(usize) -> bool + Send + 'static,
) {
    *RESTORE_BEFORE_LOCK_HOOK.lock().unwrap() = Some((session.to_string(), Box::new(hook)));
}

#[cfg(test)]
fn run_restore_before_lock_hook_for_tests(session: &str, attempt: usize) {
    let mut hook_slot = RESTORE_BEFORE_LOCK_HOOK.lock().unwrap();
    let Some((hook_session, mut hook)) = hook_slot.take() else {
        return;
    };
    if hook_session != session {
        *hook_slot = Some((hook_session, hook));
        return;
    }
    drop(hook_slot);
    let keep_hook = hook(attempt);
    if keep_hook {
        *RESTORE_BEFORE_LOCK_HOOK.lock().unwrap() = Some((hook_session, hook));
    }
}

#[cfg(not(test))]
fn run_restore_before_lock_hook_for_tests(_session: &str, _attempt: usize) {}

/// Current on-disk backup metadata schema version.
///
/// Bump this when the `meta.json` shape changes. Readers check the field and
/// refuse or migrate older versions instead of misinterpreting them.
const SCHEMA_VERSION: u32 = 4;

/// A single backup entry for a file.
#[derive(Debug, Clone)]
pub struct BackupEntry {
    pub backup_id: String,
    /// UTF-8 view of the captured regular-file bytes, kept for API/tests that
    /// inspect text backups. Restore uses `content_bytes` so binary files round-trip.
    pub content: String,
    pub content_bytes: Vec<u8>,
    pub timestamp: u64,
    pub order: u128,
    pub description: String,
    pub op_id: Option<String>,
    pub kind: BackupEntryKind,
    pub mode: Option<u32>,
    pub link_target: Option<PathBuf>,
    pub created_dirs: Vec<PathBuf>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackupEntryKind {
    Content,
    Symlink,
    Tombstone,
}

#[derive(Debug, Clone)]
struct BackupEntryHead {
    order: u128,
    op_id: Option<String>,
}

impl BackupEntryHead {
    fn from_entry(entry: &BackupEntry) -> Self {
        Self {
            order: entry.order,
            op_id: entry.op_id.clone(),
        }
    }

    fn from_row(row: &BackupRow) -> Self {
        Self {
            order: row.order,
            op_id: row.op_id.clone(),
        }
    }
}

impl BackupEntry {
    fn to_backup_row(
        &self,
        harness: &str,
        session_id: &str,
        project_key: &str,
        file_path: &str,
        path_hash: &str,
        backup_path: Option<&str>,
    ) -> BackupRow {
        BackupRow {
            backup_id: self.backup_id.clone(),
            harness: harness.to_string(),
            session_id: session_id.to_string(),
            project_key: project_key.to_string(),
            op_id: self.op_id.clone(),
            order: self.order,
            file_path: file_path.to_string(),
            path_hash: path_hash.to_string(),
            backup_path: backup_path.map(str::to_string),
            kind: match self.kind {
                BackupEntryKind::Content => "content".to_string(),
                BackupEntryKind::Symlink => "symlink".to_string(),
                BackupEntryKind::Tombstone => "tombstone".to_string(),
            },
            description: self.description.clone(),
            created_at: i64::try_from(self.timestamp).unwrap_or(i64::MAX),
            is_tombstone: matches!(self.kind, BackupEntryKind::Tombstone),
        }
    }
}

impl TryFrom<BackupRow> for BackupEntry {
    type Error = std::io::Error;

    fn try_from(row: BackupRow) -> Result<Self, Self::Error> {
        let kind = if row.is_tombstone || row.kind == "tombstone" {
            BackupEntryKind::Tombstone
        } else if row.kind == "symlink" {
            BackupEntryKind::Symlink
        } else {
            BackupEntryKind::Content
        };
        let backup_path = row.backup_path.clone();
        let disk_metadata = backup_path
            .as_deref()
            .and_then(|path| read_entry_disk_metadata(Path::new(path), &row.backup_id));
        let content_bytes = match kind {
            BackupEntryKind::Content | BackupEntryKind::Symlink => {
                let backup_path = backup_path.ok_or_else(|| {
                    std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        format!("backup DB row {} has no backup_path", row.backup_id),
                    )
                })?;
                std::fs::read(backup_path)?
            }
            BackupEntryKind::Tombstone => Vec::new(),
        };
        let link_target = if kind == BackupEntryKind::Symlink {
            disk_metadata
                .as_ref()
                .and_then(|metadata| metadata.link_target.clone())
                .or_else(|| {
                    Some(PathBuf::from(
                        String::from_utf8_lossy(&content_bytes).into_owned(),
                    ))
                })
        } else {
            None
        };
        let content = match kind {
            BackupEntryKind::Content => String::from_utf8_lossy(&content_bytes).into_owned(),
            BackupEntryKind::Symlink => link_target
                .as_ref()
                .map(|target| target.display().to_string())
                .unwrap_or_default(),
            BackupEntryKind::Tombstone => String::new(),
        };

        Ok(BackupEntry {
            backup_id: row.backup_id,
            content,
            content_bytes,
            timestamp: u64::try_from(row.created_at).unwrap_or_default(),
            order: row.order,
            description: row.description,
            op_id: row.op_id,
            kind,
            mode: disk_metadata.as_ref().and_then(|metadata| metadata.mode),
            link_target,
            created_dirs: disk_metadata
                .map(|metadata| metadata.created_dirs)
                .unwrap_or_default(),
        })
    }
}

#[derive(Debug, Clone)]
pub struct RestoredOperation {
    pub op_id: String,
    pub restored: Vec<RestoredFile>,
    pub warnings: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct RestoredFile {
    pub path: PathBuf,
    pub backup_id: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BackupPolicy {
    pub enabled: bool,
    pub max_depth: usize,
    pub max_file_size: Option<u64>,
}

impl Default for BackupPolicy {
    fn default() -> Self {
        Self {
            enabled: true,
            max_depth: DEFAULT_MAX_UNDO_DEPTH,
            max_file_size: None,
        }
    }
}

/// Per-(session, file) undo store with optional disk persistence.
///
/// Introduced alongside project-shared bridges (issue #14): one bridge can now
/// serve many OpenCode sessions in the same project, so undo history must be
/// partitioned by session to keep session A's edits invisible to session B.
///
/// The 20-entry cap is enforced **per (session, file)** deliberately — a global
/// per-file LRU would re-couple sessions and let one busy session evict
/// another's history.
///
/// Disk layout (metadata `format_version` v2):
///   `<storage_dir>/backups/<session_hash>/session.json` — session metadata
///   `<storage_dir>/backups/<session_hash>/<path_hash>/meta.json` — file path + count + session
///   `<storage_dir>/backups/<session_hash>/<path_hash>/bak_<order>_<id>.bak` — append-only content
///
/// Legacy layouts from before sessionization (flat `<path_hash>/` directly under
/// `backups/`) are migrated on first `set_storage_dir` call into the default
/// session namespace.
#[derive(Debug)]
pub struct BackupStore {
    /// session -> path -> entry stack
    entries: HashMap<String, HashMap<PathBuf, Vec<BackupEntry>>>,
    /// session -> path -> disk metadata
    disk_index: HashMap<String, HashMap<PathBuf, DiskMeta>>,
    /// session -> metadata
    session_meta: HashMap<String, SessionMeta>,
    counter: AtomicU64,
    storage_dir: Option<PathBuf>,
    storage_harness: Option<String>,
    db_pool: RwLock<Option<Arc<Mutex<Connection>>>>,
    db_harness: RwLock<Option<String>>,
    db_project_key: RwLock<Option<String>>,
    policy: BackupPolicy,
    #[cfg(test)]
    fail_next_disk_write: bool,
}

#[derive(Debug, Clone)]
struct DiskMeta {
    dir: PathBuf,
    count: usize,
}

#[derive(Debug, Clone, Default)]
struct SessionMeta {
    /// Unix timestamp of last read/write activity in this session namespace.
    /// Maintained in-memory now, reserved for future inactivity-TTL cleanup.
    last_accessed: u64,
}

impl BackupStore {
    pub fn new() -> Self {
        BackupStore {
            entries: HashMap::new(),
            disk_index: HashMap::new(),
            session_meta: HashMap::new(),
            counter: AtomicU64::new(0),
            storage_dir: None,
            storage_harness: None,
            db_pool: RwLock::new(None),
            db_harness: RwLock::new(None),
            db_project_key: RwLock::new(None),
            policy: BackupPolicy::default(),
            #[cfg(test)]
            fail_next_disk_write: false,
        }
    }

    pub fn set_policy(&mut self, policy: BackupPolicy) {
        let old_policy = self.policy;
        self.policy = policy;

        let failed_disk_prunes = if policy.max_depth < old_policy.max_depth {
            self.prune_disk_stacks_to_depth(policy.max_depth)
        } else {
            HashSet::new()
        };

        for (session, files) in &mut self.entries {
            for (key, stack) in files {
                if failed_disk_prunes.contains(&(session.clone(), key.clone())) {
                    continue;
                }
                trim_stack_to_depth(stack, self.policy.max_depth);
            }
        }
        self.entries.retain(|_, files| {
            files.retain(|_, stack| !stack.is_empty());
            !files.is_empty()
        });
    }

    pub fn policy(&self) -> BackupPolicy {
        self.policy
    }

    #[cfg(test)]
    fn fail_next_disk_write_for_tests(&mut self) {
        self.fail_next_disk_write = true;
    }

    pub fn set_db_pool(&self, conn: Arc<Mutex<Connection>>) {
        if let Ok(mut slot) = self.db_pool.write() {
            *slot = Some(conn);
        }
    }

    pub fn clear_db_pool(&self) {
        if let Ok(mut slot) = self.db_pool.write() {
            *slot = None;
        }
    }

    pub fn set_db_harness(&self, harness: crate::harness::Harness) {
        if let Ok(mut slot) = self.db_harness.write() {
            *slot = Some(harness.storage_segment());
        }
    }

    pub fn set_db_project_key(&self, project_key: String) {
        if let Ok(mut slot) = self.db_project_key.write() {
            *slot = Some(project_key);
        }
    }

    /// Set storage directory for disk persistence (called during configure).
    ///
    /// Loads the disk index for all session namespaces, removes stale session
    /// directories, and migrates any legacy pre-session (flat) layout into the
    /// default namespace.
    pub fn set_storage_dir(&mut self, dir: PathBuf, ttl_hours: u32) {
        self.set_storage_dir_inner(dir, None, ttl_hours);
    }

    pub fn set_storage_dir_for_harness(
        &mut self,
        dir: PathBuf,
        harness: crate::harness::Harness,
        ttl_hours: u32,
    ) {
        self.set_storage_dir_inner(dir, Some(harness.storage_segment()), ttl_hours);
    }

    fn set_storage_dir_inner(&mut self, dir: PathBuf, harness: Option<String>, ttl_hours: u32) {
        self.storage_dir = Some(dir);
        self.storage_harness = harness;
        self.entries.clear();
        self.disk_index.clear();
        self.session_meta.clear();
        self.repair_root_backups_if_needed();
        self.gc_stale_sessions(ttl_hours);
        self.migrate_legacy_layout_if_needed();
        self.load_disk_index();
    }

    /// Snapshot the current contents of `path` under the given session namespace.
    pub fn snapshot(
        &mut self,
        session: &str,
        path: &Path,
        description: &str,
    ) -> Result<Option<String>, AftError> {
        self.snapshot_with_op(session, path, description, None)
    }

    /// Snapshot the current contents of `path` under the given session namespace,
    /// optionally tagging it with an operation id shared by all files touched by
    /// one mutating tool call.
    pub fn snapshot_with_op(
        &mut self,
        session: &str,
        path: &Path,
        description: &str,
        op_id: Option<&str>,
    ) -> Result<Option<String>, AftError> {
        if !self.should_snapshot_path(path)? {
            return Ok(None);
        }
        let key = canonicalize_key(path);
        let _disk_lock = self.acquire_stack_disk_lock(session, &key)?;
        // Hydrate any prior on-disk history before appending, so a snapshot
        // taken on a fresh store (post-restart) extends the existing stack and
        // advances the id counter instead of overwriting history with a single
        // entry and reusing backup-0.
        self.ensure_stack_hydrated_locked(session, &key)?;
        let (id, order) = self.next_id_and_order();
        let entry = backup_entry_from_path(path, id.clone(), order, description, op_id)?;

        let max_depth = self.policy.max_depth;
        let pre_mutation_stack = self
            .entries
            .get(session)
            .and_then(|files| files.get(&key))
            .cloned();
        let session_entries = self.entries.entry(session.to_string()).or_default();
        let stack = session_entries.entry(key.clone()).or_default();
        trim_stack_to_depth(stack, max_depth.saturating_sub(1));
        stack.push(entry);
        trim_stack_to_depth(stack, max_depth);

        // Persist to disk
        let stack_clone = stack.clone();
        if let Err(error) = self.write_snapshot_to_disk_locked(session, &key, &stack_clone) {
            self.restore_in_memory_stack(session, &key, pre_mutation_stack);
            return Err(error);
        }
        self.touch_session(session);

        Ok(Some(id))
    }

    /// Record that `path` was created by the operation and should be removed
    /// if that operation is undone. No file content is captured.
    pub fn snapshot_op_tombstone(
        &mut self,
        session: &str,
        op_id: &str,
        path: &Path,
        description: &str,
    ) -> Result<Option<String>, AftError> {
        if !self.policy.enabled {
            return Ok(None);
        }
        let key = canonicalize_key(path);
        let _disk_lock = self.acquire_stack_disk_lock(session, &key)?;
        self.ensure_stack_hydrated_locked(session, &key)?;
        let created_dirs = path.parent().map(missing_parent_dirs).unwrap_or_default();
        let (id, order) = self.next_id_and_order();
        let entry = BackupEntry {
            backup_id: id.clone(),
            content: String::new(),
            content_bytes: Vec::new(),
            timestamp: current_timestamp(),
            order,
            description: description.to_string(),
            op_id: Some(op_id.to_string()),
            kind: BackupEntryKind::Tombstone,
            mode: None,
            link_target: None,
            created_dirs,
        };

        let max_depth = self.policy.max_depth;
        let pre_mutation_stack = self
            .entries
            .get(session)
            .and_then(|files| files.get(&key))
            .cloned();
        let session_entries = self.entries.entry(session.to_string()).or_default();
        let stack = session_entries.entry(key.clone()).or_default();
        trim_stack_to_depth(stack, max_depth.saturating_sub(1));
        stack.push(entry);
        trim_stack_to_depth(stack, max_depth);

        let stack_clone = stack.clone();
        if let Err(error) = self.write_snapshot_to_disk_locked(session, &key, &stack_clone) {
            self.restore_in_memory_stack(session, &key, pre_mutation_stack);
            return Err(error);
        }
        self.touch_session(session);

        Ok(Some(id))
    }

    /// Restore every top-of-stack backup entry belonging to the most recent
    /// operation in this session.
    pub fn restore_last_operation(&mut self, session: &str) -> Result<RestoredOperation, AftError> {
        let mut candidate_keys = self.restore_operation_candidate_keys(session)?;
        if candidate_keys.is_empty() {
            self.load_latest_operation_from_db_or_log(session);
            candidate_keys = self.restore_operation_candidate_keys(session)?;
        }

        for attempt in 0..MAX_RESTORE_OPERATION_LOCK_RETRIES {
            if candidate_keys.is_empty() {
                return Err(AftError::NoUndoHistory {
                    path: "operation".to_string(),
                });
            }

            run_restore_before_lock_hook_for_tests(session, attempt);

            let disk_locks = self.acquire_stack_disk_locks(session, &candidate_keys)?;
            let locked_keys: HashSet<PathBuf> = candidate_keys.iter().cloned().collect();
            let current_keys = self.restore_operation_candidate_keys(session)?;
            let current_key_set: HashSet<PathBuf> = current_keys.iter().cloned().collect();
            if !current_key_set.is_subset(&locked_keys) {
                drop(disk_locks);
                candidate_keys.extend(current_key_set);
                candidate_keys.sort();
                candidate_keys.dedup();
                continue;
            }

            for key in &current_keys {
                self.load_from_disk_if_needed_locked(session, key)?;
            }

            if !self.has_in_memory_entries(session) {
                self.load_latest_operation_from_db_or_log(session);
            }

            let Some(op_id) = self.latest_operation_id_from_memory(session) else {
                return Err(AftError::NoUndoHistory {
                    path: "operation".to_string(),
                });
            };

            let keys_to_restore = self.operation_keys_for_top_op(session, &op_id);
            if keys_to_restore.is_empty() {
                return Err(AftError::NoUndoHistory {
                    path: "operation".to_string(),
                });
            }
            if !keys_to_restore.iter().all(|key| locked_keys.contains(key)) {
                drop(disk_locks);
                candidate_keys.extend(keys_to_restore);
                candidate_keys.sort();
                candidate_keys.dedup();
                continue;
            }

            let mut content_targets = Vec::new();
            let mut tombstone_targets = Vec::new();
            for key in &keys_to_restore {
                let entry = self
                    .entries
                    .get(session)
                    .and_then(|files| files.get(key))
                    .and_then(|stack| stack.last())
                    .cloned()
                    .ok_or_else(|| AftError::NoUndoHistory {
                        path: key.display().to_string(),
                    })?;
                match entry.kind {
                    BackupEntryKind::Content | BackupEntryKind::Symlink => {
                        let existing_state = capture_path_state(key)?;
                        let warning = self.check_external_modification(session, key, key);
                        content_targets.push((key.clone(), entry, warning, existing_state));
                    }
                    BackupEntryKind::Tombstone => {
                        let existing_state = capture_path_state(key)?;
                        tombstone_targets.push((key.clone(), entry, existing_state));
                    }
                }
            }

            let mut created_dirs = Vec::new();
            for (key, _, _, _) in &content_targets {
                if let Some(parent) = key.parent() {
                    if !parent.as_os_str().is_empty() {
                        let missing_dirs = missing_parent_dirs(parent);
                        if let Err(e) = std::fs::create_dir_all(parent) {
                            let mut dirs_to_remove = created_dirs;
                            dirs_to_remove.extend(missing_dirs);
                            let rollback_ok = rollback_created_dirs(&dirs_to_remove);
                            return Err(AftError::IoError {
                                path: parent.display().to_string(),
                                message: format!(
                                    "{}; restore_last_operation aborted; partial_rollback: {}; rollback_succeeded: {}",
                                    e,
                                    !rollback_ok,
                                    rollback_ok
                                ),
                            });
                        }
                        created_dirs.extend(missing_dirs);
                    }
                }
            }

            let mut written = Vec::new();
            for (key, entry, _, existing_state) in &content_targets {
                if let Err(e) = restore_entry_to_path(key, entry) {
                    let files_rollback_ok =
                        rollback_transactional_restore(&written, Some((key, existing_state)));
                    let dirs_rollback_ok = rollback_created_dirs(&created_dirs);
                    let rollback_ok = files_rollback_ok && dirs_rollback_ok;
                    return Err(AftError::IoError {
                        path: key.display().to_string(),
                        message: format!(
                            "{}; restore_last_operation aborted; partial_rollback: {}; rollback_succeeded: {}",
                            e,
                            !rollback_ok,
                            rollback_ok
                        ),
                    });
                }
                written.push((key.clone(), existing_state.clone()));
            }

            let mut deleted_tombstones = Vec::new();
            for (key, _, existing_state) in &tombstone_targets {
                match remove_tombstone_path(key) {
                    Ok(()) => deleted_tombstones.push((key.clone(), existing_state.clone())),
                    Err(e) => {
                        let files_rollback_ok = rollback_transactional_restore(&written, None);
                        let tombstone_rollback_ok =
                            rollback_deleted_tombstones(&deleted_tombstones);
                        let dirs_rollback_ok = rollback_created_dirs(&created_dirs);
                        let rollback_ok =
                            files_rollback_ok && tombstone_rollback_ok && dirs_rollback_ok;
                        return Err(AftError::IoError {
                            path: key.display().to_string(),
                            message: format!(
                                "{}; restore_last_operation aborted; partial_rollback: {}; rollback_succeeded: {}",
                                e,
                                !rollback_ok,
                                rollback_ok
                            ),
                        });
                    }
                }
            }
            let tombstone_created_dirs = tombstone_targets
                .iter()
                .flat_map(|(_, entry, _)| entry.created_dirs.iter().cloned())
                .collect::<Vec<_>>();
            remove_created_dirs_best_effort(&tombstone_created_dirs);

            let mut restored = Vec::new();
            let mut warnings = Vec::new();
            for (key, entry, warning, _) in content_targets {
                self.commit_restored_backup_locked(session, &key)?;
                if let Some(warning) = warning {
                    warnings.push(format!("{}: {}", key.display(), warning));
                }
                restored.push(RestoredFile {
                    path: key,
                    backup_id: entry.backup_id,
                });
            }
            for (key, _, _) in tombstone_targets {
                self.commit_restored_backup_locked(session, &key)?;
            }
            self.touch_session(session);
            drop(disk_locks);

            return Ok(RestoredOperation {
                op_id,
                restored,
                warnings,
            });
        }

        Err(AftError::IoError {
            path: "operation".to_string(),
            message: "backup stack changing under concurrent activity; retry".to_string(),
        })
    }

    /// Pop the most recent backup for `(session, path)` and restore the file.
    /// Returns `(entry, optional_warning)`.
    pub fn restore_latest(
        &mut self,
        session: &str,
        path: &Path,
    ) -> Result<(BackupEntry, Option<String>), AftError> {
        let key = canonicalize_key(path);
        let _disk_lock = self.acquire_stack_disk_lock(session, &key)?;

        match self.read_stack_from_disk_unlocked(session, &key) {
            Ok(Some(entries)) if !entries.is_empty() => {
                self.update_counter_from_entries(&entries);
                self.entries
                    .entry(session.to_string())
                    .or_default()
                    .insert(key.to_path_buf(), entries);
            }
            Ok(_) => {
                if self.session_dir(session).is_some() {
                    self.restore_in_memory_stack(session, &key, None);
                }
            }
            Err(error) => {
                return Err(AftError::IoError {
                    path: key.display().to_string(),
                    message: error,
                });
            }
        }

        if self
            .entries
            .get(session)
            .and_then(|s| s.get(&key))
            .is_none_or(|s| s.is_empty())
        {
            match self.load_from_db_if_present(session, &key) {
                Some(Ok(true)) => {}
                Some(Ok(false)) => {
                    crate::slog_info!(
                        "backup DB miss for session {} path {}; disk meta is authoritative",
                        session,
                        key.display()
                    );
                }
                Some(Err(error)) => {
                    crate::slog_warn!(
                        "backup DB lookup failed for session {} path {}: {}",
                        session,
                        key.display(),
                        error
                    );
                }
                None => {
                    crate::slog_info!(
                        "backup DB unavailable for session {} path {}",
                        session,
                        key.display()
                    );
                }
            }
        }

        // Try memory first
        let in_memory = self
            .entries
            .get(session)
            .and_then(|s| s.get(&key))
            .map_or(false, |s| !s.is_empty());
        if in_memory {
            let warning = self.check_external_modification(session, &key, path);
            let result = self
                .do_restore_locked(session, &key, path)
                .map(|(entry, _)| (entry, warning));
            if result.is_ok() {
                self.touch_session(session);
            }
            return result;
        }

        Err(AftError::NoUndoHistory {
            path: path.display().to_string(),
        })
    }

    /// Return the backup history for `(session, path)` (oldest first).
    pub fn history(&self, session: &str, path: &Path) -> Vec<BackupEntry> {
        let key = canonicalize_key(path);
        let _disk_lock = match self.acquire_stack_disk_lock(session, &key) {
            Ok(lock) => lock,
            Err(error) => {
                crate::slog_warn!(
                    "backup disk read lock failed for {}: {}",
                    key.display(),
                    error
                );
                return Vec::new();
            }
        };

        match self.read_stack_from_disk_unlocked(session, &key) {
            Ok(Some(stack)) if !stack.is_empty() => return stack,
            Ok(_) => {}
            Err(error) => {
                crate::slog_warn!("backup disk read failed for {}: {}", key.display(), error);
                return Vec::new();
            }
        }

        if let Some(stack) = self.entries.get(session).and_then(|s| s.get(&key)).cloned() {
            if !stack.is_empty() {
                return stack;
            }
        }

        match self.read_stack_from_db(session, &key) {
            Some(Ok(stack)) if !stack.is_empty() => stack,
            Some(Ok(_)) => Vec::new(),
            Some(Err(error)) => {
                crate::slog_warn!(
                    "backup history DB lookup failed for session {} path {}: {}",
                    session,
                    key.display(),
                    error
                );
                Vec::new()
            }
            None => Vec::new(),
        }
    }

    /// Return the number of on-disk backup entries for `(session, file)`.
    pub fn disk_history_count(&self, session: &str, path: &Path) -> usize {
        let key = canonicalize_key(path);
        self.disk_index
            .get(session)
            .and_then(|s| s.get(&key))
            .map(|m| m.count)
            .unwrap_or(0)
    }

    /// Return all files that have at least one backup entry in this session
    /// (memory + disk). Other sessions' files are not visible.
    pub fn tracked_files(&self, session: &str) -> Vec<PathBuf> {
        let mut files: std::collections::HashSet<PathBuf> = self
            .entries
            .get(session)
            .map(|s| s.keys().cloned().collect())
            .unwrap_or_default();
        if let Some(disk) = self.disk_index.get(session) {
            for key in disk.keys() {
                files.insert(key.clone());
            }
        }
        files.into_iter().collect()
    }

    /// Preview the file path that `restore_latest` would write for `(session, path)`.
    ///
    /// This is intentionally read-only: it inspects DB/disk/in-memory backup metadata
    /// without popping the undo stack or writing restored file contents.
    pub fn preview_latest_path(&self, session: &str, path: &Path) -> Result<PathBuf, AftError> {
        let key = canonicalize_key(path);
        if self.latest_head_for_key(session, &key).is_some() {
            Ok(key)
        } else {
            Err(AftError::NoUndoHistory {
                path: path.display().to_string(),
            })
        }
    }

    /// Preview the paths that `restore_last_operation` would touch for `session`.
    ///
    /// This mirrors the operation selection logic used by restore, but only reads
    /// backup metadata. It includes tombstone targets because undoing a create
    /// operation deletes those paths and therefore still requires write permission.
    pub fn preview_last_operation_paths(&self, session: &str) -> Result<Vec<PathBuf>, AftError> {
        let mut heads_by_path: HashMap<PathBuf, BackupEntryHead> = self
            .entries
            .get(session)
            .map(|files| {
                files
                    .iter()
                    .filter_map(|(key, stack)| {
                        stack
                            .last()
                            .map(|entry| (key.clone(), BackupEntryHead::from_entry(entry)))
                    })
                    .collect()
            })
            .unwrap_or_default();

        match self.read_latest_operation_heads_from_db(session) {
            Some(Ok(db_heads)) if !db_heads.is_empty() => {
                for (key, head) in db_heads {
                    heads_by_path.insert(key, head);
                }
                self.merge_disk_stack_heads(session, &mut heads_by_path);
            }
            Some(Ok(_)) => {
                crate::slog_info!(
                    "backup latest operation preview DB miss for session {}; falling back to disk",
                    session
                );
                self.merge_disk_stack_heads(session, &mut heads_by_path);
            }
            Some(Err(error)) => {
                crate::slog_warn!(
                    "backup latest operation preview DB lookup failed for session {}; falling back to disk: {}",
                    session,
                    error
                );
                self.merge_disk_stack_heads(session, &mut heads_by_path);
            }
            None => {
                crate::slog_info!(
                    "backup latest operation preview DB unavailable for session {}; falling back to disk",
                    session
                );
                self.merge_disk_stack_heads(session, &mut heads_by_path);
            }
        }

        let mut latest: Option<(u128, String)> = None;
        for head in heads_by_path.values() {
            if let Some(op_id) = &head.op_id {
                if latest
                    .as_ref()
                    .map_or(true, |(latest_order, _)| head.order > *latest_order)
                {
                    latest = Some((head.order, op_id.clone()));
                }
            }
        }

        let Some((_, op_id)) = latest else {
            return Err(AftError::NoUndoHistory {
                path: "operation".to_string(),
            });
        };

        let mut paths: Vec<PathBuf> = heads_by_path
            .into_iter()
            .filter_map(|(key, head)| {
                (head.op_id.as_deref() == Some(op_id.as_str())).then_some(key)
            })
            .collect();
        paths.sort();

        if paths.is_empty() {
            Err(AftError::NoUndoHistory {
                path: "operation".to_string(),
            })
        } else {
            Ok(paths)
        }
    }

    /// Return all session namespaces that currently have any backup state
    /// (memory or disk). Exposed for `/aft-status` aggregate reporting.
    pub fn sessions_with_backups(&self) -> Vec<String> {
        let mut sessions: std::collections::HashSet<String> =
            self.entries.keys().cloned().collect();
        for s in self.disk_index.keys() {
            sessions.insert(s.clone());
        }
        sessions.into_iter().collect()
    }

    /// Total on-disk bytes across all sessions (best-effort, reads metadata only).
    /// Used by `/aft-status` to surface storage footprint.
    pub fn total_disk_bytes(&self) -> u64 {
        let mut total = 0u64;
        for session_dirs in self.disk_index.values() {
            for meta in session_dirs.values() {
                if let Ok(read_dir) = std::fs::read_dir(&meta.dir) {
                    for entry in read_dir.flatten() {
                        if let Ok(m) = entry.metadata() {
                            if m.is_file() {
                                total += m.len();
                            }
                        }
                    }
                }
            }
        }
        total
    }

    fn next_id_and_order(&self) -> (String, u128) {
        let n = self.counter.fetch_add(1, Ordering::Relaxed);
        let order = ((current_timestamp_nanos() as u128) << 32) | u128::from(n);
        (format!("backup-{}", n), order)
    }

    fn db_pool_and_harness(&self) -> Option<(Arc<Mutex<Connection>>, String)> {
        let pool = self.db_pool.read().ok().and_then(|slot| slot.clone())?;
        let harness = self.db_harness.read().ok().and_then(|slot| slot.clone())?;
        Some((pool, harness))
    }

    fn latest_head_for_key(&self, session: &str, key: &Path) -> Option<BackupEntryHead> {
        self.entries
            .get(session)
            .and_then(|files| files.get(key))
            .and_then(|stack| stack.last())
            .map(BackupEntryHead::from_entry)
            .or_else(|| {
                self.read_stack_heads_from_disk(session, key)
                    .and_then(|stack| stack.last().cloned())
            })
            .or_else(|| match self.read_stack_heads_from_db(session, key) {
                Some(Ok(stack)) if !stack.is_empty() => stack.last().cloned(),
                Some(Err(error)) => {
                    crate::slog_warn!(
                        "backup preview DB lookup failed for session {} path {}: {}",
                        session,
                        key.display(),
                        error
                    );
                    None
                }
                _ => None,
            })
    }

    fn merge_disk_stack_heads(
        &self,
        session: &str,
        heads_by_path: &mut HashMap<PathBuf, BackupEntryHead>,
    ) {
        let disk_keys: Vec<PathBuf> = self
            .disk_index
            .get(session)
            .map(|files| files.keys().cloned().collect())
            .unwrap_or_default();
        for key in disk_keys {
            if let Some(head) = self
                .read_stack_heads_from_disk(session, &key)
                .and_then(|stack| stack.last().cloned())
            {
                heads_by_path.insert(key, head);
            }
        }
    }

    fn read_stack_heads_from_db(
        &self,
        session: &str,
        key: &Path,
    ) -> Option<Result<Vec<BackupEntryHead>, String>> {
        let (pool, harness) = self.db_pool_and_harness()?;
        let conn = match pool.lock() {
            Ok(conn) => conn,
            Err(_) => return Some(Err("db mutex poisoned".to_string())),
        };
        let path_hash = Self::path_hash(key);
        Some(
            crate::db::backups::list_backups(&conn, &harness, session, &path_hash)
                .map_err(|error| error.to_string())
                .map(|rows| {
                    rows.iter()
                        .map(BackupEntryHead::from_row)
                        .collect::<Vec<_>>()
                }),
        )
    }

    fn read_latest_operation_heads_from_db(
        &self,
        session: &str,
    ) -> Option<Result<HashMap<PathBuf, BackupEntryHead>, String>> {
        let (pool, harness) = self.db_pool_and_harness()?;
        let conn = match pool.lock() {
            Ok(conn) => conn,
            Err(_) => return Some(Err("db mutex poisoned".to_string())),
        };
        let latest = match crate::db::backups::get_latest_operation_backup(&conn, &harness, session)
        {
            Ok(Some(row)) => row,
            Ok(None) => return Some(Ok(HashMap::new())),
            Err(error) => return Some(Err(error.to_string())),
        };
        let Some(op_id) = latest.op_id else {
            return Some(Ok(HashMap::new()));
        };
        let rows = match crate::db::backups::list_backups_by_op(&conn, &harness, session, &op_id) {
            Ok(rows) => rows,
            Err(error) => return Some(Err(error.to_string())),
        };
        if rows.is_empty() {
            return Some(Ok(HashMap::new()));
        }
        let path_hashes: std::collections::HashSet<String> =
            rows.into_iter().map(|row| row.path_hash).collect();
        drop(conn);

        let mut heads = HashMap::new();
        for path_hash in path_hashes {
            let conn = match pool.lock() {
                Ok(conn) => conn,
                Err(_) => return Some(Err("db mutex poisoned".to_string())),
            };
            let rows = match crate::db::backups::list_backups(&conn, &harness, session, &path_hash)
            {
                Ok(rows) => rows,
                Err(error) => return Some(Err(error.to_string())),
            };
            drop(conn);

            let Some(file_path) = rows.first().map(|row| row.file_path.clone()) else {
                continue;
            };
            let Some(head) = rows.last().map(BackupEntryHead::from_row) else {
                continue;
            };
            heads.insert(PathBuf::from(file_path), head);
        }

        Some(Ok(heads))
    }

    fn read_stack_from_db(
        &self,
        session: &str,
        key: &Path,
    ) -> Option<Result<Vec<BackupEntry>, String>> {
        let (pool, harness) = self.db_pool_and_harness()?;
        let conn = match pool.lock() {
            Ok(conn) => conn,
            Err(_) => return Some(Err("db mutex poisoned".to_string())),
        };
        let path_hash = Self::path_hash(key);
        Some(
            crate::db::backups::list_backups(&conn, &harness, session, &path_hash)
                .map_err(|error| error.to_string())
                .and_then(|rows| {
                    rows.into_iter()
                        .map(|row| self.backup_entry_from_db_row(row))
                        .collect::<Result<Vec<_>, _>>()
                        .map_err(|error| error.to_string())
                }),
        )
    }

    fn load_from_db_if_present(
        &mut self,
        session: &str,
        key: &Path,
    ) -> Option<Result<bool, String>> {
        match self.read_stack_from_db(session, key) {
            Some(Ok(stack)) if !stack.is_empty() => {
                self.update_counter_from_entries(&stack);
                self.entries
                    .entry(session.to_string())
                    .or_default()
                    .insert(key.to_path_buf(), stack);
                Some(Ok(true))
            }
            Some(Ok(_)) => Some(Ok(false)),
            Some(Err(error)) => Some(Err(error)),
            None => None,
        }
    }

    fn load_latest_operation_from_db(&mut self, session: &str) -> Option<Result<bool, String>> {
        let (pool, harness) = self.db_pool_and_harness()?;
        let conn = match pool.lock() {
            Ok(conn) => conn,
            Err(_) => return Some(Err("db mutex poisoned".to_string())),
        };
        let latest = match crate::db::backups::get_latest_operation_backup(&conn, &harness, session)
        {
            Ok(Some(row)) => row,
            Ok(None) => return Some(Ok(false)),
            Err(error) => return Some(Err(error.to_string())),
        };
        let Some(op_id) = latest.op_id else {
            return Some(Ok(false));
        };
        let rows = match crate::db::backups::list_backups_by_op(&conn, &harness, session, &op_id) {
            Ok(rows) => rows,
            Err(error) => return Some(Err(error.to_string())),
        };
        if rows.is_empty() {
            return Some(Ok(false));
        }
        let path_hashes: std::collections::HashSet<String> =
            rows.into_iter().map(|row| row.path_hash).collect();
        drop(conn);

        let mut loaded_any = false;
        for path_hash in path_hashes {
            let conn = match pool.lock() {
                Ok(conn) => conn,
                Err(_) => return Some(Err("db mutex poisoned".to_string())),
            };
            let loaded =
                match crate::db::backups::list_backups(&conn, &harness, session, &path_hash) {
                    Ok(rows) => {
                        let file_path = rows.first().map(|row| row.file_path.clone());
                        rows.into_iter()
                            .map(|row| self.backup_entry_from_db_row(row))
                            .collect::<Result<Vec<_>, _>>()
                            .map(|stack| (file_path, stack))
                            .map_err(|error| error.to_string())
                    }
                    Err(error) => Err(error.to_string()),
                };
            drop(conn);
            let (file_path, stack) = match loaded {
                Ok((file_path, stack)) if !stack.is_empty() => (file_path, stack),
                Ok(_) => continue,
                Err(error) => return Some(Err(error)),
            };
            let Some(file_path) = file_path else {
                return Some(Err(format!(
                    "backup DB rows for path hash {path_hash} have no file path"
                )));
            };
            let key = PathBuf::from(file_path);
            self.update_counter_from_entries(&stack);
            self.entries
                .entry(session.to_string())
                .or_default()
                .insert(key, stack);
            loaded_any = true;
        }

        Some(Ok(loaded_any))
    }

    fn update_counter_from_entries(&self, entries: &[BackupEntry]) {
        if let Some(next_counter) = entries
            .iter()
            .filter_map(|entry| backup_sequence(&entry.backup_id))
            .max()
            .and_then(|max| max.checked_add(1))
        {
            let _ = self
                .counter
                .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                    (current < next_counter).then_some(next_counter)
                });
        }
    }

    fn restore_in_memory_stack(
        &mut self,
        session: &str,
        key: &Path,
        stack: Option<Vec<BackupEntry>>,
    ) {
        match stack {
            Some(stack) if !stack.is_empty() => {
                self.entries
                    .entry(session.to_string())
                    .or_default()
                    .insert(key.to_path_buf(), stack);
            }
            _ => {
                if let Some(files) = self.entries.get_mut(session) {
                    files.remove(key);
                    if files.is_empty() {
                        self.entries.remove(session);
                    }
                }
            }
        }
    }

    fn has_in_memory_entries(&self, session: &str) -> bool {
        self.entries
            .get(session)
            .is_some_and(|files| files.values().any(|stack| !stack.is_empty()))
    }

    fn latest_operation_id_from_memory(&self, session: &str) -> Option<String> {
        let mut latest: Option<(u128, String)> = None;
        if let Some(files) = self.entries.get(session) {
            for stack in files.values() {
                if let Some(entry) = stack.last() {
                    if let Some(op_id) = &entry.op_id {
                        if latest
                            .as_ref()
                            .is_none_or(|(latest_order, _)| entry.order > *latest_order)
                        {
                            latest = Some((entry.order, op_id.clone()));
                        }
                    }
                }
            }
        }
        latest.map(|(_, op_id)| op_id)
    }

    fn operation_keys_for_top_op(&self, session: &str, op_id: &str) -> Vec<PathBuf> {
        let mut keys: Vec<PathBuf> = self
            .entries
            .get(session)
            .map(|files| {
                files
                    .iter()
                    .filter_map(|(key, stack)| {
                        stack.last().and_then(|entry| {
                            (entry.op_id.as_deref() == Some(op_id)).then(|| key.clone())
                        })
                    })
                    .collect()
            })
            .unwrap_or_default();
        keys.sort();
        keys
    }

    fn load_latest_operation_from_db_or_log(&mut self, session: &str) {
        match self.load_latest_operation_from_db(session) {
            Some(Ok(true)) => {}
            Some(Ok(false)) => {
                crate::slog_info!(
                    "backup latest operation DB miss for session {}; disk meta is authoritative",
                    session
                );
            }
            Some(Err(error)) => {
                crate::slog_warn!(
                    "backup latest operation DB lookup failed for session {}: {}",
                    session,
                    error
                );
            }
            None => {
                crate::slog_info!(
                    "backup latest operation DB unavailable for session {}",
                    session
                );
            }
        }
    }

    fn resolve_db_backup_row_path(&self, mut row: BackupRow) -> BackupRow {
        if let Some(backup_path) = row.backup_path.clone() {
            let path = PathBuf::from(&backup_path);
            if path.is_relative() {
                if let Some(session_dir) = self.session_dir(&row.session_id) {
                    row.backup_path = Some(
                        session_dir
                            .join(&row.path_hash)
                            .join(path)
                            .display()
                            .to_string(),
                    );
                }
            }
        }
        row
    }

    fn backup_entry_from_db_row(&self, row: BackupRow) -> Result<BackupEntry, std::io::Error> {
        BackupEntry::try_from(self.resolve_db_backup_row_path(row))
    }

    pub fn discard_operation_entries(&mut self, session: &str, op_id: &str) {
        let keys: Vec<PathBuf> = self
            .entries
            .get(session)
            .map(|files| files.keys().cloned().collect())
            .unwrap_or_default();

        for key in keys {
            let mut remove_key = false;
            let mut remaining_stack = None;
            if let Some(session_entries) = self.entries.get_mut(session) {
                if let Some(stack) = session_entries.get_mut(&key) {
                    while stack
                        .last()
                        .is_some_and(|entry| entry.op_id.as_deref() == Some(op_id))
                    {
                        stack.pop();
                    }
                    if stack.is_empty() {
                        remove_key = true;
                    } else {
                        remaining_stack = Some(stack.clone());
                    }
                }
                if remove_key {
                    session_entries.remove(&key);
                }
            }

            if remove_key {
                if let Err(error) = self.remove_disk_backups(session, &key) {
                    crate::slog_warn!(
                        "failed to remove backup stack for {} during operation discard: {}",
                        key.display(),
                        error
                    );
                }
            } else if let Some(stack) = remaining_stack {
                if let Err(error) = self.write_snapshot_to_disk(session, &key, &stack) {
                    crate::slog_warn!(
                        "failed to persist backup stack for {} during operation discard: {}",
                        key.display(),
                        error
                    );
                }
            }
        }

        if self
            .entries
            .get(session)
            .is_some_and(|session_entries| session_entries.is_empty())
        {
            self.entries.remove(session);
        }
    }

    fn touch_session(&mut self, session: &str) {
        let now = current_timestamp();
        self.session_meta
            .entry(session.to_string())
            .or_default()
            .last_accessed = now;
        self.write_session_marker(session, now);
    }

    // ---- Internal helpers ----

    fn do_restore_locked(
        &mut self,
        session: &str,
        key: &Path,
        path: &Path,
    ) -> Result<(BackupEntry, Option<String>), AftError> {
        let session_entries =
            self.entries
                .get_mut(session)
                .ok_or_else(|| AftError::NoUndoHistory {
                    path: path.display().to_string(),
                })?;
        let stack = session_entries
            .get_mut(key)
            .ok_or_else(|| AftError::NoUndoHistory {
                path: path.display().to_string(),
            })?;

        let entry = stack
            .last()
            .cloned()
            .ok_or_else(|| AftError::NoUndoHistory {
                path: path.display().to_string(),
            })?;

        match entry.kind {
            BackupEntryKind::Content | BackupEntryKind::Symlink => {
                restore_entry_to_path(path, &entry).map_err(|e| AftError::IoError {
                    path: path.display().to_string(),
                    message: e.to_string(),
                })?;
            }
            BackupEntryKind::Tombstone => {
                remove_tombstone_path(path).map_err(|e| AftError::IoError {
                    path: path.display().to_string(),
                    message: e.to_string(),
                })?;
                remove_created_dirs_best_effort(&entry.created_dirs);
            }
        }

        stack.pop();
        if stack.is_empty() {
            session_entries.remove(key);
            // Also prune the session map when its last file is gone.
            if session_entries.is_empty() {
                self.entries.remove(session);
            }
            self.remove_disk_backups_locked(session, key)?;
        } else {
            let stack_clone = self
                .entries
                .get(session)
                .and_then(|s| s.get(key))
                .cloned()
                .unwrap_or_default();
            self.write_snapshot_to_disk_locked(session, key, &stack_clone)?;
        }

        Ok((entry, None))
    }

    fn commit_restored_backup_locked(&mut self, session: &str, key: &Path) -> Result<(), AftError> {
        let mut remove_key = false;
        let mut remove_session = false;
        let mut remaining_stack = None;

        if let Some(session_entries) = self.entries.get_mut(session) {
            if let Some(stack) = session_entries.get_mut(key) {
                stack.pop();
                if stack.is_empty() {
                    remove_key = true;
                } else {
                    remaining_stack = Some(stack.clone());
                }
            }

            if remove_key {
                session_entries.remove(key);
                remove_session = session_entries.is_empty();
            }
        }

        if remove_session {
            self.entries.remove(session);
        }

        if remove_key {
            self.remove_disk_backups_locked(session, key)?;
        } else if let Some(stack) = remaining_stack {
            self.write_snapshot_to_disk_locked(session, key, &stack)?;
        }

        Ok(())
    }

    fn check_external_modification(
        &self,
        session: &str,
        key: &Path,
        path: &Path,
    ) -> Option<String> {
        let stack = self.entries.get(session).and_then(|s| s.get(key))?;
        let latest = stack.last()?;
        let modified = match latest.kind {
            BackupEntryKind::Content => std::fs::read(path)
                .map(|current| current != latest.content_bytes)
                .unwrap_or(true),
            BackupEntryKind::Symlink => std::fs::read_link(path)
                .map(|target| latest.link_target.as_ref() != Some(&target))
                .unwrap_or(true),
            BackupEntryKind::Tombstone => false,
        };
        modified.then(|| "file was modified externally since last backup".to_string())
    }

    // ---- Disk persistence ----

    fn backups_dir(&self) -> Option<PathBuf> {
        self.storage_dir
            .as_ref()
            .map(|dir| match &self.storage_harness {
                Some(harness) => dir.join(harness).join("backups"),
                None => dir.join("backups"),
            })
    }

    fn session_dir(&self, session: &str) -> Option<PathBuf> {
        self.backups_dir()
            .map(|d| d.join(Self::session_hash(session)))
    }

    fn session_hash(session: &str) -> String {
        hash_session(session)
    }

    fn path_hash(key: &Path) -> String {
        // v0.16.0 intentionally switched from DefaultHasher to SHA-256 for
        // stable on-disk names. Existing DefaultHasher backup directories are
        // not migrated: backups are short-lived/session-scoped, so one-time
        // loss of pre-upgrade undo history is acceptable.
        stable_hash_16(key.to_string_lossy().as_bytes())
    }

    fn write_session_marker(&self, session: &str, last_accessed: u64) {
        let Some(session_dir) = self.session_dir(session) else {
            return;
        };
        if let Err(e) = std::fs::create_dir_all(&session_dir) {
            crate::slog_warn!("failed to create session dir: {}", e);
            return;
        }
        let marker = session_dir.join("session.json");
        let json = serde_json::json!({
            "schema_version": SCHEMA_VERSION,
            "session_id": session,
            "last_accessed": last_accessed,
        });
        if let Ok(s) = serde_json::to_string_pretty(&json) {
            let tmp = session_dir.join("session.json.tmp");
            if std::fs::write(&tmp, s).is_ok() {
                let _ = std::fs::rename(&tmp, marker);
            }
        }
    }

    fn repair_root_backups_if_needed(&self) {
        let (Some(storage_dir), Some(harness)) = (&self.storage_dir, &self.storage_harness) else {
            return;
        };
        let root_backups = storage_dir.join("backups");
        if !dir_has_entries(&root_backups) {
            return;
        }
        let harness_backups = storage_dir.join(harness).join("backups");
        if dir_has_entries(&harness_backups) {
            return;
        }
        if let Some(parent) = harness_backups.parent() {
            if let Err(error) = std::fs::create_dir_all(parent) {
                crate::slog_warn!(
                    "failed to create harness backup dir {}: {}",
                    parent.display(),
                    error
                );
                return;
            }
        }
        if harness_backups.exists() {
            let _ = std::fs::remove_dir(&harness_backups);
        }
        match std::fs::rename(&root_backups, &harness_backups) {
            Ok(()) => {
                crate::slog_info!(
                    "moved legacy root backups into harness namespace: {}",
                    harness_backups.display()
                );
            }
            Err(error) => {
                crate::slog_warn!(
                    "failed to move legacy root backups into {}: {}; trying child merge",
                    harness_backups.display(),
                    error
                );
                if std::fs::create_dir_all(&harness_backups).is_err() {
                    return;
                }
                if let Ok(entries) = std::fs::read_dir(&root_backups) {
                    for entry in entries.flatten() {
                        let source = entry.path();
                        let target = harness_backups.join(entry.file_name());
                        if !target.exists() {
                            let _ = std::fs::rename(source, target);
                        }
                    }
                }
                let _ = std::fs::remove_dir(&root_backups);
            }
        }
    }

    fn gc_stale_sessions(&mut self, ttl_hours: u32) {
        let backups_dir = match self.backups_dir() {
            Some(d) if d.exists() => d,
            _ => return,
        };
        let ttl_secs = u64::from(if ttl_hours == 0 { 72 } else { ttl_hours }) * 60 * 60;
        let cutoff = current_timestamp().saturating_sub(ttl_secs);
        let entries = match std::fs::read_dir(&backups_dir) {
            Ok(entries) => entries,
            Err(_) => return,
        };

        for entry in entries.flatten() {
            let session_dir = entry.path();
            if !session_dir.is_dir() || session_dir.join("meta.json").exists() {
                continue;
            }
            let Some(last_accessed) = Self::read_session_last_accessed(&session_dir) else {
                continue;
            };
            if last_accessed >= cutoff {
                continue;
            }
            if let Err(e) = std::fs::remove_dir_all(&session_dir) {
                crate::slog_warn!(
                    "failed to remove stale backup session {}: {}",
                    session_dir.display(),
                    e
                );
            } else {
                crate::slog_warn!(
                    "removed stale backup session {} (last_accessed={})",
                    session_dir.display(),
                    last_accessed
                );
            }
        }
    }

    /// One-time migration: move pre-session flat layout into the default
    /// session namespace. Called from `set_storage_dir` so existing backups
    /// survive the upgrade.
    ///
    /// Detection: any directory directly under `backups/` that contains a
    /// `meta.json` (as opposed to a `session.json` marker or subdirectories)
    /// is treated as a legacy entry.
    fn migrate_legacy_layout_if_needed(&mut self) {
        let backups_dir = match self.backups_dir() {
            Some(d) if d.exists() => d,
            _ => return,
        };
        let default_session_dir =
            backups_dir.join(Self::session_hash(crate::protocol::DEFAULT_SESSION_ID));

        let entries = match std::fs::read_dir(&backups_dir) {
            Ok(e) => e,
            Err(_) => return,
        };
        let mut migrated = 0usize;
        for entry in entries.flatten() {
            let entry_path = entry.path();
            // Skip non-directories and already-sessionized layouts.
            if !entry_path.is_dir() {
                continue;
            }
            if entry_path == default_session_dir {
                continue;
            }
            let meta_path = entry_path.join("meta.json");
            if !meta_path.exists() {
                continue; // Already a session-hash dir (contains per-path subdirs), skip
            }
            // This is a legacy flat-layout path-hash directory. Move it under
            // the default session namespace.
            if let Err(e) = std::fs::create_dir_all(&default_session_dir) {
                crate::slog_warn!("failed to create default session dir: {}", e);
                return;
            }
            let leaf = match entry_path.file_name() {
                Some(n) => n,
                None => continue,
            };
            let target = default_session_dir.join(leaf);
            if target.exists() {
                // Already migrated on a prior run that was interrupted —
                // leave both and let the regular load pick up the target.
                continue;
            }
            match std::fs::rename(&entry_path, &target) {
                Ok(()) => {
                    // Bump meta.json to include session_id + schema_version.
                    Self::upgrade_meta_file(
                        &target.join("meta.json"),
                        crate::protocol::DEFAULT_SESSION_ID,
                    );
                    migrated += 1;
                }
                Err(e) => {
                    crate::slog_warn!(
                        "failed to migrate legacy backup {}: {}",
                        entry_path.display(),
                        e
                    );
                }
            }
        }
        if migrated > 0 {
            crate::slog_info!(
                "migrated {} legacy backup entries into default session namespace",
                migrated
            );
            // Write a session.json marker so future scans don't re-migrate.
            let marker = default_session_dir.join("session.json");
            let json = serde_json::json!({
                "schema_version": SCHEMA_VERSION,
                "session_id": crate::protocol::DEFAULT_SESSION_ID,
                "last_accessed": current_timestamp(),
            });
            if let Ok(s) = serde_json::to_string_pretty(&json) {
                let _ = std::fs::write(&marker, s);
            }
        }
    }

    fn upgrade_meta_file(meta_path: &Path, session_id: &str) {
        let content = match std::fs::read_to_string(meta_path) {
            Ok(c) => c,
            Err(_) => return,
        };
        let mut parsed: serde_json::Value = match serde_json::from_str(&content) {
            Ok(v) => v,
            Err(_) => return,
        };
        if let Some(obj) = parsed.as_object_mut() {
            let count = obj.get("count").and_then(|v| v.as_u64()).unwrap_or(0);
            obj.insert(
                "schema_version".to_string(),
                serde_json::json!(SCHEMA_VERSION),
            );
            obj.insert("session_id".to_string(), serde_json::json!(session_id));
            obj.entry("entries").or_insert_with(|| {
                serde_json::Value::Array(
                    (0..count)
                        .map(|i| {
                            serde_json::json!({
                                "backup_id": format!("disk-{}", i),
                                "timestamp": 0,
                                "description": "restored from disk",
                                "op_id": null,
                            })
                        })
                        .collect(),
                )
            });
        }
        if let Ok(s) = serde_json::to_string_pretty(&parsed) {
            let tmp = meta_path.with_extension("json.tmp");
            if std::fs::write(&tmp, &s).is_ok() {
                let _ = std::fs::rename(&tmp, meta_path);
            }
        }
    }

    fn load_disk_index(&mut self) {
        let backups_dir = match self.backups_dir() {
            Some(d) if d.exists() => d,
            _ => return,
        };
        let session_dirs = match std::fs::read_dir(&backups_dir) {
            Ok(e) => e,
            Err(_) => return,
        };
        let mut total_entries = 0usize;
        let mut skipped_legacy = 0usize;
        for session_entry in session_dirs.flatten() {
            let session_dir = session_entry.path();
            if !session_dir.is_dir() {
                continue;
            }
            // Recover the session_id from session.json if present, otherwise skip
            // (can't invert the hash to recover the original).
            let session_id = match Self::read_session_marker(&session_dir) {
                Some(session_id) => session_id,
                None => {
                    crate::slog_warn!(
                        "skipping backup session dir without readable session marker: {}",
                        session_dir.display()
                    );
                    continue;
                }
            };

            let path_dirs = match std::fs::read_dir(&session_dir) {
                Ok(e) => e,
                Err(_) => continue,
            };
            let per_session = self.disk_index.entry(session_id.clone()).or_default();
            for path_entry in path_dirs.flatten() {
                let path_dir = path_entry.path();
                if !path_dir.is_dir() {
                    continue;
                }
                let meta_path = path_dir.join("meta.json");
                if let Ok(content) = std::fs::read_to_string(&meta_path) {
                    if let Ok(meta) = serde_json::from_str::<serde_json::Value>(&content) {
                        if let (Some(path_str), Some(count)) = (
                            meta.get("path").and_then(|v| v.as_str()),
                            meta_entry_count(&meta).map(|count| count as u64),
                        ) {
                            let key = PathBuf::from(path_str);
                            if !is_loadable_backup_path(&key, &path_dir) {
                                // Legacy/relocated backup dirs whose folder name came
                                // from an older path-hash scheme can never be loaded by
                                // the current hasher. They are harmless dead husks
                                // (active undo is DB-backed), so skip quietly and
                                // summarize once at debug instead of warning per entry.
                                skipped_legacy += 1;
                                crate::slog_debug!(
                                    "skipping backup entry with invalid path metadata: {}",
                                    meta_path.display()
                                );
                                continue;
                            }
                            per_session.insert(
                                key,
                                DiskMeta {
                                    dir: path_dir.clone(),
                                    count: count as usize,
                                },
                            );
                            total_entries += 1;
                        }
                    }
                }
            }
            if per_session.is_empty() {
                self.disk_index.remove(&session_id);
            }
        }
        if skipped_legacy > 0 {
            crate::slog_debug!(
                "skipped {} legacy backup entries with mismatched path-hash directories",
                skipped_legacy
            );
        }
        if total_entries > 0 {
            crate::slog_info!(
                "loaded {} backup entries across {} session(s) from disk",
                total_entries,
                self.disk_index.len()
            );
        }
    }

    fn read_session_marker(session_dir: &Path) -> Option<String> {
        let marker = session_dir.join("session.json");
        let content = std::fs::read_to_string(&marker).ok()?;
        let parsed: serde_json::Value = serde_json::from_str(&content).ok()?;
        parsed
            .get("session_id")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
    }

    fn read_session_last_accessed(session_dir: &Path) -> Option<u64> {
        let marker = session_dir.join("session.json");
        let content = std::fs::read_to_string(&marker).ok()?;
        let parsed: serde_json::Value = serde_json::from_str(&content).ok()?;
        parsed.get("last_accessed").and_then(|v| v.as_u64())
    }

    fn should_snapshot_path(&self, path: &Path) -> Result<bool, AftError> {
        if !self.policy.enabled {
            return Ok(false);
        }
        let Some(max_file_size) = self.policy.max_file_size else {
            return Ok(true);
        };
        match std::fs::symlink_metadata(path) {
            Ok(metadata) if metadata.is_file() && metadata.len() > max_file_size => Ok(false),
            Ok(_) => Ok(true),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                Err(AftError::FileNotFound {
                    path: path.display().to_string(),
                })
            }
            Err(error) => Err(AftError::IoError {
                path: path.display().to_string(),
                message: error.to_string(),
            }),
        }
    }

    fn ensure_session_marker(&self, session_dir: &Path, session: &str) -> Result<(), AftError> {
        let marker = session_dir.join("session.json");
        if marker.exists() {
            return Ok(());
        }
        let json = serde_json::json!({
            "schema_version": SCHEMA_VERSION,
            "session_id": session,
            "last_accessed": current_timestamp(),
        });
        let content = serde_json::to_string_pretty(&json).map_err(|error| AftError::IoError {
            path: marker.display().to_string(),
            message: error.to_string(),
        })?;
        write_temp_fsync_rename(session_dir, "session.json", content.as_bytes()).map_err(
            |error| AftError::IoError {
                path: marker.display().to_string(),
                message: error.to_string(),
            },
        )?;
        let _ = fsync_dir(session_dir);
        Ok(())
    }

    fn acquire_stack_disk_lock(
        &self,
        session: &str,
        key: &Path,
    ) -> Result<Option<crate::fs_lock::LockGuard>, AftError> {
        let Some(session_dir) = self.session_dir(session) else {
            return Ok(None);
        };
        let lock_dir = session_dir.join(".locks");
        std::fs::create_dir_all(&lock_dir).map_err(|error| AftError::IoError {
            path: lock_dir.display().to_string(),
            message: error.to_string(),
        })?;
        let lock_path = lock_dir.join(format!("{}.lock", Self::path_hash(key)));
        crate::fs_lock::acquire(&lock_path)
            .map(Some)
            .map_err(|error| AftError::IoError {
                path: lock_path.display().to_string(),
                message: error.to_string(),
            })
    }

    fn acquire_stack_disk_locks(
        &self,
        session: &str,
        keys: &[PathBuf],
    ) -> Result<Vec<crate::fs_lock::LockGuard>, AftError> {
        let mut keys = keys.to_vec();
        keys.sort();
        keys.dedup();
        let mut guards = Vec::with_capacity(keys.len());
        for key in keys {
            if let Some(guard) = self.acquire_stack_disk_lock(session, &key)? {
                guards.push(guard);
            }
        }
        Ok(guards)
    }

    #[cfg(test)]
    fn load_from_disk_if_needed(&mut self, session: &str, key: &Path) -> Result<bool, AftError> {
        let _disk_lock = self.acquire_stack_disk_lock(session, key)?;
        self.load_from_disk_if_needed_locked(session, key)
    }

    fn load_from_disk_if_needed_locked(
        &mut self,
        session: &str,
        key: &Path,
    ) -> Result<bool, AftError> {
        let entries = match self.read_stack_from_disk_unlocked(session, key) {
            Ok(Some(entries)) => entries,
            Ok(None) => {
                if self.session_dir(session).is_some() {
                    self.restore_in_memory_stack(session, key, None);
                }
                if let Some(files) = self.disk_index.get_mut(session) {
                    files.remove(key);
                    if files.is_empty() {
                        self.disk_index.remove(session);
                    }
                }
                return Ok(false);
            }
            Err(error) => {
                return Err(AftError::IoError {
                    path: key.display().to_string(),
                    message: error,
                });
            }
        };

        self.update_counter_from_entries(&entries);
        if let Ok(Some((disk_meta, _))) = self.read_disk_meta_value(session, key) {
            self.disk_index
                .entry(session.to_string())
                .or_default()
                .insert(key.to_path_buf(), disk_meta);
        }
        self.entries
            .entry(session.to_string())
            .or_default()
            .insert(key.to_path_buf(), entries);
        Ok(true)
    }

    /// Re-read the on-disk stack while the per-stack disk lock is held.
    ///
    /// The on-disk stack is authoritative across processes. A long-running
    /// process may have a non-empty but stale in-memory stack, so every mutating
    /// append validates disk state before it writes new metadata or prunes old
    /// content files.
    fn ensure_stack_hydrated_locked(&mut self, session: &str, key: &Path) -> Result<(), AftError> {
        self.load_from_disk_if_needed_locked(session, key)?;
        Ok(())
    }

    fn refresh_disk_index_for_session(&mut self, session: &str) -> Result<Vec<PathBuf>, AftError> {
        let Some(session_dir) = self.session_dir(session) else {
            self.disk_index.remove(session);
            return Ok(Vec::new());
        };
        if !session_dir.exists() {
            self.disk_index.remove(session);
            return Ok(Vec::new());
        }

        let path_dirs = std::fs::read_dir(&session_dir).map_err(|error| AftError::IoError {
            path: session_dir.display().to_string(),
            message: error.to_string(),
        })?;
        let mut per_session = HashMap::new();
        for path_entry in path_dirs {
            let path_entry = path_entry.map_err(|error| AftError::IoError {
                path: session_dir.display().to_string(),
                message: error.to_string(),
            })?;
            let path_dir = path_entry.path();
            if !path_dir.is_dir() {
                continue;
            }
            let meta_path = path_dir.join("meta.json");
            if !meta_path.exists() {
                continue;
            }
            let content =
                std::fs::read_to_string(&meta_path).map_err(|error| AftError::IoError {
                    path: meta_path.display().to_string(),
                    message: error.to_string(),
                })?;
            let meta = serde_json::from_str::<serde_json::Value>(&content).map_err(|error| {
                AftError::IoError {
                    path: meta_path.display().to_string(),
                    message: error.to_string(),
                }
            })?;
            let path_str = meta
                .get("path")
                .and_then(|value| value.as_str())
                .ok_or_else(|| AftError::IoError {
                    path: meta_path.display().to_string(),
                    message: "backup meta missing path".to_string(),
                })?;
            let key = PathBuf::from(path_str);
            if !is_loadable_backup_path(&key, &path_dir) {
                continue;
            }
            let count = meta_entry_count(&meta).ok_or_else(|| AftError::IoError {
                path: meta_path.display().to_string(),
                message: "backup meta missing entry count".to_string(),
            })?;
            if count > 0 {
                per_session.insert(
                    key,
                    DiskMeta {
                        dir: path_dir,
                        count,
                    },
                );
            }
        }

        let keys = per_session.keys().cloned().collect::<Vec<_>>();
        if per_session.is_empty() {
            self.disk_index.remove(session);
        } else {
            self.disk_index.insert(session.to_string(), per_session);
        }
        Ok(keys)
    }

    fn restore_operation_candidate_keys(
        &mut self,
        session: &str,
    ) -> Result<Vec<PathBuf>, AftError> {
        let mut keys: HashSet<PathBuf> = self
            .refresh_disk_index_for_session(session)?
            .into_iter()
            .collect();
        if let Some(files) = self.entries.get(session) {
            keys.extend(files.keys().cloned());
        }
        let mut keys = keys.into_iter().collect::<Vec<_>>();
        keys.sort();
        Ok(keys)
    }

    fn read_stack_heads_from_disk(
        &self,
        session: &str,
        key: &Path,
    ) -> Option<Vec<BackupEntryHead>> {
        let _disk_lock = match self.acquire_stack_disk_lock(session, key) {
            Ok(lock) => lock,
            Err(error) => {
                crate::slog_warn!(
                    "backup disk head read lock failed for {}: {}",
                    key.display(),
                    error
                );
                return None;
            }
        };
        match self.read_stack_heads_from_disk_unlocked(session, key) {
            Ok(heads) => heads,
            Err(error) => {
                crate::slog_warn!(
                    "backup disk head read failed for {}: {}",
                    key.display(),
                    error
                );
                None
            }
        }
    }

    fn read_stack_heads_from_disk_unlocked(
        &self,
        session: &str,
        key: &Path,
    ) -> Result<Option<Vec<BackupEntryHead>>, String> {
        let Some((disk_meta, meta)) = self.read_disk_meta_value(session, key)? else {
            return Ok(None);
        };
        if disk_meta.count == 0 {
            return Ok(None);
        }

        let heads = if is_v2_meta(&meta) {
            let entries = meta_entries(&meta)?;
            for entry in entries {
                self.validate_v2_content_reference(&disk_meta.dir, entry)?;
            }
            entries
                .iter()
                .enumerate()
                .map(|(i, entry)| backup_head_from_meta(Some(entry), i))
                .collect::<Vec<_>>()
        } else {
            let entries = meta.get("entries").and_then(|value| value.as_array());
            (0..disk_meta.count)
                .map(|i| backup_head_from_meta(entries.and_then(|entries| entries.get(i)), i))
                .collect::<Vec<_>>()
        };

        Ok((!heads.is_empty()).then_some(heads))
    }

    fn read_stack_from_disk_unlocked(
        &self,
        session: &str,
        key: &Path,
    ) -> Result<Option<Vec<BackupEntry>>, String> {
        let Some((disk_meta, meta)) = self.read_disk_meta_value(session, key)? else {
            return Ok(None);
        };
        if disk_meta.count == 0 {
            return Ok(None);
        }

        let entries = if is_v2_meta(&meta) {
            meta_entries(&meta)?
                .iter()
                .enumerate()
                .map(|(i, entry_meta)| self.entry_from_v2_meta(&disk_meta.dir, entry_meta, i))
                .collect::<Result<Vec<_>, _>>()?
        } else {
            let entries = meta.get("entries").and_then(|value| value.as_array());
            let mut loaded = Vec::new();
            for i in 0..disk_meta.count {
                let entry_meta = entries.and_then(|entries| entries.get(i));
                if let Some(entry) = legacy_entry_from_meta(&disk_meta.dir, entry_meta, i) {
                    loaded.push(entry);
                }
            }
            loaded
        };

        Ok((!entries.is_empty()).then_some(entries))
    }

    fn read_disk_meta_value(
        &self,
        session: &str,
        key: &Path,
    ) -> Result<Option<(DiskMeta, serde_json::Value)>, String> {
        let Some(session_dir) = self.session_dir(session) else {
            return Ok(None);
        };
        let dir = session_dir.join(Self::path_hash(key));
        let meta_path = dir.join("meta.json");
        if !meta_path.exists() {
            return Ok(None);
        }
        let content = std::fs::read_to_string(&meta_path)
            .map_err(|error| format!("failed to read {}: {}", meta_path.display(), error))?;
        let meta = serde_json::from_str::<serde_json::Value>(&content)
            .map_err(|error| format!("failed to parse {}: {}", meta_path.display(), error))?;
        let path_str = meta
            .get("path")
            .and_then(|value| value.as_str())
            .ok_or_else(|| format!("backup meta {} missing path", meta_path.display()))?;
        let stored_key = PathBuf::from(path_str);
        if stored_key != key || !is_loadable_backup_path(&stored_key, &dir) {
            return Ok(None);
        }
        let count = meta_entry_count(&meta)
            .ok_or_else(|| format!("backup meta {} missing entry count", meta_path.display()))?;
        Ok(Some((DiskMeta { dir, count }, meta)))
    }

    fn validate_v2_content_reference(
        &self,
        dir: &Path,
        entry_meta: &serde_json::Value,
    ) -> Result<(), String> {
        let kind = entry_kind_from_meta(Some(entry_meta));
        if matches!(kind, BackupEntryKind::Tombstone) {
            return Ok(());
        }
        let content_path = content_path_from_meta(entry_meta)?;
        let path = dir.join(content_path);
        if !path.is_file() {
            return Err(format!(
                "v2 backup meta references missing content file {}",
                path.display()
            ));
        }
        Ok(())
    }

    fn entry_from_v2_meta(
        &self,
        dir: &Path,
        entry_meta: &serde_json::Value,
        index: usize,
    ) -> Result<BackupEntry, String> {
        let kind = entry_kind_from_meta(Some(entry_meta));
        let content_bytes = match kind {
            BackupEntryKind::Content | BackupEntryKind::Symlink => {
                let content_path = content_path_from_meta(entry_meta)?;
                let path = dir.join(content_path);
                std::fs::read(&path).map_err(|error| {
                    format!(
                        "failed to read v2 backup content {}: {}",
                        path.display(),
                        error
                    )
                })?
            }
            BackupEntryKind::Tombstone => Vec::new(),
        };
        Ok(entry_from_meta(
            Some(entry_meta),
            index,
            kind,
            content_bytes,
        ))
    }

    fn write_snapshot_to_disk(
        &mut self,
        session: &str,
        key: &Path,
        stack: &[BackupEntry],
    ) -> Result<(), AftError> {
        let _disk_lock = self.acquire_stack_disk_lock(session, key)?;
        self.write_snapshot_to_disk_locked(session, key, stack)
    }

    fn write_snapshot_to_disk_locked(
        &mut self,
        session: &str,
        key: &Path,
        stack: &[BackupEntry],
    ) -> Result<(), AftError> {
        #[cfg(test)]
        if self.fail_next_disk_write {
            self.fail_next_disk_write = false;
            return Err(AftError::IoError {
                path: key.display().to_string(),
                message: "injected backup disk write failure".to_string(),
            });
        }

        let Some(session_dir) = self.session_dir(session) else {
            return Ok(());
        };

        std::fs::create_dir_all(&session_dir).map_err(|error| AftError::IoError {
            path: session_dir.display().to_string(),
            message: error.to_string(),
        })?;
        self.ensure_session_marker(&session_dir, session)?;

        let hash = Self::path_hash(key);
        let dir = session_dir.join(&hash);
        std::fs::create_dir_all(&dir).map_err(|error| AftError::IoError {
            path: dir.display().to_string(),
            message: error.to_string(),
        })?;

        let max_depth = self.policy.max_depth;
        let retained_start = stack.len().saturating_sub(max_depth);
        let retained = &stack[retained_start..];
        let mut referenced_content = HashSet::new();
        let mut wrote_content = false;

        for entry in retained {
            if let Some(content_path) = content_filename_for_entry(entry) {
                referenced_content.insert(content_path.clone());
                let final_path = dir.join(&content_path);
                if final_path.exists() {
                    continue;
                }
                let bytes = content_bytes_for_disk(entry);
                write_temp_fsync_rename(&dir, &content_path, &bytes).map_err(|error| {
                    AftError::IoError {
                        path: final_path.display().to_string(),
                        message: error.to_string(),
                    }
                })?;
                wrote_content = true;
            }
        }
        if wrote_content {
            fsync_dir(&dir).map_err(|error| AftError::IoError {
                path: dir.display().to_string(),
                message: error.to_string(),
            })?;
        }

        let entries: Vec<serde_json::Value> = retained.iter().map(entry_meta_json).collect();
        let meta = serde_json::json!({
            "schema_version": SCHEMA_VERSION,
            "format_version": V2_FORMAT_VERSION,
            "session_id": session,
            "path": key.display().to_string(),
            "count": retained.len(),
            "entries": entries,
        });
        let meta_content =
            serde_json::to_string_pretty(&meta).map_err(|error| AftError::IoError {
                path: dir.join("meta.json").display().to_string(),
                message: error.to_string(),
            })?;
        write_temp_fsync_rename(&dir, "meta.json", meta_content.as_bytes()).map_err(|error| {
            AftError::IoError {
                path: dir.join("meta.json").display().to_string(),
                message: error.to_string(),
            }
        })?;
        fsync_dir(&dir).map_err(|error| AftError::IoError {
            path: dir.display().to_string(),
            message: error.to_string(),
        })?;

        prune_unreferenced_backup_files(&dir, &referenced_content).map_err(|error| {
            AftError::IoError {
                path: dir.display().to_string(),
                message: error.to_string(),
            }
        })?;
        let _ = fsync_dir(&dir);

        // Keep the in-memory disk_index in sync so tracked_files() and
        // disk_history_count() immediately reflect what we just wrote.
        self.disk_index
            .entry(session.to_string())
            .or_default()
            .insert(
                key.to_path_buf(),
                DiskMeta {
                    dir: dir.clone(),
                    count: retained.len(),
                },
            );
        self.dual_write_stack_to_db(session, key, retained);
        Ok(())
    }

    fn dual_write_stack_to_db(&self, session: &str, key: &Path, stack: &[BackupEntry]) {
        let pool = self.db_pool.read().ok().and_then(|slot| slot.clone());
        let Some(pool) = pool else {
            return;
        };
        let harness = self.db_harness.read().ok().and_then(|slot| slot.clone());
        let Some(harness) = harness else {
            crate::slog_warn!(
                "dual-write backup to DB skipped for {}: harness not configured",
                key.display()
            );
            return;
        };
        let project_key = self
            .db_project_key
            .read()
            .ok()
            .and_then(|slot| slot.clone());
        let Some(project_key) = project_key else {
            crate::slog_warn!(
                "dual-write backup to DB skipped for {}: project key not configured",
                key.display()
            );
            return;
        };

        let conn = match pool.lock() {
            Ok(conn) => conn,
            Err(_) => {
                crate::slog_warn!(
                    "dual-write backup to DB failed for {}: db mutex poisoned",
                    key.display()
                );
                return;
            }
        };
        let path_hash = Self::path_hash(key);
        let file_path = key.display().to_string();

        // Replace the path's stack ATOMICALLY: delete old rows + insert the full
        // new stack inside one transaction. The previous version deleted, then
        // inserted row-by-row outside any transaction and merely warned-and-
        // continued on an insert error — so a crash or SQLITE_BUSY mid-loop left
        // a PARTIAL stack in the DB, which restore/history then preferred over
        // the (consistent) disk stack. On any error here the transaction rolls
        // back, leaving the prior consistent stack untouched.
        let write_result = (|| -> rusqlite::Result<()> {
            let tx = conn.unchecked_transaction()?;
            crate::db::backups::delete_backups_for_path(&tx, &harness, session, &path_hash)?;
            for entry in stack {
                let backup_path = content_filename_for_entry(entry);
                let row = entry.to_backup_row(
                    &harness,
                    session,
                    &project_key,
                    &file_path,
                    &path_hash,
                    backup_path.as_deref(),
                );
                crate::db::backups::upsert_backup(&tx, &row)?;
            }
            tx.commit()
        })();
        if let Err(error) = write_result {
            crate::slog_warn!(
                "dual-write backup stack to DB failed for {} (rolled back, prior stack kept): {}",
                key.display(),
                error
            );
        }
    }

    fn prune_disk_stacks_to_depth(&mut self, max_depth: usize) -> HashSet<(String, PathBuf)> {
        self.disk_index.clear();
        self.load_disk_index();
        let disk_keys = self
            .disk_index
            .iter()
            .flat_map(|(session, files)| {
                files
                    .keys()
                    .cloned()
                    .map(|key| (session.clone(), key))
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();
        let mut failed = HashSet::new();

        for (session, key) in disk_keys {
            let disk_lock = match self.acquire_stack_disk_lock(&session, &key) {
                Ok(lock) => lock,
                Err(error) => {
                    crate::slog_warn!(
                        "failed to lock backup stack for {} while applying max_depth: {}",
                        key.display(),
                        error
                    );
                    failed.insert((session, key));
                    continue;
                }
            };

            let mut stack = match self.read_stack_from_disk_unlocked(&session, &key) {
                Ok(Some(stack)) => stack,
                Ok(None) => Vec::new(),
                Err(error) => {
                    crate::slog_warn!(
                        "failed to read backup stack for {} while applying max_depth: {}",
                        key.display(),
                        error
                    );
                    failed.insert((session, key));
                    drop(disk_lock);
                    continue;
                }
            };
            trim_stack_to_depth(&mut stack, max_depth);
            if let Err(error) = self.write_snapshot_to_disk_locked(&session, &key, &stack) {
                crate::slog_warn!(
                    "failed to prune backup stack for {} while applying max_depth: {}",
                    key.display(),
                    error
                );
                failed.insert((session, key));
                drop(disk_lock);
                continue;
            }
            if stack.is_empty() {
                if let Some(files) = self.entries.get_mut(&session) {
                    files.remove(&key);
                    if files.is_empty() {
                        self.entries.remove(&session);
                    }
                }
            } else {
                self.entries
                    .entry(session.clone())
                    .or_default()
                    .insert(key.clone(), stack);
            }
            drop(disk_lock);
        }

        failed
    }

    fn remove_disk_backups(&mut self, session: &str, key: &Path) -> Result<(), AftError> {
        let _disk_lock = self.acquire_stack_disk_lock(session, key)?;
        self.remove_disk_backups_locked(session, key)
    }

    fn remove_disk_backups_locked(&mut self, session: &str, key: &Path) -> Result<(), AftError> {
        self.remove_db_backups(session, key);
        let removed = self.disk_index.get_mut(session).and_then(|s| s.remove(key));
        if let Some(meta) = removed {
            if let Err(error) = std::fs::remove_dir_all(&meta.dir) {
                return Err(AftError::IoError {
                    path: meta.dir.display().to_string(),
                    message: error.to_string(),
                });
            }
        } else if let Some(session_dir) = self.session_dir(session) {
            let hash = Self::path_hash(key);
            let dir = session_dir.join(&hash);
            if dir.exists() {
                if let Err(error) = std::fs::remove_dir_all(&dir) {
                    return Err(AftError::IoError {
                        path: dir.display().to_string(),
                        message: error.to_string(),
                    });
                }
            }
        }

        // If this session has no more disk entries, drop the map slot (session
        // dir itself is kept so the marker survives future sessions).
        let empty = self
            .disk_index
            .get(session)
            .map(|s| s.is_empty())
            .unwrap_or(false);
        if empty {
            self.disk_index.remove(session);
        }
        Ok(())
    }

    fn remove_db_backups(&self, session: &str, key: &Path) {
        let Some((pool, harness)) = self.db_pool_and_harness() else {
            return;
        };
        let conn = match pool.lock() {
            Ok(conn) => conn,
            Err(_) => {
                crate::slog_warn!(
                    "delete backup DB rows failed for {}: db mutex poisoned",
                    key.display()
                );
                return;
            }
        };
        let path_hash = Self::path_hash(key);
        if let Err(error) =
            crate::db::backups::delete_backups_for_path(&conn, &harness, session, &path_hash)
        {
            crate::slog_warn!(
                "delete backup DB rows failed for {}: {}",
                key.display(),
                error
            );
        }
    }
}

pub fn hash_session(session: &str) -> String {
    stable_hash_16(session.as_bytes())
}

pub fn new_op_id() -> String {
    let mut bytes = [0u8; 4];
    if getrandom::fill(&mut bytes).is_err() {
        bytes = current_timestamp().to_le_bytes()[..4]
            .try_into()
            .unwrap_or([0; 4]);
    }
    let rand = u32::from_le_bytes(bytes);
    format!("op-{}-{:08x}", current_timestamp() * 1000, rand)
}

#[derive(Debug, Clone)]
struct BackupEntryDiskMetadata {
    mode: Option<u32>,
    link_target: Option<PathBuf>,
    created_dirs: Vec<PathBuf>,
}

#[derive(Debug, Clone)]
enum RestorePathState {
    Missing,
    Regular {
        content_bytes: Vec<u8>,
        mode: Option<u32>,
    },
    Symlink {
        target: PathBuf,
    },
    Directory,
}

fn backup_entry_from_path(
    path: &Path,
    backup_id: String,
    order: u128,
    description: &str,
    op_id: Option<&str>,
) -> Result<BackupEntry, AftError> {
    let metadata = std::fs::symlink_metadata(path).map_err(|error| match error.kind() {
        std::io::ErrorKind::NotFound => AftError::FileNotFound {
            path: path.display().to_string(),
        },
        _ => AftError::IoError {
            path: path.display().to_string(),
            message: error.to_string(),
        },
    })?;
    let mode = file_mode(&metadata);

    let (kind, content, content_bytes, link_target) = if metadata.file_type().is_symlink() {
        let target = std::fs::read_link(path).map_err(|error| AftError::IoError {
            path: path.display().to_string(),
            message: error.to_string(),
        })?;
        (
            BackupEntryKind::Symlink,
            target.display().to_string(),
            Vec::new(),
            Some(target),
        )
    } else if metadata.is_file() {
        let bytes = std::fs::read(path).map_err(|error| AftError::IoError {
            path: path.display().to_string(),
            message: error.to_string(),
        })?;
        (
            BackupEntryKind::Content,
            String::from_utf8_lossy(&bytes).into_owned(),
            bytes,
            None,
        )
    } else {
        return Err(AftError::InvalidRequest {
            message: format!(
                "backup: '{}' is not a regular file or symlink",
                path.display()
            ),
        });
    };

    Ok(BackupEntry {
        backup_id,
        content,
        content_bytes,
        timestamp: current_timestamp(),
        order,
        description: description.to_string(),
        op_id: op_id.map(str::to_string),
        kind,
        mode,
        link_target,
        created_dirs: Vec::new(),
    })
}

fn canonicalize_key(path: &Path) -> PathBuf {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("."))
            .join(path)
    };

    match std::fs::symlink_metadata(&absolute) {
        Ok(metadata) if metadata.file_type().is_symlink() => {
            canonicalize_parent_join_leaf(&absolute)
        }
        Ok(_) => std::fs::canonicalize(&absolute)
            .map(|path| normalize_absolute_key(&path))
            .unwrap_or_else(|_| canonicalize_existing_ancestor(&absolute)),
        Err(_) => canonicalize_existing_ancestor(&absolute),
    }
}

fn canonicalize_parent_join_leaf(path: &Path) -> PathBuf {
    let Some(parent) = path.parent() else {
        return normalize_absolute_key(path);
    };
    let mut key = canonicalize_existing_ancestor(parent);
    if let Some(file_name) = path.file_name() {
        key.push(file_name);
    }
    key
}

fn canonicalize_existing_ancestor(path: &Path) -> PathBuf {
    let mut suffix = Vec::new();
    let mut current = path;

    loop {
        if let Ok(mut base) = std::fs::canonicalize(current) {
            for component in suffix.iter().rev() {
                base.push(Path::new(component));
            }
            return normalize_absolute_key(&base);
        }
        let Some(parent) = current.parent() else {
            return normalize_absolute_key(path);
        };
        if let Some(file_name) = current.file_name() {
            suffix.push(file_name.to_os_string());
        }
        current = parent;
    }
}

fn normalize_absolute_key(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();

    for component in path.components() {
        match component {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                if !normalized.pop() {
                    normalized.push(component.as_os_str());
                }
            }
            other => normalized.push(other.as_os_str()),
        }
    }

    normalized
}

fn file_mode(metadata: &std::fs::Metadata) -> Option<u32> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        Some(metadata.permissions().mode())
    }
    #[cfg(not(unix))]
    {
        let _ = metadata;
        None
    }
}

fn set_file_mode(path: &Path, mode: Option<u32>) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Some(mode) = mode {
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))?;
        }
    }
    #[cfg(not(unix))]
    {
        let _ = (path, mode);
    }
    Ok(())
}

fn capture_path_state(path: &Path) -> Result<RestorePathState, AftError> {
    let metadata = match std::fs::symlink_metadata(path) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Ok(RestorePathState::Missing);
        }
        Err(error) => {
            return Err(AftError::IoError {
                path: path.display().to_string(),
                message: error.to_string(),
            });
        }
    };

    if metadata.file_type().is_symlink() {
        let target = std::fs::read_link(path).map_err(|error| AftError::IoError {
            path: path.display().to_string(),
            message: error.to_string(),
        })?;
        Ok(RestorePathState::Symlink { target })
    } else if metadata.is_file() {
        let content_bytes = std::fs::read(path).map_err(|error| AftError::IoError {
            path: path.display().to_string(),
            message: error.to_string(),
        })?;
        Ok(RestorePathState::Regular {
            content_bytes,
            mode: file_mode(&metadata),
        })
    } else {
        Ok(RestorePathState::Directory)
    }
}

fn restore_entry_to_path(path: &Path, entry: &BackupEntry) -> std::io::Result<()> {
    match entry.kind {
        BackupEntryKind::Content => restore_regular_file(path, &entry.content_bytes, entry.mode),
        BackupEntryKind::Symlink => {
            let target = entry.link_target.as_ref().ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "symlink backup entry missing target",
                )
            })?;
            restore_symlink(path, target)
        }
        BackupEntryKind::Tombstone => remove_tombstone_path(path),
    }
}

fn restore_path_state(path: &Path, state: &RestorePathState) -> bool {
    match state {
        RestorePathState::Missing => remove_file_or_symlink_if_present(path).is_ok(),
        RestorePathState::Regular {
            content_bytes,
            mode,
        } => restore_regular_file(path, content_bytes, *mode).is_ok(),
        RestorePathState::Symlink { target } => restore_symlink(path, target).is_ok(),
        RestorePathState::Directory => true,
    }
}

fn restore_regular_file(
    path: &Path,
    content_bytes: &[u8],
    mode: Option<u32>,
) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)?;
        }
    }
    if std::fs::symlink_metadata(path)
        .map(|metadata| metadata.file_type().is_symlink())
        .unwrap_or(false)
    {
        std::fs::remove_file(path)?;
    }
    std::fs::write(path, content_bytes)?;
    set_file_mode(path, mode)
}

fn restore_symlink(path: &Path, target: &Path) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)?;
        }
    }
    remove_file_or_symlink_if_present(path)?;
    create_symlink(target, path)
}

#[cfg(unix)]
fn create_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(target, link)
}

#[cfg(windows)]
fn create_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    if target.is_dir() {
        std::os::windows::fs::symlink_dir(target, link)
    } else {
        std::os::windows::fs::symlink_file(target, link)
    }
}

fn remove_tombstone_path(path: &Path) -> std::io::Result<()> {
    match std::fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() || metadata.is_file() => {
            std::fs::remove_file(path)
        }
        Ok(_) => Err(std::io::Error::new(
            std::io::ErrorKind::IsADirectory,
            "tombstone target is a directory",
        )),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error),
    }
}

fn remove_file_or_symlink_if_present(path: &Path) -> std::io::Result<()> {
    match std::fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() || metadata.is_file() => {
            std::fs::remove_file(path)
        }
        Ok(_) => Err(std::io::Error::new(
            std::io::ErrorKind::IsADirectory,
            "path is a directory",
        )),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error),
    }
}

fn read_entry_disk_metadata(
    backup_path: &Path,
    backup_id: &str,
) -> Option<BackupEntryDiskMetadata> {
    let meta_path = if backup_path.file_name().and_then(|name| name.to_str()) == Some("meta.json") {
        backup_path.to_path_buf()
    } else {
        backup_path.parent()?.join("meta.json")
    };
    let content = std::fs::read_to_string(meta_path).ok()?;
    let meta: serde_json::Value = serde_json::from_str(&content).ok()?;
    let entries = meta.get("entries")?.as_array()?;
    let entry = entries
        .iter()
        .find(|entry| entry.get("backup_id").and_then(|value| value.as_str()) == Some(backup_id))?;
    Some(BackupEntryDiskMetadata {
        mode: entry
            .get("mode")
            .and_then(|value| value.as_u64())
            .and_then(|mode| u32::try_from(mode).ok()),
        link_target: entry
            .get("link_target")
            .and_then(|value| value.as_str())
            .map(PathBuf::from),
        created_dirs: entry
            .get("created_dirs")
            .and_then(|value| value.as_array())
            .map(|dirs| {
                dirs.iter()
                    .filter_map(|dir| dir.as_str())
                    .map(PathBuf::from)
                    .collect()
            })
            .unwrap_or_default(),
    })
}

fn rollback_transactional_restore(
    written: &[(PathBuf, RestorePathState)],
    attempted: Option<(&PathBuf, &RestorePathState)>,
) -> bool {
    let mut ok = true;

    if let Some((path, state)) = attempted {
        ok &= restore_path_state(path, state);
    }

    for (path, state) in written.iter().rev() {
        ok &= restore_path_state(path, state);
    }

    ok
}

fn rollback_deleted_tombstones(deleted: &[(PathBuf, RestorePathState)]) -> bool {
    let mut ok = true;
    for (path, state) in deleted.iter().rev() {
        ok &= restore_path_state(path, state);
    }
    ok
}

fn missing_parent_dirs(parent: &Path) -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    let mut current = Some(parent);

    while let Some(dir) = current {
        if dir.as_os_str().is_empty() || dir.exists() {
            break;
        }
        dirs.push(dir.to_path_buf());
        current = dir.parent();
    }

    dirs
}

fn rollback_created_dirs(dirs: &[PathBuf]) -> bool {
    let mut dirs = dirs.to_vec();
    dirs.sort_by_key(|dir| std::cmp::Reverse(dir.components().count()));
    dirs.dedup();

    let mut ok = true;
    for dir in dirs {
        match std::fs::remove_dir(&dir) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(_) => ok = false,
        }
    }

    ok
}

fn remove_created_dirs_best_effort(dirs: &[PathBuf]) {
    let mut dirs = dirs.to_vec();
    dirs.sort_by_key(|dir| std::cmp::Reverse(dir.components().count()));
    dirs.dedup();

    for dir in dirs {
        match std::fs::remove_dir(&dir) {
            Ok(()) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(_) => {}
        }
    }
}

fn dir_has_entries(path: &Path) -> bool {
    std::fs::read_dir(path)
        .map(|mut entries| entries.next().is_some())
        .unwrap_or(false)
}

fn current_timestamp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

fn current_timestamp_nanos() -> u64 {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    nanos.min(u128::from(u64::MAX)) as u64
}

fn legacy_entry_order(timestamp_secs: u64, backup_id: &str) -> u128 {
    let nanos = timestamp_secs.saturating_mul(1_000_000_000);
    ((nanos as u128) << 32) | u128::from(backup_sequence(backup_id).unwrap_or(0))
}

fn parse_order_value(value: &serde_json::Value) -> Option<u128> {
    value
        .as_str()
        .and_then(|s| s.parse::<u128>().ok())
        .or_else(|| value.as_u64().map(u128::from))
}

fn is_v2_meta(meta: &serde_json::Value) -> bool {
    meta.get("format_version").and_then(|value| value.as_str()) == Some(V2_FORMAT_VERSION)
}

fn meta_entries(meta: &serde_json::Value) -> Result<&Vec<serde_json::Value>, String> {
    meta.get("entries")
        .and_then(|value| value.as_array())
        .ok_or_else(|| "backup meta missing entries array".to_string())
}

fn meta_entry_count(meta: &serde_json::Value) -> Option<usize> {
    if is_v2_meta(meta) {
        return meta
            .get("entries")
            .and_then(|value| value.as_array())
            .map(Vec::len);
    }
    meta.get("count")
        .and_then(|value| value.as_u64())
        .and_then(|count| usize::try_from(count).ok())
        .or_else(|| {
            meta.get("entries")
                .and_then(|value| value.as_array())
                .map(Vec::len)
        })
}

fn entry_kind_from_meta(entry_meta: Option<&serde_json::Value>) -> BackupEntryKind {
    match entry_meta
        .and_then(|meta| meta.get("kind"))
        .and_then(|value| value.as_str())
    {
        Some("tombstone") => BackupEntryKind::Tombstone,
        Some("symlink") => BackupEntryKind::Symlink,
        _ => BackupEntryKind::Content,
    }
}

fn backup_head_from_meta(entry_meta: Option<&serde_json::Value>, index: usize) -> BackupEntryHead {
    let backup_id = entry_backup_id(entry_meta, index);
    let timestamp = entry_meta
        .and_then(|meta| meta.get("timestamp"))
        .and_then(|value| value.as_u64())
        .unwrap_or(0);
    let order = entry_meta
        .and_then(|meta| meta.get("order"))
        .and_then(parse_order_value)
        .unwrap_or_else(|| legacy_entry_order(timestamp, &backup_id));
    BackupEntryHead {
        order,
        op_id: entry_meta
            .and_then(|meta| meta.get("op_id"))
            .and_then(|value| value.as_str())
            .map(str::to_string),
    }
}

fn entry_backup_id(entry_meta: Option<&serde_json::Value>, index: usize) -> String {
    entry_meta
        .and_then(|meta| meta.get("backup_id"))
        .and_then(|value| value.as_str())
        .map(str::to_string)
        .unwrap_or_else(|| format!("disk-{}", index))
}

fn entry_from_meta(
    entry_meta: Option<&serde_json::Value>,
    index: usize,
    kind: BackupEntryKind,
    content_bytes: Vec<u8>,
) -> BackupEntry {
    let backup_id = entry_backup_id(entry_meta, index);
    let timestamp = entry_meta
        .and_then(|meta| meta.get("timestamp"))
        .and_then(|value| value.as_u64())
        .unwrap_or(0);
    let order = entry_meta
        .and_then(|meta| meta.get("order"))
        .and_then(parse_order_value)
        .unwrap_or_else(|| legacy_entry_order(timestamp, &backup_id));
    let link_target = if kind == BackupEntryKind::Symlink {
        entry_meta
            .and_then(|meta| meta.get("link_target"))
            .and_then(|value| value.as_str())
            .map(PathBuf::from)
            .or_else(|| {
                Some(PathBuf::from(
                    String::from_utf8_lossy(&content_bytes).into_owned(),
                ))
            })
    } else {
        None
    };
    let content = match kind {
        BackupEntryKind::Content => String::from_utf8_lossy(&content_bytes).into_owned(),
        BackupEntryKind::Symlink => link_target
            .as_ref()
            .map(|target| target.display().to_string())
            .unwrap_or_default(),
        BackupEntryKind::Tombstone => String::new(),
    };
    BackupEntry {
        backup_id,
        content,
        content_bytes,
        timestamp,
        order,
        description: entry_meta
            .and_then(|meta| meta.get("description"))
            .and_then(|value| value.as_str())
            .unwrap_or("restored from disk")
            .to_string(),
        op_id: entry_meta
            .and_then(|meta| meta.get("op_id"))
            .and_then(|value| value.as_str())
            .map(str::to_string),
        kind,
        mode: entry_meta
            .and_then(|meta| meta.get("mode"))
            .and_then(|value| value.as_u64())
            .and_then(|mode| u32::try_from(mode).ok()),
        link_target,
        created_dirs: entry_meta
            .and_then(|meta| meta.get("created_dirs"))
            .and_then(|value| value.as_array())
            .map(|dirs| {
                dirs.iter()
                    .filter_map(|dir| dir.as_str())
                    .map(PathBuf::from)
                    .collect()
            })
            .unwrap_or_default(),
    }
}

fn legacy_entry_from_meta(
    dir: &Path,
    entry_meta: Option<&serde_json::Value>,
    index: usize,
) -> Option<BackupEntry> {
    let kind = entry_kind_from_meta(entry_meta);
    let content_bytes = match kind {
        BackupEntryKind::Content | BackupEntryKind::Symlink => {
            std::fs::read(dir.join(format!("{}.bak", index))).ok()?
        }
        BackupEntryKind::Tombstone => Vec::new(),
    };
    Some(entry_from_meta(entry_meta, index, kind, content_bytes))
}

fn content_path_from_meta(entry_meta: &serde_json::Value) -> Result<&str, String> {
    let value = entry_meta
        .get("content_path")
        .and_then(|value| value.as_str())
        .ok_or_else(|| "v2 backup entry missing content_path".to_string())?;
    let path = Path::new(value);
    let mut components = path.components();
    match (components.next(), components.next()) {
        (Some(std::path::Component::Normal(_)), None) => Ok(value),
        _ => Err(format!("invalid backup content_path '{value}'")),
    }
}

fn sanitize_backup_id(value: &str) -> String {
    value
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
                ch
            } else {
                '_'
            }
        })
        .collect()
}

fn content_filename_for_entry(entry: &BackupEntry) -> Option<String> {
    match entry.kind {
        BackupEntryKind::Content | BackupEntryKind::Symlink => Some(format!(
            "bak_{}_{}.bak",
            entry.order,
            sanitize_backup_id(&entry.backup_id)
        )),
        BackupEntryKind::Tombstone => None,
    }
}

fn content_bytes_for_disk(entry: &BackupEntry) -> Vec<u8> {
    match entry.kind {
        BackupEntryKind::Content => entry.content_bytes.clone(),
        BackupEntryKind::Symlink => entry
            .link_target
            .as_ref()
            .map(|target| target.as_os_str().to_string_lossy().as_bytes().to_vec())
            .unwrap_or_default(),
        BackupEntryKind::Tombstone => Vec::new(),
    }
}

fn entry_meta_json(entry: &BackupEntry) -> serde_json::Value {
    serde_json::json!({
        "backup_id": entry.backup_id,
        "timestamp": entry.timestamp,
        "order": entry.order.to_string(),
        "description": entry.description,
        "op_id": entry.op_id,
        "kind": match entry.kind {
            BackupEntryKind::Content => "content",
            BackupEntryKind::Symlink => "symlink",
            BackupEntryKind::Tombstone => "tombstone",
        },
        "content_path": content_filename_for_entry(entry),
        "mode": entry.mode,
        "link_target": entry.link_target.as_ref().map(|target| target.display().to_string()),
        "created_dirs": entry
            .created_dirs
            .iter()
            .map(|dir| dir.display().to_string())
            .collect::<Vec<_>>(),
    })
}

fn trim_stack_to_depth(stack: &mut Vec<BackupEntry>, max_depth: usize) {
    if max_depth == 0 {
        stack.clear();
        return;
    }
    while stack.len() > max_depth {
        stack.remove(0);
    }
}

fn write_temp_fsync_rename(dir: &Path, final_name: &str, content: &[u8]) -> std::io::Result<()> {
    let tmp_name = format!(
        ".{}.{}.{}.tmp",
        final_name,
        std::process::id(),
        current_timestamp_nanos()
    );
    let tmp_path = dir.join(tmp_name);
    let final_path = dir.join(final_name);
    {
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp_path)?;
        file.write_all(content)?;
        file.sync_all()?;
    }
    replace_file(&tmp_path, &final_path)
}

fn replace_file(from: &Path, to: &Path) -> std::io::Result<()> {
    // On Windows, std::fs::rename uses MoveFileExW replace-existing semantics,
    // so a single rename keeps meta.json atomic instead of deleting it first.
    std::fs::rename(from, to)
}

#[cfg(unix)]
fn fsync_dir(path: &Path) -> std::io::Result<()> {
    std::fs::File::open(path)?.sync_all()
}

#[cfg(not(unix))]
fn fsync_dir(_path: &Path) -> std::io::Result<()> {
    // Windows cannot open a directory as a regular File handle without
    // FILE_FLAG_BACKUP_SEMANTICS — `File::open` on a directory returns
    // "Access is denied" (os error 5). Directory fsync is also not the
    // durability mechanism there: `std::fs::rename` maps to MoveFileExW with
    // MOVEFILE_WRITE_THROUGH, which flushes the rename's metadata change to
    // disk, and each content/meta file is already `sync_all()`-ed before the
    // rename. So a separate directory sync is unnecessary on non-Unix.
    Ok(())
}

fn prune_unreferenced_backup_files(
    dir: &Path,
    referenced: &HashSet<String>,
) -> std::io::Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
            continue;
        };
        let is_backup_content = (name.starts_with("bak_") && name.ends_with(".bak"))
            || legacy_numeric_backup_name(name);
        let is_temp = name.ends_with(".tmp") || name.contains(".tmp.");
        if is_temp || (is_backup_content && !referenced.contains(name)) {
            let _ = std::fs::remove_file(path);
        }
    }
    Ok(())
}

fn legacy_numeric_backup_name(name: &str) -> bool {
    name.strip_suffix(".bak")
        .is_some_and(|stem| !stem.is_empty() && stem.chars().all(|ch| ch.is_ascii_digit()))
}

fn is_loadable_backup_path(key: &Path, path_dir: &Path) -> bool {
    if !key.is_absolute()
        || key
            .components()
            .any(|c| matches!(c, std::path::Component::ParentDir))
    {
        return false;
    }
    let Some(dir_name) = path_dir.file_name().and_then(|name| name.to_str()) else {
        return false;
    };
    BackupStore::path_hash(key) == dir_name
}

fn stable_hash_16(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    digest[..8]
        .iter()
        .map(|byte| format!("{:02x}", byte))
        .collect()
}

fn backup_sequence(backup_id: &str) -> Option<u64> {
    backup_id
        .strip_prefix("backup-")
        .or_else(|| backup_id.strip_prefix("disk-"))
        .and_then(|s| s.parse().ok())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::harness::Harness;
    use crate::protocol::DEFAULT_SESSION_ID;
    use std::fs;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;
    use std::sync::{Arc, Mutex};

    fn temp_file(name: &str, content: &str) -> PathBuf {
        let dir = std::env::temp_dir().join("aft_backup_tests");
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join(name);
        fs::write(&path, content).unwrap();
        path
    }

    #[test]
    fn snapshot_and_restore_round_trip() {
        let path = temp_file("round_trip.txt", "original");
        let mut store = BackupStore::new();

        let id = store
            .snapshot(DEFAULT_SESSION_ID, &path, "before edit")
            .unwrap()
            .unwrap();
        assert!(id.starts_with("backup-"));

        fs::write(&path, "modified").unwrap();
        assert_eq!(fs::read_to_string(&path).unwrap(), "modified");

        let (entry, _) = store.restore_latest(DEFAULT_SESSION_ID, &path).unwrap();
        assert_eq!(entry.content, "original");
        assert_eq!(fs::read_to_string(&path).unwrap(), "original");
    }

    #[test]
    fn multiple_snapshots_preserve_order() {
        let path = temp_file("order.txt", "v1");
        let mut store = BackupStore::new();

        store.snapshot(DEFAULT_SESSION_ID, &path, "first").unwrap();
        fs::write(&path, "v2").unwrap();
        store.snapshot(DEFAULT_SESSION_ID, &path, "second").unwrap();
        fs::write(&path, "v3").unwrap();
        store.snapshot(DEFAULT_SESSION_ID, &path, "third").unwrap();

        let history = store.history(DEFAULT_SESSION_ID, &path);
        assert_eq!(history.len(), 3);
        assert_eq!(history[0].content, "v1");
        assert_eq!(history[1].content, "v2");
        assert_eq!(history[2].content, "v3");
    }

    #[test]
    fn restore_pops_from_stack() {
        let path = temp_file("pop.txt", "v1");
        let mut store = BackupStore::new();

        store.snapshot(DEFAULT_SESSION_ID, &path, "first").unwrap();
        fs::write(&path, "v2").unwrap();
        store.snapshot(DEFAULT_SESSION_ID, &path, "second").unwrap();

        let (entry, _) = store.restore_latest(DEFAULT_SESSION_ID, &path).unwrap();
        assert_eq!(entry.description, "second");
        assert_eq!(entry.content, "v2");

        let history = store.history(DEFAULT_SESSION_ID, &path);
        assert_eq!(history.len(), 1);
    }

    #[test]
    fn empty_history_returns_empty_vec() {
        let store = BackupStore::new();
        let path = Path::new("/tmp/aft_backup_tests/nonexistent_history.txt");
        assert!(store.history(DEFAULT_SESSION_ID, path).is_empty());
    }

    #[test]
    fn snapshot_nonexistent_file_returns_error() {
        let mut store = BackupStore::new();
        let path = Path::new("/tmp/aft_backup_tests/absolutely_does_not_exist.txt");
        assert!(store.snapshot(DEFAULT_SESSION_ID, path, "test").is_err());
    }

    #[test]
    fn tracked_files_lists_snapshotted_paths() {
        let path1 = temp_file("tracked1.txt", "a");
        let path2 = temp_file("tracked2.txt", "b");
        let mut store = BackupStore::new();

        store.snapshot(DEFAULT_SESSION_ID, &path1, "snap1").unwrap();
        store.snapshot(DEFAULT_SESSION_ID, &path2, "snap2").unwrap();
        assert_eq!(store.tracked_files(DEFAULT_SESSION_ID).len(), 2);
    }

    #[test]
    fn sessions_are_isolated() {
        let path = temp_file("isolated.txt", "original");
        let mut store = BackupStore::new();

        store.snapshot("session_a", &path, "a's snapshot").unwrap();

        // Session B sees no history for this file.
        assert!(store.history("session_b", &path).is_empty());
        assert_eq!(store.tracked_files("session_b").len(), 0);

        // Session B's restore_latest fails with NoUndoHistory.
        let err = store.restore_latest("session_b", &path);
        assert!(matches!(err, Err(AftError::NoUndoHistory { .. })));

        // Session A still sees its own snapshot.
        assert_eq!(store.history("session_a", &path).len(), 1);
        assert_eq!(store.tracked_files("session_a").len(), 1);
    }

    #[test]
    fn per_session_per_file_cap_is_independent() {
        // Two sessions fill up their own stacks independently; hitting the cap
        // in session A does not evict anything from session B.
        let path = temp_file("cap_indep.txt", "v0");
        let mut store = BackupStore::new();

        for i in 0..(MAX_UNDO_DEPTH + 5) {
            fs::write(&path, format!("a{}", i)).unwrap();
            store.snapshot("session_a", &path, "a").unwrap();
        }
        fs::write(&path, "b_initial").unwrap();
        store.snapshot("session_b", &path, "b").unwrap();

        // Session A should be capped at MAX_UNDO_DEPTH.
        assert_eq!(store.history("session_a", &path).len(), MAX_UNDO_DEPTH);
        // Session B should still have its single entry.
        assert_eq!(store.history("session_b", &path).len(), 1);
    }

    #[test]
    fn sessions_with_backups_lists_all_namespaces() {
        let path_a = temp_file("sessions_list_a.txt", "a");
        let path_b = temp_file("sessions_list_b.txt", "b");
        let mut store = BackupStore::new();

        store.snapshot("alice", &path_a, "from alice").unwrap();
        store.snapshot("bob", &path_b, "from bob").unwrap();

        let sessions = store.sessions_with_backups();
        assert_eq!(sessions.len(), 2);
        assert!(sessions.iter().any(|s| s == "alice"));
        assert!(sessions.iter().any(|s| s == "bob"));
    }

    #[test]
    fn disk_persistence_survives_reload() {
        let dir = std::env::temp_dir().join("aft_backup_disk_test");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();

        let file_path = temp_file("disk_persist.txt", "original");

        // Create store with storage, snapshot under default session, drop.
        {
            let mut store = BackupStore::new();
            store.set_storage_dir(dir.clone(), 72);
            store
                .snapshot(DEFAULT_SESSION_ID, &file_path, "before edit")
                .unwrap();
        }

        // Modify the file externally.
        fs::write(&file_path, "externally modified").unwrap();

        // Create new store, load from disk, restore.
        let mut store2 = BackupStore::new();
        store2.set_storage_dir(dir.clone(), 72);

        let (entry, warning) = store2
            .restore_latest(DEFAULT_SESSION_ID, &file_path)
            .unwrap();
        assert_eq!(entry.content, "original");
        assert!(warning.is_some()); // modified externally
        assert_eq!(fs::read_to_string(&file_path).unwrap(), "original");

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn snapshot_after_restart_preserves_history_and_unique_ids() {
        // Regression (bug #8): after a restart the BackupStore is fresh
        // (entries cleared, counter reset to 0). A new snapshot must EXTEND the
        // persisted undo stack — not overwrite it with a single entry — and must
        // not reuse backup-0. Two undo levels must remain available across the
        // restart boundary.
        let dir = std::env::temp_dir().join("aft_backup_restart_history_test");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let file_path = temp_file("restart_history.txt", "v0");

        // Run 1: edit v0 -> v1 (snapshot captures "v0"), then write v1.
        let first_id = {
            let mut store = BackupStore::new();
            store.set_storage_dir(dir.clone(), 72);
            let id = store
                .snapshot(DEFAULT_SESSION_ID, &file_path, "edit 1")
                .unwrap()
                .unwrap();
            fs::write(&file_path, "v1").unwrap();
            id
        };

        // Restart: fresh store, same storage dir. Edit v1 -> v2 (snapshot
        // captures "v1"), then write v2.
        let second_id = {
            let mut store = BackupStore::new();
            store.set_storage_dir(dir.clone(), 72);
            let id = store
                .snapshot(DEFAULT_SESSION_ID, &file_path, "edit 2")
                .unwrap()
                .unwrap();
            fs::write(&file_path, "v2").unwrap();
            id
        };

        // The post-restart snapshot must NOT reuse the first id (counter
        // advanced past persisted entries).
        assert_ne!(
            first_id, second_id,
            "post-restart snapshot reused backup id {first_id}"
        );

        // Both undo levels survive: a fresh store sees 2 entries on disk, and
        // two sequential restores walk v1 then v0.
        let mut store = BackupStore::new();
        store.set_storage_dir(dir.clone(), 72);
        assert_eq!(
            store.history(DEFAULT_SESSION_ID, &file_path).len(),
            2,
            "prior history was overwritten by the post-restart snapshot"
        );

        let (entry1, _) = store
            .restore_latest(DEFAULT_SESSION_ID, &file_path)
            .unwrap();
        assert_eq!(entry1.content, "v1", "first undo should restore v1");
        let (entry0, _) = store
            .restore_latest(DEFAULT_SESSION_ID, &file_path)
            .unwrap();
        assert_eq!(entry0.content, "v0", "second undo should restore v0");

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn legacy_flat_layout_migrates_to_default_session() {
        // Simulate a pre-session on-disk layout (schema v1) and verify it's
        // moved under the default session namespace on set_storage_dir.
        let dir = std::env::temp_dir().join("aft_backup_migration_test");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let backups = dir.join("backups");
        fs::create_dir_all(&backups).unwrap();

        // Fake legacy entry for some path hash.
        let legacy_hash = "deadbeefcafebabe";
        let legacy_dir = backups.join(legacy_hash);
        fs::create_dir_all(&legacy_dir).unwrap();
        fs::write(legacy_dir.join("0.bak"), "original content").unwrap();
        let legacy_meta = serde_json::json!({
            "path": "/tmp/migrated_file.txt",
            "count": 1,
        });
        fs::write(
            legacy_dir.join("meta.json"),
            serde_json::to_string_pretty(&legacy_meta).unwrap(),
        )
        .unwrap();

        // Run migration.
        let mut store = BackupStore::new();
        store.set_storage_dir(dir.clone(), 72);

        // After migration, the legacy dir should be gone from the top level,
        // and the entry should now live under the default-session hash dir.
        let default_session_dir = backups.join(BackupStore::session_hash(DEFAULT_SESSION_ID));
        assert!(default_session_dir.exists());
        assert!(default_session_dir.join(legacy_hash).exists());
        assert!(!backups.join(legacy_hash).exists());

        // The upgraded meta.json should now include session_id + schema_version.
        let meta_content =
            fs::read_to_string(default_session_dir.join(legacy_hash).join("meta.json")).unwrap();
        let meta: serde_json::Value = serde_json::from_str(&meta_content).unwrap();
        assert_eq!(meta["session_id"], DEFAULT_SESSION_ID);
        assert_eq!(meta["schema_version"], SCHEMA_VERSION);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn set_storage_dir_removes_stale_backup_sessions() {
        let dir = std::env::temp_dir().join("aft_backup_gc_test");
        let _ = fs::remove_dir_all(&dir);
        let backups = dir.join("backups");
        fs::create_dir_all(&backups).unwrap();

        let stale_session_dir = backups.join("stale-session");
        fs::create_dir_all(&stale_session_dir).unwrap();
        let stale_marker = serde_json::json!({
            "schema_version": SCHEMA_VERSION,
            "session_id": "stale",
            "last_accessed": 1,
        });
        fs::write(
            stale_session_dir.join("session.json"),
            serde_json::to_string_pretty(&stale_marker).unwrap(),
        )
        .unwrap();

        let mut store = BackupStore::new();
        store.set_storage_dir(dir.clone(), 1);

        assert!(!stale_session_dir.exists());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn markerless_session_dir_is_skipped_not_mapped_to_default() {
        let dir = std::env::temp_dir().join("aft_backup_markerless_skip_test");
        let _ = fs::remove_dir_all(&dir);
        let file_path = temp_file("markerless.txt", "original");
        let key = canonicalize_key(&file_path);
        let path_dir = dir
            .join("backups")
            .join("corrupt-session")
            .join("path-entry");
        fs::create_dir_all(&path_dir).unwrap();
        fs::write(path_dir.join("0.bak"), "original").unwrap();
        fs::write(
            path_dir.join("meta.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": SCHEMA_VERSION,
                "session_id": "lost-session",
                "path": key.display().to_string(),
                "count": 1,
                "entries": [{
                    "backup_id": "disk-0",
                    "timestamp": 0,
                    "description": "corrupt marker test",
                    "op_id": null,
                    "kind": "content",
                }]
            }))
            .unwrap(),
        )
        .unwrap();

        let mut store = BackupStore::new();
        store.set_storage_dir(dir.clone(), 72);

        assert_eq!(store.disk_history_count(DEFAULT_SESSION_ID, &file_path), 0);
        assert!(store.sessions_with_backups().is_empty());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn set_storage_dir_reconfiguration_drops_previous_disk_index() {
        let dir_a = std::env::temp_dir().join("aft_backup_storage_a_test");
        let dir_b = std::env::temp_dir().join("aft_backup_storage_b_test");
        let _ = fs::remove_dir_all(&dir_a);
        let _ = fs::remove_dir_all(&dir_b);
        fs::create_dir_all(&dir_a).unwrap();
        fs::create_dir_all(&dir_b).unwrap();
        let file_path = temp_file("storage_reconfigure.txt", "original");

        let mut store = BackupStore::new();
        store.set_storage_dir(dir_a.clone(), 72);
        store
            .snapshot(DEFAULT_SESSION_ID, &file_path, "stored in a")
            .unwrap();
        assert_eq!(store.disk_history_count(DEFAULT_SESSION_ID, &file_path), 1);

        store.set_storage_dir(dir_b.clone(), 72);

        assert_eq!(store.disk_history_count(DEFAULT_SESSION_ID, &file_path), 0);
        assert!(store.tracked_files(DEFAULT_SESSION_ID).is_empty());
        let _ = fs::remove_dir_all(&dir_a);
        let _ = fs::remove_dir_all(&dir_b);
    }

    #[test]
    fn restore_last_operation_restores_all_top_entries_for_same_op() {
        let path_a = temp_file("op_restore_a.txt", "a1");
        let path_b = temp_file("op_restore_b.txt", "b1");
        let mut store = BackupStore::new();
        let op_id = "op-test-00000001";

        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path_a, "a", Some(op_id))
            .unwrap();
        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path_b, "b", Some(op_id))
            .unwrap();
        fs::write(&path_a, "a2").unwrap();
        fs::write(&path_b, "b2").unwrap();

        let restored = store.restore_last_operation(DEFAULT_SESSION_ID).unwrap();
        assert_eq!(restored.op_id, op_id);
        assert_eq!(restored.restored.len(), 2);
        assert_eq!(fs::read_to_string(&path_a).unwrap(), "a1");
        assert_eq!(fs::read_to_string(&path_b).unwrap(), "b1");
    }

    #[test]
    fn restore_last_operation_deletes_tombstone_destination() {
        let dir = std::env::temp_dir().join("aft_backup_tombstone_delete_test");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let source = dir.join("source.txt");
        let destination = dir.join("destination.txt");
        fs::write(&source, "original").unwrap();

        let mut store = BackupStore::new();
        let op_id = "op-tombstone-delete";
        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &source, "move source", Some(op_id))
            .unwrap();
        fs::rename(&source, &destination).unwrap();
        store
            .snapshot_op_tombstone(DEFAULT_SESSION_ID, op_id, &destination, "created dest")
            .unwrap();

        let restored = store.restore_last_operation(DEFAULT_SESSION_ID).unwrap();
        assert_eq!(restored.op_id, op_id);
        assert_eq!(restored.restored.len(), 1);
        assert_eq!(fs::read_to_string(&source).unwrap(), "original");
        assert!(!destination.exists());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn restore_last_operation_rolls_back_source_when_tombstone_delete_fails() {
        let dir = std::env::temp_dir().join("aft_backup_tombstone_atomic_test");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let source = dir.join("source.txt");
        let destination = dir.join("destination.txt");
        fs::write(&source, "original").unwrap();

        let mut store = BackupStore::new();
        let op_id = "op-tombstone-atomic";
        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &source, "move source", Some(op_id))
            .unwrap();
        fs::rename(&source, &destination).unwrap();
        store
            .snapshot_op_tombstone(DEFAULT_SESSION_ID, op_id, &destination, "created dest")
            .unwrap();

        fs::remove_file(&destination).unwrap();
        fs::create_dir(&destination).unwrap();
        let result = store.restore_last_operation(DEFAULT_SESSION_ID);

        assert!(result.is_err(), "directory tombstone target should fail");
        assert!(
            !source.exists(),
            "source restore must roll back when destination deletion fails"
        );
        assert!(
            destination.is_dir(),
            "failed tombstone target should remain"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    // Uses Unix-specific PermissionsExt::set_mode to make a target file
    // read-only and force the staging-phase write of the two-phase-commit
    // restore to fail. The atomicity logic it exercises is platform-independent
    // — Windows has different mechanisms for forcing write failures, covered
    // separately.
    #[cfg(unix)]
    #[test]
    fn restore_last_operation_is_atomic_when_a_write_fails() {
        let dir = std::env::temp_dir().join("aft_backup_tests_atomic_restore");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path_a = dir.join("a.txt");
        let path_b = dir.join("b.txt");
        let path_c = dir.join("c.txt");
        fs::write(&path_a, "a-original").unwrap();
        fs::write(&path_b, "b-original").unwrap();
        fs::write(&path_c, "c-original").unwrap();

        let mut store = BackupStore::new();
        let op_id = "op-atomic-restore-01";
        let id_a = store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path_a, "a", Some(op_id))
            .unwrap()
            .unwrap();
        let id_b = store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path_b, "b", Some(op_id))
            .unwrap()
            .unwrap();
        let id_c = store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path_c, "c", Some(op_id))
            .unwrap()
            .unwrap();
        fs::write(&path_a, "a-modified").unwrap();
        fs::write(&path_b, "b-modified").unwrap();
        fs::write(&path_c, "c-modified").unwrap();

        let original_permissions = fs::metadata(&path_b).unwrap().permissions();
        let mut readonly_permissions = original_permissions.clone();
        readonly_permissions.set_mode(0o444);
        fs::set_permissions(&path_b, readonly_permissions).unwrap();

        let result = store.restore_last_operation(DEFAULT_SESSION_ID);
        fs::set_permissions(&path_b, original_permissions).unwrap();

        assert!(result.is_err());
        assert_eq!(fs::read_to_string(&path_a).unwrap(), "a-modified");
        assert_eq!(fs::read_to_string(&path_b).unwrap(), "b-modified");
        assert_eq!(fs::read_to_string(&path_c).unwrap(), "c-modified");

        let history_a = store.history(DEFAULT_SESSION_ID, &path_a);
        let history_b = store.history(DEFAULT_SESSION_ID, &path_b);
        let history_c = store.history(DEFAULT_SESSION_ID, &path_c);
        assert_eq!(history_a.len(), 1);
        assert_eq!(history_b.len(), 1);
        assert_eq!(history_c.len(), 1);
        assert_eq!(history_a[0].backup_id, id_a);
        assert_eq!(history_b[0].backup_id, id_b);
        assert_eq!(history_c[0].backup_id, id_c);
        assert_eq!(history_a[0].op_id.as_deref(), Some(op_id));
        assert_eq!(history_b[0].op_id.as_deref(), Some(op_id));
        assert_eq!(history_c[0].op_id.as_deref(), Some(op_id));

        let restored = store.restore_last_operation(DEFAULT_SESSION_ID).unwrap();
        assert_eq!(restored.op_id, op_id);
        assert_eq!(restored.restored.len(), 3);
        assert_eq!(fs::read_to_string(&path_a).unwrap(), "a-original");
        assert_eq!(fs::read_to_string(&path_b).unwrap(), "b-original");
        assert_eq!(fs::read_to_string(&path_c).unwrap(), "c-original");

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn restore_last_operation_restores_only_most_recent_op() {
        let path_a = temp_file("op_recent_a.txt", "a1");
        let path_b = temp_file("op_recent_b.txt", "b1");
        let mut store = BackupStore::new();

        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path_a, "older", Some("op-older"))
            .unwrap();
        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path_b, "newer", Some("op-newer"))
            .unwrap();
        fs::write(&path_a, "a2").unwrap();
        fs::write(&path_b, "b2").unwrap();

        let restored = store.restore_last_operation(DEFAULT_SESSION_ID).unwrap();
        assert_eq!(restored.op_id, "op-newer");
        assert_eq!(restored.restored.len(), 1);
        assert_eq!(fs::read_to_string(&path_a).unwrap(), "a2");
        assert_eq!(fs::read_to_string(&path_b).unwrap(), "b1");
    }

    #[test]
    fn restore_recreates_missing_parent_directories() {
        // Simulate aft_delete files: [dir/] with recursive: true:
        // the parent directories are gone by the time we restore.
        let dir = std::env::temp_dir().join("aft_backup_tests_recreate_parents");
        let _ = fs::remove_dir_all(&dir);
        let nested = dir.join("nested");
        fs::create_dir_all(&nested).unwrap();
        let path = nested.join("inner.txt");
        fs::write(&path, "original").unwrap();

        let mut store = BackupStore::new();
        let op_id = "op-recreate-parents-01";
        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path, "original", Some(op_id))
            .unwrap();

        // Real-world delete sequence: tree is wiped before undo runs.
        fs::remove_dir_all(&dir).unwrap();
        assert!(!path.exists());
        assert!(!nested.exists());
        assert!(!dir.exists());

        let restored = store.restore_last_operation(DEFAULT_SESSION_ID).unwrap();
        assert_eq!(restored.op_id, op_id);
        assert_eq!(restored.restored.len(), 1);
        assert!(
            path.exists(),
            "file should be restored even though both nested/ and dir/ were missing"
        );
        assert_eq!(fs::read_to_string(&path).unwrap(), "original");

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn restore_last_operation_ignores_legacy_entries_without_op_id() {
        let path = temp_file("op_legacy_none.txt", "v1");
        let mut store = BackupStore::new();

        store.snapshot(DEFAULT_SESSION_ID, &path, "legacy").unwrap();
        fs::write(&path, "v2").unwrap();

        let err = store.restore_last_operation(DEFAULT_SESSION_ID);
        assert!(matches!(err, Err(AftError::NoUndoHistory { .. })));
        assert_eq!(fs::read_to_string(&path).unwrap(), "v2");
    }

    #[test]
    fn schema_v2_meta_loads_with_none_op_id_and_persists_as_v3() {
        let dir = std::env::temp_dir().join("aft_backup_v2_to_v3_test");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let file_path = temp_file("v2_to_v3.txt", "original");
        let key = canonicalize_key(&file_path);
        let session_dir = dir
            .join("backups")
            .join(BackupStore::session_hash(DEFAULT_SESSION_ID));
        let path_dir = session_dir.join(BackupStore::path_hash(&key));
        fs::create_dir_all(&path_dir).unwrap();
        fs::write(path_dir.join("0.bak"), "original").unwrap();
        fs::write(
            session_dir.join("session.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": 2,
                "session_id": DEFAULT_SESSION_ID,
                "last_accessed": current_timestamp(),
            }))
            .unwrap(),
        )
        .unwrap();
        fs::write(
            path_dir.join("meta.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": 2,
                "session_id": DEFAULT_SESSION_ID,
                "path": key.display().to_string(),
                "count": 1,
            }))
            .unwrap(),
        )
        .unwrap();

        let mut store = BackupStore::new();
        store.set_storage_dir(dir.clone(), 72);
        assert!(store
            .load_from_disk_if_needed(DEFAULT_SESSION_ID, &key)
            .unwrap());
        let history = store.history(DEFAULT_SESSION_ID, &file_path);
        assert_eq!(history.len(), 1);
        assert_eq!(history[0].op_id, None);

        fs::write(&file_path, "second").unwrap();
        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &file_path, "second", Some("op-v3"))
            .unwrap();
        let written: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(path_dir.join("meta.json")).unwrap()).unwrap();
        assert_eq!(written["schema_version"], SCHEMA_VERSION);
        assert_eq!(written["entries"][0]["op_id"], serde_json::Value::Null);
        assert_eq!(written["entries"][1]["op_id"], "op-v3");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn per_file_restore_latest_still_works_with_op_ids() {
        let path = temp_file("op_per_file.txt", "v1");
        let mut store = BackupStore::new();

        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path, "op", Some("op-file"))
            .unwrap();
        fs::write(&path, "v2").unwrap();

        let (entry, _) = store.restore_latest(DEFAULT_SESSION_ID, &path).unwrap();
        assert_eq!(entry.op_id.as_deref(), Some("op-file"));
        assert_eq!(fs::read_to_string(&path).unwrap(), "v1");
    }

    #[test]
    fn per_file_restore_latest_deletes_tombstone() {
        let dir = std::env::temp_dir().join("aft_backup_per_file_tombstone_test");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("created.txt");
        fs::write(&path, "created").unwrap();

        let mut store = BackupStore::new();
        let id = store
            .snapshot_op_tombstone(DEFAULT_SESSION_ID, "op-create", &path, "created")
            .unwrap()
            .unwrap();

        let (entry, _) = store.restore_latest(DEFAULT_SESSION_ID, &path).unwrap();
        assert_eq!(entry.backup_id, id);
        assert!(!path.exists(), "tombstone undo should delete the file");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_disk_index_skips_tampered_meta_path_hash_mismatch() {
        let dir = std::env::temp_dir().join("aft_backup_tampered_meta_skip_test");
        let _ = fs::remove_dir_all(&dir);
        let backups = dir.join("backups");
        let session_dir = backups.join(BackupStore::session_hash(DEFAULT_SESSION_ID));
        let path_dir = session_dir.join("not-the-path-hash");
        fs::create_dir_all(&path_dir).unwrap();
        fs::write(
            session_dir.join("session.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": SCHEMA_VERSION,
                "session_id": DEFAULT_SESSION_ID,
                "last_accessed": current_timestamp(),
            }))
            .unwrap(),
        )
        .unwrap();
        fs::write(path_dir.join("0.bak"), "outside").unwrap();
        fs::write(
            path_dir.join("meta.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": SCHEMA_VERSION,
                "session_id": DEFAULT_SESSION_ID,
                "path": "/tmp/aft-malicious-overwrite-target.txt",
                "count": 1,
                "entries": [{
                    "backup_id": "backup-0",
                    "timestamp": current_timestamp(),
                    "order": "1",
                    "description": "tampered",
                    "op_id": "op-tampered",
                    "kind": "content",
                }]
            }))
            .unwrap(),
        )
        .unwrap();

        let mut store = BackupStore::new();
        store.set_storage_dir(dir.clone(), 72);

        assert!(store.sessions_with_backups().is_empty());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn restore_last_operation_uses_only_top_entries_and_persisted_order() {
        let path_a = temp_file("op_order_a.txt", "a1");
        let path_b = temp_file("op_order_b.txt", "b1");
        let mut store = BackupStore::new();

        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path_a, "buried", Some("op-buried"))
            .unwrap();
        store
            .snapshot(DEFAULT_SESSION_ID, &path_a, "top without op")
            .unwrap();
        store
            .snapshot_with_op(DEFAULT_SESSION_ID, &path_b, "top", Some("op-top"))
            .unwrap();

        let key_a = canonicalize_key(&path_a);
        let key_b = canonicalize_key(&path_b);
        let files = store.entries.get_mut(DEFAULT_SESSION_ID).unwrap();
        files.get_mut(&key_a).unwrap()[0].order = u128::MAX;
        files.get_mut(&key_a).unwrap()[1].order = 1;
        files.get_mut(&key_b).unwrap()[0].order = 2;

        fs::write(&path_a, "a2").unwrap();
        fs::write(&path_b, "b2").unwrap();

        let restored = store.restore_last_operation(DEFAULT_SESSION_ID).unwrap();
        assert_eq!(restored.op_id, "op-top");
        assert_eq!(restored.restored.len(), 1);
        assert_eq!(fs::read_to_string(&path_a).unwrap(), "a2");
        assert_eq!(fs::read_to_string(&path_b).unwrap(), "b1");
    }

    #[test]
    fn append_only_v2_adds_one_content_file_at_steady_depth() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("append_only.txt");
        fs::write(&path, "v0").unwrap();
        let mut store = BackupStore::new();
        store.set_storage_dir(dir.path().to_path_buf(), 72);

        for i in 0..MAX_UNDO_DEPTH {
            store
                .snapshot(DEFAULT_SESSION_ID, &path, "push")
                .unwrap()
                .unwrap();
            fs::write(&path, format!("v{}", i + 1)).unwrap();
        }

        let key = canonicalize_key(&path);
        let stack_dir = store
            .session_dir(DEFAULT_SESSION_ID)
            .unwrap()
            .join(BackupStore::path_hash(&key));
        let before = backup_content_names(&stack_dir);
        assert_eq!(before.len(), MAX_UNDO_DEPTH);

        store
            .snapshot(DEFAULT_SESSION_ID, &path, "steady push")
            .unwrap()
            .unwrap();
        let after = backup_content_names(&stack_dir);
        assert_eq!(after.len(), MAX_UNDO_DEPTH);
        assert_eq!(after.difference(&before).count(), 1);
        assert_eq!(before.difference(&after).count(), 1);

        let meta: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(stack_dir.join("meta.json")).unwrap())
                .unwrap();
        assert_eq!(
            meta.get("format_version").and_then(|v| v.as_str()),
            Some("v2")
        );
        assert!(meta_entries(&meta)
            .unwrap()
            .iter()
            .all(|entry| entry.get("content_path").and_then(|v| v.as_str()).is_some()));
    }

    #[test]
    fn legacy_stack_migrates_to_v2_on_next_write() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("legacy.txt");
        fs::write(&path, "current").unwrap();
        let key = canonicalize_key(&path);
        let session_dir = dir
            .path()
            .join("backups")
            .join(BackupStore::session_hash(DEFAULT_SESSION_ID));
        let stack_dir = session_dir.join(BackupStore::path_hash(&key));
        fs::create_dir_all(&stack_dir).unwrap();
        fs::write(
            session_dir.join("session.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": SCHEMA_VERSION,
                "session_id": DEFAULT_SESSION_ID,
                "last_accessed": current_timestamp(),
            }))
            .unwrap(),
        )
        .unwrap();
        fs::write(stack_dir.join("0.bak"), "legacy").unwrap();
        fs::write(
            stack_dir.join("meta.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": SCHEMA_VERSION,
                "session_id": DEFAULT_SESSION_ID,
                "path": key.display().to_string(),
                "count": 1,
                "entries": [{
                    "backup_id": "backup-0",
                    "timestamp": current_timestamp(),
                    "order": "1",
                    "description": "legacy",
                    "kind": "content",
                }]
            }))
            .unwrap(),
        )
        .unwrap();

        let mut store = BackupStore::new();
        store.set_storage_dir(dir.path().to_path_buf(), 72);
        assert_eq!(
            store.history(DEFAULT_SESSION_ID, &path)[0].content,
            "legacy"
        );

        store
            .snapshot(DEFAULT_SESSION_ID, &path, "migrate")
            .unwrap()
            .unwrap();
        let meta: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(stack_dir.join("meta.json")).unwrap())
                .unwrap();
        assert_eq!(
            meta.get("format_version").and_then(|v| v.as_str()),
            Some("v2")
        );
        assert!(!stack_dir.join("0.bak").exists());
        assert_eq!(backup_content_names(&stack_dir).len(), 2);
    }

    #[test]
    fn snapshot_reloads_non_empty_stale_stack_before_append() {
        let project = tempfile::tempdir().unwrap();
        let storage = tempfile::tempdir().unwrap();
        let path = project.path().join("stale-memory.txt");
        fs::write(&path, "v0").unwrap();
        let policy = BackupPolicy {
            enabled: true,
            max_depth: 2,
            max_file_size: None,
        };

        let mut store_a = BackupStore::new();
        store_a.set_storage_dir(storage.path().to_path_buf(), 72);
        store_a.set_policy(policy);
        store_a
            .snapshot(DEFAULT_SESSION_ID, &path, "a captures v0")
            .unwrap();
        fs::write(&path, "v1").unwrap();

        let mut store_b = BackupStore::new();
        store_b.set_storage_dir(storage.path().to_path_buf(), 72);
        store_b.set_policy(policy);
        store_b
            .snapshot(DEFAULT_SESSION_ID, &path, "b captures v1")
            .unwrap();
        fs::write(&path, "v2").unwrap();

        store_a
            .snapshot(DEFAULT_SESSION_ID, &path, "a captures v2")
            .unwrap();

        let mut fresh = BackupStore::new();
        fresh.set_storage_dir(storage.path().to_path_buf(), 72);
        let contents = fresh
            .history(DEFAULT_SESSION_ID, &path)
            .into_iter()
            .map(|entry| entry.content)
            .collect::<Vec<_>>();
        assert_eq!(contents, vec!["v1".to_string(), "v2".to_string()]);
    }

    #[test]
    fn restore_latest_clears_stale_memory_when_disk_stack_disappears() {
        let project = tempfile::tempdir().unwrap();
        let storage = tempfile::tempdir().unwrap();
        let session = "stale-resurrection-session";
        let path = project.path().join("stale-resurrection.txt");
        fs::write(&path, "v0").unwrap();

        let mut store_a = BackupStore::new();
        store_a.set_storage_dir(storage.path().to_path_buf(), 72);
        store_a.snapshot(session, &path, "a captures v0").unwrap();
        fs::write(&path, "v1").unwrap();

        let mut store_b = BackupStore::new();
        store_b.set_storage_dir(storage.path().to_path_buf(), 72);
        let (restored, _) = store_b.restore_latest(session, &path).unwrap();
        assert_eq!(restored.content, "v0");

        fs::write(&path, "current after other restore").unwrap();
        let error = store_a.restore_latest(session, &path).unwrap_err();

        assert_eq!(error.code(), "no_undo_history");
        assert_eq!(
            fs::read_to_string(&path).unwrap(),
            "current after other restore"
        );
        let key = canonicalize_key(&path);
        assert!(store_a
            .entries
            .get(session)
            .and_then(|files| files.get(&key))
            .is_none());

        let snapshot_path = project.path().join("stale-snapshot.txt");
        fs::write(&snapshot_path, "snapshot v0").unwrap();
        let mut store_c = BackupStore::new();
        store_c.set_storage_dir(storage.path().to_path_buf(), 72);
        store_c
            .snapshot(session, &snapshot_path, "c captures v0")
            .unwrap();
        fs::write(&snapshot_path, "snapshot v1").unwrap();
        let mut store_d = BackupStore::new();
        store_d.set_storage_dir(storage.path().to_path_buf(), 72);
        store_d.restore_latest(session, &snapshot_path).unwrap();

        fs::write(&snapshot_path, "snapshot current").unwrap();
        store_c
            .snapshot(session, &snapshot_path, "c captures current")
            .unwrap();
        let mut fresh = BackupStore::new();
        fresh.set_storage_dir(storage.path().to_path_buf(), 72);
        let contents = fresh
            .history(session, &snapshot_path)
            .into_iter()
            .map(|entry| entry.content)
            .collect::<Vec<_>>();
        assert_eq!(contents, vec!["snapshot current".to_string()]);
    }

    #[test]
    fn restore_last_operation_returns_retry_error_under_unbounded_key_churn() {
        let project = tempfile::tempdir().unwrap();
        let storage = tempfile::tempdir().unwrap();
        let session = "restore-churn-session";
        let base_path = project.path().join("base.txt");
        fs::write(&base_path, "base before").unwrap();
        let mut base_store = BackupStore::new();
        base_store.set_storage_dir(storage.path().to_path_buf(), 72);
        base_store
            .snapshot_with_op(session, &base_path, "base op", Some("op-base"))
            .unwrap();
        fs::write(&base_path, "base after").unwrap();

        let churn_count = Arc::new(Mutex::new(0usize));
        let hook_count = churn_count.clone();
        let hook_project = project.path().to_path_buf();
        let hook_storage = storage.path().to_path_buf();
        set_restore_before_lock_hook_for_tests(session, move |_| {
            let mut count = hook_count.lock().unwrap();
            let churn_path = hook_project.join(format!("churn-{}.txt", *count));
            fs::write(&churn_path, format!("churn before {}", *count)).unwrap();
            let mut churn_store = BackupStore::new();
            churn_store.set_storage_dir(hook_storage.clone(), 72);
            let op_id = format!("op-churn-{}", *count);
            churn_store
                .snapshot_with_op(session, &churn_path, "churn op", Some(&op_id))
                .unwrap();
            fs::write(&churn_path, format!("churn after {}", *count)).unwrap();
            *count += 1;
            *count < MAX_RESTORE_OPERATION_LOCK_RETRIES
        });

        let mut restore_store = BackupStore::new();
        restore_store.set_storage_dir(storage.path().to_path_buf(), 72);
        let error = restore_store.restore_last_operation(session).unwrap_err();

        assert_eq!(error.code(), "io_error");
        assert!(error
            .to_string()
            .contains("backup stack changing under concurrent activity; retry"));
        assert_eq!(
            *churn_count.lock().unwrap(),
            MAX_RESTORE_OPERATION_LOCK_RETRIES
        );
    }

    #[test]
    fn restore_last_operation_rescans_stack_after_locking() {
        let project = tempfile::tempdir().unwrap();
        let storage = tempfile::tempdir().unwrap();
        let session = "restore-toctou-session";
        let path = project.path().join("restore-toctou.txt");
        fs::write(&path, "v0").unwrap();

        let mut store_a = BackupStore::new();
        store_a.set_storage_dir(storage.path().to_path_buf(), 72);
        store_a
            .snapshot_with_op(session, &path, "old op", Some("op-old"))
            .unwrap();
        fs::write(&path, "v1").unwrap();

        let hook_storage = storage.path().to_path_buf();
        let hook_path = path.clone();
        set_restore_before_lock_hook_for_tests(session, move |_| {
            let mut store_b = BackupStore::new();
            store_b.set_storage_dir(hook_storage.clone(), 72);
            store_b
                .snapshot_with_op(session, &hook_path, "new op", Some("op-new"))
                .unwrap();
            fs::write(&hook_path, "v2").unwrap();
            false
        });

        let restored = store_a.restore_last_operation(session).unwrap();

        assert_eq!(restored.op_id, "op-new");
        assert_eq!(fs::read_to_string(&path).unwrap(), "v1");
    }

    #[test]
    fn corrupt_v2_meta_fails_closed_for_operation_and_single_restore() {
        let project = tempfile::tempdir().unwrap();
        let storage = tempfile::tempdir().unwrap();
        let session = "corrupt-v2-session";
        let path = project.path().join("corrupt-v2.txt");
        fs::write(&path, "current").unwrap();
        let key = canonicalize_key(&path);
        let session_dir = storage
            .path()
            .join("backups")
            .join(BackupStore::session_hash(session));
        let stack_dir = session_dir.join(BackupStore::path_hash(&key));
        fs::create_dir_all(&stack_dir).unwrap();
        fs::write(
            session_dir.join("session.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": SCHEMA_VERSION,
                "session_id": session,
                "last_accessed": current_timestamp(),
            }))
            .unwrap(),
        )
        .unwrap();
        fs::write(
            stack_dir.join("meta.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": SCHEMA_VERSION,
                "format_version": "v2",
                "session_id": session,
                "path": key.display().to_string(),
                "count": 1,
                "entries": [{
                    "backup_id": "backup-corrupt",
                    "timestamp": current_timestamp(),
                    "order": "9",
                    "description": "corrupt disk should win over DB fallback",
                    "op_id": "op-corrupt",
                    "kind": "content",
                    "content_path": "bak_9_backup-corrupt.bak",
                }]
            }))
            .unwrap(),
        )
        .unwrap();

        let conn = crate::db::open(&storage.path().join("aft.db")).unwrap();
        let fallback_path = stack_dir.join("db-fallback.bak");
        fs::write(&fallback_path, "db fallback").unwrap();
        crate::db::backups::upsert_backup(
            &conn,
            &BackupRow {
                backup_id: "backup-db".to_string(),
                harness: "opencode".to_string(),
                session_id: session.to_string(),
                project_key: "project".to_string(),
                op_id: Some("op-corrupt".to_string()),
                order: 9,
                file_path: key.display().to_string(),
                path_hash: BackupStore::path_hash(&key),
                backup_path: Some(fallback_path.display().to_string()),
                kind: "content".to_string(),
                description: "db fallback".to_string(),
                created_at: i64::try_from(current_timestamp()).unwrap(),
                is_tombstone: false,
            },
        )
        .unwrap();
        let shared = Arc::new(Mutex::new(conn));

        let mut single = BackupStore::new();
        single.set_storage_dir(storage.path().to_path_buf(), 72);
        single.set_db_harness(Harness::Opencode);
        single.set_db_project_key("project".to_string());
        single.set_db_pool(shared.clone());
        let single_error = single.restore_latest(session, &path).unwrap_err();
        assert_eq!(single_error.code(), "io_error");
        assert_eq!(fs::read_to_string(&path).unwrap(), "current");

        let mut operation = BackupStore::new();
        operation.set_storage_dir(storage.path().to_path_buf(), 72);
        operation.set_db_harness(Harness::Opencode);
        operation.set_db_project_key("project".to_string());
        operation.set_db_pool(shared);
        let operation_error = operation.restore_last_operation(session).unwrap_err();
        assert_eq!(operation_error.code(), "io_error");
        assert_eq!(fs::read_to_string(&path).unwrap(), "current");
    }

    #[test]
    fn replace_file_replaces_existing_meta_with_single_rename_path() {
        let dir = tempfile::tempdir().unwrap();
        let meta_path = dir.path().join("meta.json");
        let temp_path = dir.path().join("meta.tmp");
        fs::write(&meta_path, "old").unwrap();
        fs::write(&temp_path, "new").unwrap();

        replace_file(&temp_path, &meta_path).unwrap();

        assert_eq!(fs::read_to_string(&meta_path).unwrap(), "new");
        assert!(!temp_path.exists());
    }

    #[test]
    fn snapshot_write_failure_restores_full_pre_trim_stack() {
        let project = tempfile::tempdir().unwrap();
        let storage = tempfile::tempdir().unwrap();
        let session = "rollback-pretrim-session";
        let path = project.path().join("rollback.txt");
        fs::write(&path, "v0").unwrap();
        let mut store = BackupStore::new();
        store.set_storage_dir(storage.path().to_path_buf(), 72);
        store.set_policy(BackupPolicy {
            enabled: true,
            max_depth: 2,
            max_file_size: None,
        });

        store.snapshot(session, &path, "first").unwrap();
        fs::write(&path, "v1").unwrap();
        store.snapshot(session, &path, "second").unwrap();
        fs::write(&path, "v2").unwrap();
        let key = canonicalize_key(&path);
        let before_file_stack = store
            .entries
            .get(session)
            .unwrap()
            .get(&key)
            .unwrap()
            .clone();

        store.fail_next_disk_write_for_tests();
        let error = store.snapshot(session, &path, "third").unwrap_err();
        assert_eq!(error.code(), "io_error");
        let after_file_stack = store.entries.get(session).unwrap().get(&key).unwrap();
        assert_eq!(
            after_file_stack
                .iter()
                .map(|entry| entry.description.as_str())
                .collect::<Vec<_>>(),
            before_file_stack
                .iter()
                .map(|entry| entry.description.as_str())
                .collect::<Vec<_>>()
        );

        let tombstone = project.path().join("created-by-op.txt");
        store
            .snapshot_op_tombstone(session, "op-one", &tombstone, "created one")
            .unwrap();
        store
            .snapshot_op_tombstone(session, "op-two", &tombstone, "created two")
            .unwrap();
        let tombstone_key = canonicalize_key(&tombstone);
        let before_tombstone_stack = store
            .entries
            .get(session)
            .unwrap()
            .get(&tombstone_key)
            .unwrap()
            .clone();

        store.fail_next_disk_write_for_tests();
        let error = store
            .snapshot_op_tombstone(session, "op-three", &tombstone, "created three")
            .unwrap_err();
        assert_eq!(error.code(), "io_error");
        let after_tombstone_stack = store
            .entries
            .get(session)
            .unwrap()
            .get(&tombstone_key)
            .unwrap();
        assert_eq!(
            after_tombstone_stack
                .iter()
                .map(|entry| entry.op_id.as_deref())
                .collect::<Vec<_>>(),
            before_tombstone_stack
                .iter()
                .map(|entry| entry.op_id.as_deref())
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn lowering_max_depth_prunes_disk_content_immediately() {
        let project = tempfile::tempdir().unwrap();
        let storage = tempfile::tempdir().unwrap();
        let path = project.path().join("policy-prune.txt");
        fs::write(&path, "v0").unwrap();
        let mut store = BackupStore::new();
        store.set_storage_dir(storage.path().to_path_buf(), 72);

        for i in 0..3 {
            store
                .snapshot(DEFAULT_SESSION_ID, &path, &format!("snapshot {i}"))
                .unwrap();
            fs::write(&path, format!("v{}", i + 1)).unwrap();
        }

        let key = canonicalize_key(&path);
        let stack_dir = store
            .session_dir(DEFAULT_SESSION_ID)
            .unwrap()
            .join(BackupStore::path_hash(&key));
        assert_eq!(backup_content_names(&stack_dir).len(), 3);

        store.set_policy(BackupPolicy {
            enabled: true,
            max_depth: 1,
            max_file_size: None,
        });

        assert_eq!(backup_content_names(&stack_dir).len(), 1);
        let meta: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(stack_dir.join("meta.json")).unwrap())
                .unwrap();
        assert_eq!(meta_entry_count(&meta), Some(1));
        let mut fresh = BackupStore::new();
        fresh.set_storage_dir(storage.path().to_path_buf(), 72);
        assert_eq!(fresh.history(DEFAULT_SESSION_ID, &path).len(), 1);
    }

    #[test]
    fn v2_missing_content_fails_closed() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("missing-content.txt");
        fs::write(&path, "current").unwrap();
        let key = canonicalize_key(&path);
        let session_dir = dir
            .path()
            .join("backups")
            .join(BackupStore::session_hash(DEFAULT_SESSION_ID));
        let stack_dir = session_dir.join(BackupStore::path_hash(&key));
        fs::create_dir_all(&stack_dir).unwrap();
        fs::write(
            session_dir.join("session.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": SCHEMA_VERSION,
                "session_id": DEFAULT_SESSION_ID,
                "last_accessed": current_timestamp(),
            }))
            .unwrap(),
        )
        .unwrap();
        fs::write(
            stack_dir.join("meta.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "schema_version": SCHEMA_VERSION,
                "format_version": "v2",
                "session_id": DEFAULT_SESSION_ID,
                "path": key.display().to_string(),
                "count": 1,
                "entries": [{
                    "backup_id": "backup-0",
                    "timestamp": current_timestamp(),
                    "order": "1",
                    "description": "missing",
                    "kind": "content",
                    "content_path": "bak_1_backup-0.bak",
                }]
            }))
            .unwrap(),
        )
        .unwrap();

        let mut store = BackupStore::new();
        store.set_storage_dir(dir.path().to_path_buf(), 72);
        let error = store.restore_latest(DEFAULT_SESSION_ID, &path).unwrap_err();
        assert_eq!(error.code(), "io_error");
    }

    #[test]
    fn v2_orphan_files_are_ignored_then_pruned() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("orphan.txt");
        fs::write(&path, "v0").unwrap();
        let mut store = BackupStore::new();
        store.set_storage_dir(dir.path().to_path_buf(), 72);
        store
            .snapshot(DEFAULT_SESSION_ID, &path, "first")
            .unwrap()
            .unwrap();
        let key = canonicalize_key(&path);
        let stack_dir = store
            .session_dir(DEFAULT_SESSION_ID)
            .unwrap()
            .join(BackupStore::path_hash(&key));
        fs::write(stack_dir.join("bak_999_orphan.bak"), "orphan").unwrap();

        assert_eq!(store.history(DEFAULT_SESSION_ID, &path).len(), 1);
        fs::write(&path, "v1").unwrap();
        store
            .snapshot(DEFAULT_SESSION_ID, &path, "second")
            .unwrap()
            .unwrap();
        assert!(!stack_dir.join("bak_999_orphan.bak").exists());
    }

    fn backup_content_names(dir: &Path) -> HashSet<String> {
        fs::read_dir(dir)
            .unwrap()
            .filter_map(|entry| entry.ok())
            .filter_map(|entry| entry.file_name().to_str().map(str::to_string))
            .filter(|name| name.starts_with("bak_") && name.ends_with(".bak"))
            .collect()
    }
}