beads_rust 0.5.3

Agent-first issue tracker (SQLite + JSONL)
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
//! Path validation and allowlist enforcement for sync operations.
//!
//! This module defines the explicit allowlist of files that `br sync` is permitted
//! to touch and provides validation functions to enforce this boundary.
//!
//! # Safety Model
//!
//! The sync allowlist is a critical safety boundary. All sync I/O operations MUST
//! pass through `validate_sync_path()` before performing any file operations.
//!
//! # Allowlist
//!
//! The following paths are permitted for sync operations:
//!
//! | Pattern | Purpose |
//! |---------|---------|
//! | `.beads/*.db` | `SQLite` database files |
//! | `.beads/*.db-wal` | `SQLite` WAL files |
//! | `.beads/*.db-wal-cert` | fsqlite parallel-WAL durability certificates |
//! | `.beads/*.db-wal-cert-head` | fsqlite checkpoint hand-off head |
//! | `.beads/*.db-shm` | `SQLite` shared memory files |
//! | `.beads/*.db-journal` | `SQLite` rollback journals |
//! | `.beads/*.db-fsqlite-ns-gate` | fsqlite multi-process namespace gate |
//! | `.beads/*.db-fsqlite-ns-use` | fsqlite multi-process namespace use-count |
//! | `.beads/*.jsonl` | `JSONL` export files |
//! | `.beads/*.jsonl.tmp` | Temp files for atomic writes |
//! | `.beads/*.jsonl.<pid>.tmp` | PID-scoped temp files for atomic writes |
//! | `.beads/.manifest.json` | Export manifest |
//! | `.beads/metadata.json` | Workspace metadata |
//!
//! # External JSONL Paths
//!
//! The `BEADS_JSONL` environment variable can override the JSONL path.
//! When set to a path outside `.beads/`, sync will refuse to operate unless
//! `--allow-external-jsonl` is explicitly provided.
//!
//! # Git Path Safety
//!
//! Sync operations NEVER access `.git/` directories. This is a hard safety invariant
//! enforced by `validate_no_git_path()`. Even with `--allow-external-jsonl`, git
//! paths are always rejected.
//!
//! # References
//!
//! - `SYNC_SAFETY_INVARIANTS.md`: PC-1, PC-2, PC-3, PC-4, NG-5, NG-6, NGI-1, NGI-3

use crate::error::{BeadsError, Result};
use sha2::{Digest, Sha256};
use std::ffi::OsStr;
use std::fs::File;
use std::path::{Path, PathBuf};
#[cfg(not(any(unix, windows)))]
use std::sync::Arc;
use std::time::{Instant, SystemTime};
use tracing::{debug, warn};

fn raw_os_str_sha256(value: &OsStr) -> String {
    let mut hasher = Sha256::new();
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        hasher.update(value.as_bytes());
    }
    #[cfg(windows)]
    {
        use std::os::windows::ffi::OsStrExt;
        for unit in value.encode_wide() {
            hasher.update(unit.to_le_bytes());
        }
    }
    #[cfg(not(any(unix, windows)))]
    hasher.update(value.to_string_lossy().as_bytes());
    crate::util::hex_encode(&hasher.finalize())
}

fn external_path_sha256(path: &Path) -> String {
    raw_os_str_sha256(path.as_os_str())
}

fn external_path_descriptor(path: &Path) -> String {
    format!("<external-path sha256={}>", external_path_sha256(path))
}

/// Files explicitly allowed for sync operations within `.beads/`.
///
/// This list is exhaustive - any file not matching these patterns is rejected.
pub const ALLOWED_EXTENSIONS: &[&str] = &[
    "db",                 // SQLite database
    "db-wal",             // SQLite WAL
    "db-wal-cert",        // fsqlite 0.2+ parallel-WAL durability certificates
    "db-wal-cert-head",   // fsqlite 0.2+ checkpoint hand-off head
    "db-shm",             // SQLite shared memory
    "db-journal",         // SQLite rollback journal
    "db-fsqlite-ns-gate", // fsqlite multi-process namespace gate
    "db-fsqlite-ns-use",  // fsqlite multi-process namespace use-count
    "jsonl",              // JSONL export
    "jsonl.tmp",          // Atomic write temp files (plus pid-scoped .jsonl.<pid>.tmp)
];

/// Files explicitly allowed by exact name within `.beads/`.
pub const ALLOWED_EXACT_NAMES: &[&str] = &[".manifest.json", "metadata.json"];

/// Result of path validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathValidation {
    /// Path is allowed for sync operations.
    Allowed,
    /// Path is outside the beads directory.
    OutsideBeadsDir { path: PathBuf, beads_dir: PathBuf },
    /// Path has a disallowed extension.
    DisallowedExtension { path: PathBuf, extension: String },
    /// Path contains traversal sequences (e.g., `..`).
    TraversalAttempt { path: PathBuf },
    /// Path is a symlink pointing outside the beads directory.
    SymlinkEscape { path: PathBuf, target: PathBuf },
    /// Path failed canonicalization.
    CanonicalizationFailed { path: PathBuf, error: String },
    /// Path exists but is not a regular file.
    NonRegularFile { path: PathBuf },
    /// Path targets git internals (.git directory).
    GitPathAttempt { path: PathBuf },
}

impl PathValidation {
    /// Returns true if the path is allowed.
    #[must_use]
    pub const fn is_allowed(&self) -> bool {
        matches!(self, Self::Allowed)
    }

    /// Returns the rejection reason as a human-readable string.
    #[must_use]
    pub fn rejection_reason(&self) -> Option<String> {
        match self {
            Self::Allowed => None,
            Self::OutsideBeadsDir { path, beads_dir } => Some(format!(
                "Path '{}' is outside the beads directory '{}'",
                path.display(),
                beads_dir.display()
            )),
            Self::DisallowedExtension { path, extension } => Some(format!(
                "Path '{}' has disallowed extension '{}' (allowed: {:?}, plus pid-scoped '*.jsonl.<pid>.tmp')",
                path.display(),
                extension,
                ALLOWED_EXTENSIONS
            )),
            Self::TraversalAttempt { path } => Some(format!(
                "Path '{}' contains traversal sequences",
                path.display()
            )),
            Self::SymlinkEscape { path, target } => Some(format!(
                "Symlink '{}' points outside beads directory to '{}'",
                path.display(),
                target.display()
            )),
            Self::CanonicalizationFailed { path, error } => Some(format!(
                "Failed to canonicalize path '{}': {}",
                path.display(),
                error
            )),
            Self::NonRegularFile { path } => {
                Some(format!("Path '{}' must be a regular file", path.display()))
            }
            Self::GitPathAttempt { path } => Some(format!(
                "Path '{}' targets git internals - sync never accesses .git/ (safety invariant NGI-3)",
                path.display()
            )),
        }
    }
}

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

    for component in path.components() {
        match component {
            std::path::Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
            std::path::Component::RootDir => normalized.push(component.as_os_str()),
            std::path::Component::CurDir => {}
            std::path::Component::Normal(part) => normalized.push(part),
            std::path::Component::ParentDir => {
                if !normalized.pop() {
                    return None;
                }
            }
        }
    }

    Some(normalized)
}

/// Reduces a Windows verbatim spelling (`\\?\C:\…`, `\\?\UNC\server\share\…`)
/// to its plain equivalent without touching the filesystem.
///
/// This is a *comparison* aid only: authority checks never open or traverse
/// through the simplified spelling. Non-verbatim inputs and verbatim device
/// prefixes with no plain equivalent pass through unchanged.
#[cfg(windows)]
fn strip_verbatim_prefix_lexically(path: &Path) -> PathBuf {
    use std::path::{Component, Prefix};

    let mut components = path.components();
    let Some(Component::Prefix(prefix)) = components.next() else {
        return path.to_path_buf();
    };
    let mut simplified = match prefix.kind() {
        Prefix::VerbatimDisk(disk) => PathBuf::from(format!(r"{}:\", char::from(disk))),
        Prefix::VerbatimUNC(server, share) => {
            let mut unc = std::ffi::OsString::from(r"\\");
            unc.push(server);
            unc.push(r"\");
            unc.push(share);
            PathBuf::from(unc)
        }
        _ => return path.to_path_buf(),
    };
    for component in components {
        match component {
            Component::RootDir => {}
            other => simplified.push(other.as_os_str()),
        }
    }
    simplified
}

/// One shared spelling for authority-path comparisons (#413).
///
/// Windows mixes lexically absolute pinned routes
/// (`C:\repo\.beads\issues.jsonl`, possibly through 8.3 short aliases such as
/// `RUNNER~1`) with `fs::canonicalize` products
/// (`\\?\C:\repo\.beads\issues.jsonl`). Byte comparison of those spellings can
/// never succeed even though they name one filesystem object, so every
/// equality or containment decision between a pinned/display route and a
/// canonical one resolves both operands through this function first.
///
/// It deliberately runs at *comparison* time on throwaway copies:
/// [`pin_jsonl_target`]'s no-follow, component-by-component traversal has
/// already rejected reparse routes before any comparison happens, so resolving
/// a copy of the spelling here cannot be steered by one and the pinned
/// traversal itself stays strictly lexical.
///
/// On non-Windows targets this is the identity function, keeping every
/// existing byte-exact comparison untouched.
#[cfg(windows)]
pub(crate) fn comparable_authority_path(path: &Path) -> PathBuf {
    // Full resolution reconciles verbatim prefixes and 8.3 short aliases in
    // one step and is exact: two distinct objects never resolve equal.
    if let Ok(resolved) = dunce::canonicalize(path) {
        return resolved;
    }
    // A missing leaf (first export) still has an existing parent: resolve the
    // parent and re-attach the exact leaf, mirroring the missing-leaf
    // convention of the canonical sidecar authority key.
    if let (Some(parent), Some(leaf)) = (path.parent(), path.file_name())
        && let Ok(resolved_parent) = dunce::canonicalize(parent)
    {
        return resolved_parent.join(leaf);
    }
    // Nothing on disk to witness: fall back to a purely lexical spelling so
    // two references to one never-created route still agree, while genuinely
    // different routes stay distinct.
    let lexical = normalize_path_lexically(path).unwrap_or_else(|| path.to_path_buf());
    strip_verbatim_prefix_lexically(&lexical)
}

/// Non-Windows targets already use one spelling convention per comparison
/// site, so the shared form is the identity and comparisons stay byte-exact.
#[cfg(not(windows))]
#[inline]
pub(crate) fn comparable_authority_path(path: &Path) -> PathBuf {
    path.to_path_buf()
}

/// Whether two authority-path spellings name the same filesystem target under
/// the shared comparison convention (#413).
///
/// A byte-equal pair short-circuits without touching the filesystem. A
/// genuinely different pair still compares unequal because both sides resolve
/// through [`comparable_authority_path`], never just one.
pub(crate) fn authority_paths_equivalent(left: &Path, right: &Path) -> bool {
    left == right || comparable_authority_path(left) == comparable_authority_path(right)
}

/// Whether `candidate` is `ancestor` itself or is contained inside it under
/// the shared comparison convention (#413).
///
/// Both operands resolve through [`comparable_authority_path`] before the
/// prefix check, so a Windows verbatim child of a plain directory is
/// contained, while genuinely external paths remain outside.
pub(crate) fn authority_path_within(candidate: &Path, ancestor: &Path) -> bool {
    candidate.starts_with(ancestor)
        || comparable_authority_path(candidate).starts_with(comparable_authority_path(ancestor))
}

fn symlink_escape_for_existing_ancestor(
    path: &Path,
    canonical_beads: &Path,
) -> Option<PathValidation> {
    for ancestor in path.ancestors() {
        let Ok(metadata) = std::fs::symlink_metadata(ancestor) else {
            continue;
        };

        if !metadata.file_type().is_symlink() {
            continue;
        }

        let target = std::fs::read_link(ancestor)
            .map(|target| resolve_symlink_target_for_validation(ancestor, &target))
            .unwrap_or_else(|_| ancestor.to_path_buf());
        if !target.starts_with(canonical_beads) {
            return Some(PathValidation::SymlinkEscape {
                path: ancestor.to_path_buf(),
                target,
            });
        }
    }

    None
}

fn resolve_symlink_target_for_validation(link_path: &Path, target: &Path) -> PathBuf {
    let anchored = if target.is_absolute() {
        target.to_path_buf()
    } else {
        link_path
            .parent()
            .unwrap_or_else(|| Path::new(""))
            .join(target)
    };
    let normalized = normalize_path_lexically(&anchored).unwrap_or(anchored);
    dunce::canonicalize(&normalized).unwrap_or(normalized)
}

/// Validates that a path does not target git internals.
///
/// This is a hard safety invariant: sync operations NEVER access `.git/` directories.
/// This check runs regardless of `allow_external` settings.
///
/// # Safety Invariants
///
/// - NGI-1: br sync NEVER executes git subprocess commands
/// - NGI-3: br sync NEVER modifies .git/ directory
///
/// # Returns
///
/// * `PathValidation::Allowed` if path does not target git
/// * `PathValidation::GitPathAttempt` if path contains `.git` component
#[must_use]
pub fn validate_no_git_path(path: &Path) -> PathValidation {
    fn has_git_component(candidate: &Path) -> bool {
        for component in candidate.components() {
            if let std::path::Component::Normal(name) = component
                && name == ".git"
            {
                return true;
            }
        }

        let path_str = candidate.to_string_lossy();
        path_str.contains("/.git/")
            || path_str.contains("\\.git\\")
            || path_str.ends_with("/.git")
            || path_str.ends_with("\\.git")
    }

    // Check raw path first
    if has_git_component(path) {
        return PathValidation::GitPathAttempt {
            path: path.to_path_buf(),
        };
    }

    // Resolve each existing ancestor. The final path or its immediate parent
    // may not exist yet, but a higher symlinked ancestor can still target .git.
    for ancestor in path.ancestors() {
        let Ok(canonical_ancestor) = dunce::canonicalize(ancestor) else {
            continue;
        };
        if has_git_component(&canonical_ancestor) {
            return PathValidation::GitPathAttempt {
                path: canonical_ancestor,
            };
        }
    }

    PathValidation::Allowed
}

/// Validates that a path is allowed for sync operations.
///
/// # Arguments
///
/// * `path` - The path to validate
/// * `beads_dir` - The `.beads` directory path (must be absolute)
///
/// # Returns
///
/// * `PathValidation::Allowed` if the path is permitted
/// * Other variants describing why the path was rejected
///
/// # Logging
///
/// - DEBUG: Logs successful validation with path details
/// - WARN: Logs rejected paths with reason
///
/// # Example
///
/// ```ignore
/// let beads_dir = PathBuf::from("/project/.beads");
/// let result = validate_sync_path(&beads_dir.join("issues.jsonl"), &beads_dir);
/// assert!(result.is_allowed());
/// ```
#[allow(clippy::too_many_lines)]
pub fn validate_sync_path(path: &Path, beads_dir: &Path) -> PathValidation {
    // Log the validation attempt
    debug!(path = %path.display(), beads_dir = %beads_dir.display(), "Validating sync path");

    // CRITICAL: Check for git path access first (hard invariant - NGI-3)
    let git_check = validate_no_git_path(path);
    if !git_check.is_allowed() {
        warn!(
            path = %path.display(),
            reason = %git_check.rejection_reason().unwrap_or_default(),
            "Git path access blocked"
        );
        return git_check;
    }

    let had_parent_dir = path
        .components()
        .any(|component| matches!(component, std::path::Component::ParentDir));
    let Some(normalized_path) = normalize_path_lexically(path) else {
        let result = PathValidation::TraversalAttempt {
            path: path.to_path_buf(),
        };
        warn!(
            path = %path.display(),
            reason = %result.rejection_reason().unwrap_or_default(),
            "Path validation rejected"
        );
        return result;
    };

    // Canonicalize the beads directory
    let canonical_beads = match dunce::canonicalize(beads_dir) {
        Ok(p) => p,
        Err(e) => {
            let result = PathValidation::CanonicalizationFailed {
                path: beads_dir.to_path_buf(),
                error: e.to_string(),
            };
            warn!(
                path = %beads_dir.display(),
                error = %e,
                "Beads directory canonicalization failed"
            );
            return result;
        }
    };

    if let Some(result) = symlink_escape_for_existing_ancestor(&normalized_path, &canonical_beads) {
        warn!(
            path = %path.display(),
            reason = %result.rejection_reason().unwrap_or_default(),
            "Path validation rejected"
        );
        return result;
    }

    if had_parent_dir
        && !normalized_path.starts_with(beads_dir)
        && !normalized_path.starts_with(&canonical_beads)
    {
        let result = PathValidation::TraversalAttempt {
            path: path.to_path_buf(),
        };
        warn!(
            path = %path.display(),
            reason = %result.rejection_reason().unwrap_or_default(),
            "Path validation rejected"
        );
        return result;
    }

    // For new files that don't exist yet, we check the parent directory
    let path_to_check = if normalized_path.exists() {
        normalized_path.clone()
    } else {
        // For non-existent files, verify the parent exists and is valid
        match normalized_path.parent() {
            Some(parent) if parent.exists() => parent.to_path_buf(),
            _ => {
                // If parent doesn't exist, just check if the path would be under beads_dir
                if let Ok(relative) = normalized_path.strip_prefix(&canonical_beads) {
                    // Path is specified relative to beads_dir
                    if !relative.to_string_lossy().contains("..") {
                        return validate_extension_and_name(&normalized_path);
                    }
                }
                // Otherwise, try to check as-is
                normalized_path.clone()
            }
        }
    };

    // Canonicalize the path (or its parent for new files)
    let canonical_path = match dunce::canonicalize(&path_to_check) {
        Ok(p) => p,
        Err(e) => {
            // For non-existent files, we can't canonicalize, so check prefix
            if !normalized_path.exists() {
                // Check if the path starts with the beads directory
                if normalized_path.starts_with(beads_dir)
                    || normalized_path.starts_with(&canonical_beads)
                {
                    return validate_extension_and_name(&normalized_path);
                }
            }
            let result = PathValidation::CanonicalizationFailed {
                path: path.to_path_buf(),
                error: e.to_string(),
            };
            warn!(
                path = %path.display(),
                error = %e,
                "Path canonicalization failed"
            );
            return result;
        }
    };

    // Check if the path is a symlink pointing outside beads_dir
    if normalized_path.is_symlink()
        && let Ok(target) = std::fs::read_link(&normalized_path)
    {
        let canonical_target = resolve_symlink_target_for_validation(&normalized_path, &target);
        if !canonical_target.starts_with(&canonical_beads) {
            let result = PathValidation::SymlinkEscape {
                path: path.to_path_buf(),
                target: canonical_target,
            };
            warn!(
                path = %path.display(),
                target = %target.display(),
                "Symlink escape detected"
            );
            return result;
        }
    }

    if normalized_path.exists() {
        match std::fs::symlink_metadata(&normalized_path) {
            Ok(metadata) if !metadata.is_file() => {
                let result = PathValidation::NonRegularFile {
                    path: path.to_path_buf(),
                };
                warn!(
                    path = %path.display(),
                    reason = %result.rejection_reason().unwrap_or_default(),
                    "Path validation rejected"
                );
                return result;
            }
            Ok(_) => {}
            Err(e) => {
                let result = PathValidation::CanonicalizationFailed {
                    path: path.to_path_buf(),
                    error: e.to_string(),
                };
                warn!(
                    path = %path.display(),
                    error = %e,
                    "Path metadata lookup failed"
                );
                return result;
            }
        }
    }

    // Verify the path is under the beads directory
    // For existing files, use the canonical path; for new files, use the parent's canonical + filename
    let effective_canonical = if normalized_path.exists() {
        canonical_path
    } else {
        canonical_path.join(normalized_path.file_name().unwrap_or_default())
    };

    if !effective_canonical.starts_with(&canonical_beads) {
        let result = PathValidation::OutsideBeadsDir {
            path: path.to_path_buf(),
            beads_dir: canonical_beads,
        };
        warn!(
            path = %path.display(),
            beads_dir = %beads_dir.display(),
            reason = %result.rejection_reason().unwrap_or_default(),
            "Path validation rejected"
        );
        return result;
    }

    // Validate extension and name
    let extension_result = validate_extension_and_name(&normalized_path);
    if !extension_result.is_allowed() {
        warn!(
            path = %path.display(),
            reason = %extension_result.rejection_reason().unwrap_or_default(),
            "Path validation rejected"
        );
        return extension_result;
    }

    debug!(path = %path.display(), "Path validated for sync I/O");
    PathValidation::Allowed
}

/// Validates that the file extension or name is in the allowlist.
fn validate_extension_and_name(path: &Path) -> PathValidation {
    let file_name = path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();

    // Check exact name matches first
    if ALLOWED_EXACT_NAMES.iter().any(|&name| file_name == name) {
        return PathValidation::Allowed;
    }

    if is_allowed_jsonl_temp_name(&file_name) {
        return PathValidation::Allowed;
    }

    // Check extension matches
    // Handle compound extensions like .jsonl.tmp
    for allowed_ext in ALLOWED_EXTENSIONS {
        if file_name.ends_with(&format!(".{allowed_ext}")) {
            return PathValidation::Allowed;
        }
    }

    // Extract simple extension for error message
    let extension = path
        .extension()
        .map_or_else(|| "none".to_string(), |e| e.to_string_lossy().to_string());

    PathValidation::DisallowedExtension {
        path: path.to_path_buf(),
        extension,
    }
}

fn is_allowed_jsonl_temp_name(file_name: &str) -> bool {
    if file_name.ends_with(".jsonl.tmp") {
        return true;
    }

    let Some(prefix) = file_name.strip_suffix(".tmp") else {
        return false;
    };
    let Some((base, pid)) = prefix.rsplit_once(".jsonl.") else {
        return false;
    };

    !base.is_empty() && !pid.is_empty() && pid.chars().all(|c| c.is_ascii_digit())
}

/// Validates a path and returns an error if it's not allowed.
///
/// This is a convenience wrapper around `validate_sync_path` that returns
/// a `Result` for easier use in sync functions.
///
/// # Errors
///
/// Returns `BeadsError::Config` with a descriptive message if the path is not allowed.
pub fn require_valid_sync_path(path: &Path, beads_dir: &Path) -> Result<()> {
    let validation = validate_sync_path(path, beads_dir);
    match validation {
        PathValidation::Allowed => Ok(()),
        _ => Err(BeadsError::Config(
            validation
                .rejection_reason()
                .unwrap_or_else(|| "Path validation failed".to_string()),
        )),
    }
}

/// Checks if a path would be allowed for sync without logging.
///
/// This is useful for preflight checks where we want to validate paths
/// before attempting operations.
#[must_use]
pub fn is_sync_path_allowed(path: &Path, beads_dir: &Path) -> bool {
    let Some(normalized_path) = normalize_path_lexically(path) else {
        return false;
    };

    validate_sync_path(&normalized_path, beads_dir).is_allowed()
}

/// Validates a path for sync operations with optional external path support.
///
/// This is the main entry point for sync path validation. It enforces:
/// 1. Git paths are ALWAYS rejected (hard invariant)
/// 2. Paths outside `.beads/` require explicit `allow_external` opt-in
/// 3. External paths must still be valid JSONL files (not arbitrary files)
///
/// # Arguments
///
/// * `path` - The path to validate
/// * `beads_dir` - The `.beads` directory path
/// * `allow_external` - Whether to allow paths outside `.beads/`
///
/// # Errors
///
/// Returns `BeadsError::Config` with a descriptive message if validation fails.
///
/// # Examples
///
/// ```ignore
/// // Normal case: path inside .beads/
/// validate_sync_path_with_external(&path, &beads_dir, false)?;
///
/// // External JSONL with opt-in
/// validate_sync_path_with_external(&external_jsonl, &beads_dir, true)?;
/// ```
pub fn validate_sync_path_with_external(
    path: &Path,
    beads_dir: &Path,
    allow_external: bool,
) -> Result<()> {
    // If a path still points at `.beads/`, keep the stricter internal
    // allowlist and symlink-escape checks even when external JSONL is enabled.
    let canonical_beads =
        dunce::canonicalize(beads_dir).unwrap_or_else(|_| beads_dir.to_path_buf());
    let resolved_path = if path.is_relative() {
        std::env::current_dir()
            .map(|cwd| cwd.join(path))
            .unwrap_or_else(|_| path.to_path_buf())
    } else {
        path.to_path_buf()
    };
    // A dotdot-carrying path that physically resolves inside `.beads/`
    // (e.g. `--db root/x/../.beads/beads.db`) must classify as internal:
    // the raw form never prefix-matches the canonicalized beads_dir, and
    // misclassifying it external refused valid workspaces (#409 routing
    // cluster). Lexical normalization only widens into the *stricter*
    // internal branch, whose validate_sync_path re-normalizes and runs the
    // symlink-escape checks itself.
    let normalized_resolved = normalize_path_lexically(&resolved_path);
    // The final disjunct resolves both operands to the shared comparison
    // spelling: on Windows a verbatim (`\\?\`) or 8.3-aliased descendant of a
    // plain `.beads` still classifies internal instead of being refused as
    // external (#413). Like the lexical widening above, this only routes into
    // the *stricter* internal branch, which re-validates the path itself.
    let is_internal = path.starts_with(beads_dir)
        || path.starts_with(&canonical_beads)
        || resolved_path.starts_with(beads_dir)
        || resolved_path.starts_with(&canonical_beads)
        || normalized_resolved.as_deref().is_some_and(|normalized| {
            normalized.starts_with(beads_dir) || normalized.starts_with(&canonical_beads)
        })
        || authority_path_within(&resolved_path, beads_dir);

    // CRITICAL: Git paths are ALWAYS rejected, even with allow_external. Do
    // not disclose an absolute external path while reporting that rejection.
    let git_check = validate_no_git_path(path);
    if !git_check.is_allowed() {
        let reason = if is_internal {
            git_check
                .rejection_reason()
                .unwrap_or_else(|| "Git path access denied".to_string())
        } else {
            format!(
                "{} targets git internals; sync never accesses .git/",
                external_path_descriptor(path)
            )
        };
        return Err(BeadsError::Config(reason));
    }

    if is_internal {
        return require_valid_sync_path(path, beads_dir);
    }

    // If external paths are allowed, only validate file type (not containment).
    if allow_external {
        let path_sha256 = external_path_sha256(path);
        tracing::info!(
            path = "<external-source>",
            path_sha256,
            "Using external JSONL path (--allow-external-jsonl)"
        );
        return validate_external_jsonl_path(path);
    }

    Err(BeadsError::Config(format!(
        "{} is outside .beads; pass --allow-external-jsonl to authorize it",
        external_path_descriptor(path)
    )))
}

fn validate_external_jsonl_path(path: &Path) -> Result<()> {
    let file_name = path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();

    // Case-sensitive check is intentional: JSONL files should use lowercase .jsonl extension
    #[allow(clippy::case_sensitive_file_extension_comparisons)]
    if !file_name.ends_with(".jsonl") && !is_allowed_jsonl_temp_name(&file_name) {
        return Err(BeadsError::Config(format!(
            "{} must be a .jsonl file",
            external_path_descriptor(path)
        )));
    }

    for component in path.components() {
        if matches!(component, std::path::Component::ParentDir) {
            return Err(BeadsError::Config(format!(
                "{} contains traversal sequences",
                external_path_descriptor(path)
            )));
        }
    }

    if let Ok(metadata) = std::fs::symlink_metadata(path) {
        if metadata.file_type().is_symlink() {
            return Err(BeadsError::Config(format!(
                "{} must not be a symlink",
                external_path_descriptor(path)
            )));
        }
        if !metadata.is_file() {
            return Err(BeadsError::Config(format!(
                "{} must be a regular file",
                external_path_descriptor(path)
            )));
        }
    }

    Ok(())
}

/// Require that a path is safe for destructive sync operations (delete/overwrite).
///
/// This guard enforces the sync allowlist and ensures we never delete or overwrite
/// files outside `.beads/`, except for explicitly allowed external JSONL paths.
///
/// # Errors
///
/// Returns `BeadsError::Config` if the path is unsafe. Rejections are logged with
/// the attempted operation for auditability.
pub fn require_safe_sync_overwrite_path(
    path: &Path,
    beads_dir: &Path,
    allow_external: bool,
    operation: &str,
) -> Result<()> {
    let canonical_beads =
        dunce::canonicalize(beads_dir).unwrap_or_else(|_| beads_dir.to_path_buf());

    // Resolve relative paths against cwd so that `.beads/issues.jsonl.<pid>.tmp`
    // is correctly recognized as internal when beads_dir is absolute (#238).
    let resolved_path = if path.is_relative() {
        std::env::current_dir()
            .map(|cwd| cwd.join(path))
            .unwrap_or_else(|_| path.to_path_buf())
    } else {
        path.to_path_buf()
    };
    // As in `validate_sync_path_with_external`, the shared-spelling disjunct
    // keeps Windows verbatim/8.3 descendants of a plain `.beads` in the
    // stricter internal branch instead of refusing them as external (#413).
    let is_internal = resolved_path.starts_with(beads_dir)
        || resolved_path.starts_with(&canonical_beads)
        || path.starts_with(beads_dir)
        || path.starts_with(&canonical_beads)
        || authority_path_within(&resolved_path, beads_dir);

    if is_internal {
        let validation = validate_sync_path(path, beads_dir);
        if validation.is_allowed() {
            debug!(
                path = %path.display(),
                operation,
                "Sync path approved for destructive operation"
            );
            return Ok(());
        }

        let reason = validation
            .rejection_reason()
            .unwrap_or_else(|| "Path validation failed".to_string());
        warn!(
            path = %path.display(),
            operation,
            reason = %reason,
            "Sync destructive path rejected"
        );
        return Err(BeadsError::Config(reason));
    }

    let path_sha256 = external_path_sha256(path);
    if !allow_external {
        let reason = format!(
            "Refusing to {operation} outside .beads: {}",
            external_path_descriptor(path)
        );
        warn!(
            path = "<external-path>",
            path_sha256,
            operation,
            reason = %reason,
            "Sync destructive path rejected"
        );
        return Err(BeadsError::Config(reason));
    }

    match validate_sync_path_with_external(path, beads_dir, true) {
        Ok(()) => {
            debug!(
                path = "<external-path>",
                path_sha256, operation, "External sync path approved for destructive operation"
            );
            Ok(())
        }
        Err(err) => {
            warn!(
                path = "<external-path>",
                path_sha256,
                operation,
                error = %err,
                "Sync destructive path rejected"
            );
            Err(err)
        }
    }
}

/// Validates a temp file path for atomic write operations.
///
/// Temp files must:
/// 1. Be in the same directory as the target file (for atomic rename)
/// 2. Not target git internals
/// 3. Have the `.tmp` extension
///
/// # Errors
///
/// Returns `BeadsError::Config` if validation fails.
pub fn validate_temp_file_path(
    temp_path: &Path,
    target_path: &Path,
    beads_dir: &Path,
    allow_external: bool,
) -> Result<()> {
    let canonical_beads =
        dunce::canonicalize(beads_dir).unwrap_or_else(|_| beads_dir.to_path_buf());
    let temp_is_external =
        !temp_path.starts_with(beads_dir) && !temp_path.starts_with(&canonical_beads);
    let safe_temp = if temp_is_external {
        external_path_descriptor(temp_path)
    } else {
        temp_path.display().to_string()
    };
    let target_is_external =
        !target_path.starts_with(beads_dir) && !target_path.starts_with(&canonical_beads);
    let safe_target = if target_is_external {
        external_path_descriptor(target_path)
    } else {
        target_path.display().to_string()
    };

    // Git check is always enforced
    let git_check = validate_no_git_path(temp_path);
    if !git_check.is_allowed() {
        let reason = if temp_is_external {
            format!("{safe_temp} targets git internals; sync never accesses .git/")
        } else {
            git_check
                .rejection_reason()
                .unwrap_or_else(|| "Git path access denied".to_string())
        };
        return Err(BeadsError::Config(reason));
    }

    // Verify temp file is in the same directory as target (PC-4)
    let temp_parent = temp_path.parent();
    let target_parent = target_path.parent();

    if temp_parent != target_parent {
        return Err(BeadsError::Config(format!(
            "Temp file '{}' must be in the same directory as target '{}' (safety invariant PC-4)",
            safe_temp, safe_target
        )));
    }

    let has_tmp_extension = temp_path
        .extension()
        .and_then(|ext| ext.to_str())
        .is_some_and(|ext| ext.eq_ignore_ascii_case("tmp"));
    if !has_tmp_extension {
        return Err(BeadsError::Config(format!(
            "Temp file '{}' must use a .tmp extension",
            safe_temp
        )));
    }

    validate_sync_path_with_external(temp_path, beads_dir, allow_external)
}

#[cfg(any(unix, windows))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JsonlFileIdentity {
    device_id: u64,
    inode: u64,
}

#[cfg(any(unix, windows))]
impl JsonlFileIdentity {
    /// Returns the filesystem device containing the opened file.
    #[must_use]
    pub const fn device_id(self) -> u64 {
        self.device_id
    }

    /// Returns the inode number of the opened file.
    #[must_use]
    pub const fn inode(self) -> u64 {
        self.inode
    }

    /// Returns the Windows volume serial number containing the opened file.
    #[cfg(windows)]
    #[must_use]
    pub const fn volume_serial_number(self) -> u64 {
        self.device_id
    }

    /// Returns the stable Windows file index observed from the opened handle.
    #[cfg(windows)]
    #[must_use]
    pub const fn file_index(self) -> u64 {
        self.inode
    }
}

/// A retained capability for one securely traversed JSONL parent directory.
///
/// Publication code can derive sibling names from this handle without
/// re-resolving the parent through the process working directory.
#[cfg(any(unix, windows))]
#[derive(Debug)]
pub(crate) struct PinnedJsonlParent {
    directory: File,
    canonical_path: PathBuf,
    identity: JsonlFileIdentity,
}

/// Non-Unix builds retain the type-level API but fail closed before a pinned
/// filesystem capability can be constructed.
#[cfg(not(any(unix, windows)))]
#[derive(Debug)]
pub(crate) struct PinnedJsonlParent {
    canonical_path: PathBuf,
}

/// One exact, single-component name interpreted relative to a pinned JSONL
/// parent directory.
#[derive(Debug, Clone)]
pub(crate) struct PinnedJsonlName {
    parent: std::sync::Arc<PinnedJsonlParent>,
    leaf: std::ffi::OsString,
    display_path: PathBuf,
}

fn validate_pinned_jsonl_leaf(leaf: &OsStr) -> Result<()> {
    let leaf_digest = raw_os_str_sha256(leaf);
    let mut components = Path::new(leaf).components();
    let is_exact_normal_component = matches!(
        (components.next(), components.next()),
        (Some(std::path::Component::Normal(component)), None) if component == leaf
    );
    if !is_exact_normal_component {
        return Err(BeadsError::Config(format!(
            "JSONL leaf <leaf sha256={leaf_digest}> must be exactly one normal filesystem component"
        )));
    }

    #[cfg(unix)]
    let contains_nul = {
        use std::os::unix::ffi::OsStrExt;
        leaf.as_bytes().contains(&0)
    };
    #[cfg(windows)]
    let contains_nul = {
        use std::os::windows::ffi::OsStrExt;
        leaf.encode_wide().any(|unit| unit == 0)
    };
    #[cfg(not(any(unix, windows)))]
    let contains_nul = leaf.to_string_lossy().contains('\0');
    if contains_nul {
        return Err(BeadsError::Config(format!(
            "JSONL leaf <leaf sha256={leaf_digest}> contains an embedded NUL"
        )));
    }

    #[cfg(windows)]
    {
        use std::os::windows::ffi::OsStrExt;

        if leaf.encode_wide().any(|unit| unit == u16::from(b':')) {
            return Err(BeadsError::Config(format!(
                "JSONL leaf <leaf sha256={leaf_digest}> contains a Windows alternate-data-stream separator"
            )));
        }
    }

    Ok(())
}

impl PinnedJsonlName {
    /// Returns the retained parent-directory capability.
    #[must_use]
    pub(crate) fn parent(&self) -> &PinnedJsonlParent {
        &self.parent
    }

    /// Returns the exact, non-lossy leaf interpreted relative to `parent()`.
    #[must_use]
    pub(crate) fn leaf(&self) -> &OsStr {
        &self.leaf
    }

    /// Returns the diagnostic path captured when this name was constructed.
    ///
    /// Filesystem operations must use `parent()` and `leaf()`, not this path.
    #[must_use]
    pub(crate) fn display_path(&self) -> &Path {
        &self.display_path
    }

    /// Returns a digest of the raw platform representation of the leaf.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn leaf_sha256(&self) -> String {
        raw_os_str_sha256(&self.leaf)
    }

    /// Derives another exact sibling name under the same retained parent.
    pub(crate) fn with_leaf(&self, leaf: &OsStr) -> Result<Self> {
        validate_pinned_jsonl_leaf(leaf)?;
        Ok(Self {
            parent: std::sync::Arc::clone(&self.parent),
            leaf: leaf.to_os_string(),
            display_path: self.parent.canonical_path().join(leaf),
        })
    }

    /// Resolves one sibling path against the retained parent without
    /// re-traversing that parent through the process namespace.
    pub(crate) fn with_sibling_path(&self, path: &Path) -> Result<Self> {
        #[cfg(any(unix, windows))]
        let absolute = absolute_jsonl_source_path(path)?;
        #[cfg(not(any(unix, windows)))]
        let absolute = path.to_path_buf();
        let parent = absolute.parent().ok_or_else(|| {
            BeadsError::Config(format!(
                "JSONL sibling {} has no parent directory",
                external_path_descriptor(path)
            ))
        })?;
        // The retained parent route is a lexical spelling; a sibling may
        // arrive as a canonical (Windows verbatim or 8.3-resolved) spelling of
        // the same directory. Compare through the shared convention so one
        // directory always matches itself, while a genuinely different parent
        // still refuses the capability (#413).
        if !authority_paths_equivalent(parent, self.parent.canonical_path()) {
            return Err(BeadsError::SyncConflict {
                message:
                    "JSONL sibling path does not belong to the retained parent-directory capability"
                        .to_string(),
            });
        }
        let leaf = absolute.file_name().ok_or_else(|| {
            BeadsError::Config(format!(
                "JSONL sibling {} has no leaf name",
                external_path_descriptor(path)
            ))
        })?;
        self.with_leaf(leaf)
    }
}

/// Open flags for the retained directory capability at the end of a stable
/// route: a real read handle, because callers `fstat`, `fsync`, and `openat`
/// through it.
#[cfg(unix)]
const STABLE_ROUTE_DIRECTORY_FLAGS: rustix::fs::OFlags = rustix::fs::OFlags::RDONLY
    .union(rustix::fs::OFlags::DIRECTORY)
    .union(rustix::fs::OFlags::NOFOLLOW)
    .union(rustix::fs::OFlags::CLOEXEC)
    .union(rustix::fs::OFlags::NONBLOCK);

/// Open flags for the intermediate components of a stable route (the
/// filesystem root and every ancestor above the pinned directory).
///
/// These handles exist only to anchor the next `openat` step, so on Linux they
/// are `O_PATH` handles: the kernel resolves them without granting read access
/// and without consulting LSM `file_open` hooks, which keeps the traversal
/// working under Landlock-style sandboxes that deny `READ_DIR` on `/` (#436).
/// `O_PATH | O_DIRECTORY | O_NOFOLLOW` still fails with `ENOTDIR` on a symlink
/// or non-directory component, so the no-symlink traversal guarantee is kept.
/// Other Unix targets have no `O_PATH`, so they keep using read handles.
#[cfg(any(target_os = "linux", target_os = "android"))]
const STABLE_ROUTE_TRAVERSAL_FLAGS: rustix::fs::OFlags = rustix::fs::OFlags::PATH
    .union(rustix::fs::OFlags::DIRECTORY)
    .union(rustix::fs::OFlags::NOFOLLOW)
    .union(rustix::fs::OFlags::CLOEXEC);

#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
const STABLE_ROUTE_TRAVERSAL_FLAGS: rustix::fs::OFlags = STABLE_ROUTE_DIRECTORY_FLAGS;

#[cfg(unix)]
fn open_jsonl_directory_via_stable_route(
    display_path: &Path,
    absolute_directory: &Path,
) -> Result<File> {
    use rustix::fs::{CWD, Mode, openat};
    use rustix::io::Errno;

    let descriptor = external_path_descriptor(display_path);
    let mut components = absolute_directory.components();
    if !matches!(components.next(), Some(std::path::Component::RootDir)) {
        return Err(BeadsError::Config(format!(
            "Could not anchor JSONL parent {descriptor} at the filesystem root"
        )));
    }
    let mut names = Vec::new();
    for component in components {
        let std::path::Component::Normal(name) = component else {
            return Err(BeadsError::Config(format!(
                "JSONL parent {descriptor} contains an unsupported filesystem route component"
            )));
        };
        names.push(name);
    }

    // Only the final component becomes the retained capability; the root and
    // every ancestor are traversal-only anchors.
    let root_flags = if names.is_empty() {
        STABLE_ROUTE_DIRECTORY_FLAGS
    } else {
        STABLE_ROUTE_TRAVERSAL_FLAGS
    };
    let mut route = openat(CWD, "/", root_flags, Mode::empty()).map_err(|error| {
        BeadsError::Config(format!(
            "Could not open the filesystem root while pinning JSONL parent {descriptor}: {error}"
        ))
    })?;
    let last_index = names.len().saturating_sub(1);
    for (index, name) in names.iter().copied().enumerate() {
        let flags = if index == last_index {
            STABLE_ROUTE_DIRECTORY_FLAGS
        } else {
            STABLE_ROUTE_TRAVERSAL_FLAGS
        };
        route = match openat(&route, name, flags, Mode::empty()) {
            Ok(next) => next,
            Err(error) if error == Errno::LOOP || error == Errno::NOTDIR => {
                return Err(BeadsError::Config(format!(
                    "JSONL parent component for {descriptor} must not be a symlink and must be a directory"
                )));
            }
            Err(error) => {
                return Err(BeadsError::Config(format!(
                    "Could not securely traverse JSONL parent {descriptor}: {error}"
                )));
            }
        };
    }

    let directory = File::from(route);
    let metadata = directory.metadata().map_err(|error| {
        BeadsError::Config(format!(
            "Could not inspect pinned JSONL parent {descriptor}: {error}"
        ))
    })?;
    if !metadata.is_dir() {
        return Err(BeadsError::Config(format!(
            "Pinned JSONL parent {descriptor} is not a directory"
        )));
    }
    Ok(directory)
}

#[cfg(windows)]
fn open_jsonl_directory_via_stable_route(
    display_path: &Path,
    absolute_directory: &Path,
) -> Result<File> {
    use cap_primitives::ambient_authority;
    use cap_primitives::fs::{open_ambient_dir, open_dir_nofollow};

    let descriptor = external_path_descriptor(display_path);
    let mut components = absolute_directory.components();
    let Some(std::path::Component::Prefix(prefix)) = components.next() else {
        return Err(BeadsError::Config(format!(
            "Could not anchor JSONL parent {descriptor} at a Windows volume root"
        )));
    };
    let mut volume_root = PathBuf::from(prefix.as_os_str());
    if !matches!(components.next(), Some(std::path::Component::RootDir)) {
        return Err(BeadsError::Config(format!(
            "Could not anchor JSONL parent {descriptor} at a Windows volume root"
        )));
    }
    volume_root.push(std::path::Component::RootDir.as_os_str());

    // cap-primitives opens directory handles without FILE_SHARE_DELETE on
    // Windows. Retaining the final handle therefore prevents its namespace
    // entry from being renamed or deleted underneath capability-relative
    // operations.
    let mut route =
        open_ambient_dir(&volume_root, ambient_authority()).map_err(|error| {
            BeadsError::Config(format!(
                "Could not open the Windows volume root while pinning JSONL parent {descriptor}: {error}"
            ))
        })?;
    for component in components {
        let std::path::Component::Normal(name) = component else {
            return Err(BeadsError::Config(format!(
                "JSONL parent {descriptor} contains an unsupported filesystem route component"
            )));
        };
        route = open_dir_nofollow(&route, Path::new(name)).map_err(|error| {
            BeadsError::Config(format!(
                "JSONL parent component for {descriptor} must be a non-reparse directory: {error}"
            ))
        })?;
    }

    let metadata = route.metadata().map_err(|error| {
        BeadsError::Config(format!(
            "Could not inspect pinned JSONL parent {descriptor}: {error}"
        ))
    })?;
    if !metadata.is_dir() {
        return Err(BeadsError::Config(format!(
            "Pinned JSONL parent {descriptor} is not a directory"
        )));
    }
    Ok(route)
}

#[cfg(unix)]
impl PinnedJsonlParent {
    /// Returns the lexically normalized absolute route used to acquire this fd.
    #[must_use]
    pub(crate) fn canonical_path(&self) -> &Path {
        &self.canonical_path
    }

    /// Returns the device/inode identity of the retained directory fd.
    #[must_use]
    pub(crate) const fn identity(&self) -> JsonlFileIdentity {
        self.identity
    }

    /// Borrows the retained directory fd for handle-relative syscalls.
    #[must_use]
    pub(crate) const fn as_file(&self) -> &File {
        &self.directory
    }

    /// Reopens the original route securely and checks that it still names the
    /// retained directory.
    pub(crate) fn verify_route(&self) -> Result<()> {
        let reopened =
            open_jsonl_directory_via_stable_route(&self.canonical_path, &self.canonical_path)
                .map_err(|error| BeadsError::SyncConflict {
                    message: format!(
                        "JSONL parent route could not be re-witnessed after its directory capability was pinned: {error}"
                    ),
                })?;
        let observed = jsonl_file_identity(&reopened.metadata().map_err(|error| {
            BeadsError::Config(format!(
                "Could not re-witness pinned JSONL parent {}: {error}",
                external_path_descriptor(&self.canonical_path)
            ))
        })?);
        if observed != self.identity {
            return Err(BeadsError::SyncConflict {
                message: "JSONL parent route changed after its directory capability was pinned"
                    .to_string(),
            });
        }
        Ok(())
    }

    /// Makes namespace changes performed through this retained directory fd
    /// durable.
    pub(crate) fn fsync(&self) -> std::io::Result<()> {
        rustix::fs::fsync(&self.directory).map_err(std::io::Error::from)
    }
}

#[cfg(windows)]
impl PinnedJsonlParent {
    /// Returns the lexically normalized absolute route used to acquire this
    /// retained Windows directory handle.
    #[must_use]
    pub(crate) fn canonical_path(&self) -> &Path {
        &self.canonical_path
    }

    /// Returns the volume/file-index identity of the retained directory.
    #[must_use]
    pub(crate) const fn identity(&self) -> JsonlFileIdentity {
        self.identity
    }

    /// Borrows the retained directory handle for capability-relative calls.
    #[must_use]
    pub(crate) const fn as_file(&self) -> &File {
        &self.directory
    }

    /// Reopens the original no-follow route and checks that it still names the
    /// retained directory handle.
    pub(crate) fn verify_route(&self) -> Result<()> {
        let reopened =
            open_jsonl_directory_via_stable_route(&self.canonical_path, &self.canonical_path)
                .map_err(|error| BeadsError::SyncConflict {
                    message: format!(
                        "JSONL parent route could not be re-witnessed after its Windows directory capability was pinned: {error}"
                    ),
                })?;
        let observed =
            windows_jsonl_file_identity(&reopened, &self.canonical_path).map_err(|error| {
                BeadsError::SyncConflict {
                    message: format!(
                        "Could not re-witness pinned Windows JSONL parent identity: {error}"
                    ),
                }
            })?;
        if observed != self.identity {
            return Err(BeadsError::SyncConflict {
                message:
                    "JSONL parent route changed after its Windows directory capability was pinned"
                        .to_string(),
            });
        }
        Ok(())
    }

    /// Windows has no documented unprivileged equivalent of directory fsync.
    ///
    /// Returning success here would falsely certify namespace durability.
    pub(crate) fn fsync(&self) -> std::io::Result<()> {
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "Windows cannot certify directory-entry durability: FlushFileBuffers requires a writable file handle and ReplaceFileW write-through is unsupported",
        ))
    }
}

#[cfg(not(any(unix, windows)))]
impl PinnedJsonlParent {
    #[must_use]
    pub(crate) fn canonical_path(&self) -> &Path {
        &self.canonical_path
    }

    pub(crate) fn verify_route(&self) -> Result<()> {
        Err(BeadsError::Config(
            "Pinned JSONL parent handles are unavailable on this platform".to_string(),
        ))
    }

    pub(crate) fn fsync(&self) -> std::io::Result<()> {
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "pinned JSONL parent handles are unavailable on this platform",
        ))
    }
}

#[cfg(unix)]
impl PinnedJsonlName {
    fn open_relative_regular_once(&self) -> Result<Option<File>> {
        use rustix::fs::{Mode, OFlags, openat};
        use rustix::io::Errno;

        let leaf_flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC | OFlags::NONBLOCK;
        let descriptor = external_path_descriptor(&self.display_path);
        let opened = match openat(self.parent.as_file(), &self.leaf, leaf_flags, Mode::empty()) {
            Ok(opened) => opened,
            Err(Errno::NOENT) => return Ok(None),
            Err(Errno::LOOP) => {
                return Err(BeadsError::Config(format!(
                    "JSONL leaf for {descriptor} must not be a symlink"
                )));
            }
            Err(error) => {
                return Err(BeadsError::Config(format!(
                    "Could not open pinned JSONL leaf {descriptor}: {error}"
                )));
            }
        };
        let file = File::from(opened);
        regular_jsonl_fd_metadata(&file, &self.display_path)?;
        Ok(Some(file))
    }

    fn verify_relative_identity(&self, expected: JsonlFileIdentity) -> Result<()> {
        let Some(observed) = self.open_relative_regular_once()? else {
            return Err(BeadsError::SyncConflict {
                message: "Pinned JSONL leaf disappeared during identity verification".to_string(),
            });
        };
        let observed = jsonl_file_identity(&observed.metadata().map_err(|error| {
            BeadsError::Config(format!(
                "Could not inspect pinned JSONL leaf {}: {error}",
                external_path_descriptor(&self.display_path)
            ))
        })?);
        if observed != expected {
            return Err(BeadsError::SyncConflict {
                message: "Pinned JSONL leaf changed between secure open and identity verification"
                    .to_string(),
            });
        }
        Ok(())
    }

    /// Opens an optional regular leaf relative to the retained parent fd.
    ///
    /// The leaf is reopened after the initial fd validation so a replacement
    /// between `openat` and identity verification is detected.
    pub(crate) fn open_optional_regular(&self) -> Result<Option<OpenedJsonlSource>> {
        let Some(file) = self.open_relative_regular_once()? else {
            return Ok(None);
        };
        let identity = jsonl_file_identity(&file.metadata().map_err(|error| {
            BeadsError::Config(format!(
                "Could not inspect pinned JSONL leaf {}: {error}",
                external_path_descriptor(&self.display_path)
            ))
        })?);
        self.verify_relative_identity(identity)?;
        Ok(Some(OpenedJsonlSource { file, identity }))
    }

    /// Creates a new read/write regular file relative to the retained parent
    /// fd, requesting owner-only `0600` permissions.
    ///
    /// `Ok(None)` means that the exact sibling name already exists. Callers
    /// with a bounded allocator may then try their next prevalidated leaf.
    pub(crate) fn create_new_regular_if_absent(&self) -> Result<Option<File>> {
        use rustix::fs::{Mode, OFlags, openat};
        use rustix::io::Errno;
        use std::os::unix::fs::PermissionsExt;

        let descriptor = external_path_descriptor(&self.display_path);
        let flags = OFlags::RDWR
            | OFlags::CREATE
            | OFlags::EXCL
            | OFlags::NOFOLLOW
            | OFlags::CLOEXEC
            | OFlags::NONBLOCK;
        let opened = openat(
            self.parent.as_file(),
            &self.leaf,
            flags,
            Mode::RUSR | Mode::WUSR,
        )
        .map_err(|error| match error {
            Errno::LOOP => BeadsError::Config(format!(
                "Pinned JSONL leaf for {descriptor} must not be a symlink"
            )),
            other => BeadsError::Io(std::io::Error::from(other)),
        });
        let opened = match opened {
            Ok(opened) => opened,
            Err(BeadsError::Io(error)) if error.kind() == std::io::ErrorKind::AlreadyExists => {
                return Ok(None);
            }
            Err(error) => return Err(error),
        };
        let file = File::from(opened);
        file.set_permissions(std::fs::Permissions::from_mode(0o600))
            .map_err(BeadsError::Io)?;
        let identity = jsonl_file_identity(&regular_jsonl_fd_metadata(&file, &self.display_path)?);
        self.verify_relative_identity(identity)?;
        Ok(Some(file))
    }

    /// Creates a new regular sibling and fails if its exact name exists.
    #[cfg(test)]
    pub(crate) fn create_new_regular(&self) -> Result<File> {
        self.create_new_regular_if_absent()?.ok_or_else(|| {
            BeadsError::Config(format!(
                "Pinned JSONL leaf already exists: {}",
                external_path_descriptor(&self.display_path)
            ))
        })
    }

    /// Removes only the exact regular-file generation identified by
    /// `expected`.
    ///
    /// This is deliberately narrower than a general cleanup primitive. It is
    /// used only after a successful atomic exchange has moved a verified
    /// displaced JSONL generation to an allocator-owned staging leaf.
    pub(crate) fn remove_regular_if_identity(&self, expected: JsonlFileIdentity) -> Result<()> {
        use rustix::fs::{AtFlags, unlinkat};

        self.parent.verify_route()?;
        let opened = self
            .open_optional_regular()?
            .ok_or_else(|| BeadsError::SyncConflict {
                message: "Verified displaced JSONL recovery leaf disappeared before exact cleanup"
                    .to_string(),
            })?;
        if opened.identity() != expected {
            return Err(BeadsError::SyncConflict {
                message:
                    "Displaced JSONL recovery leaf changed before exact handle-relative cleanup"
                        .to_string(),
            });
        }
        self.verify_relative_identity(expected)?;
        unlinkat(self.parent.as_file(), &self.leaf, AtFlags::empty())
            .map_err(|error| BeadsError::Io(std::io::Error::from(error)))?;
        if self.open_optional_regular()?.is_some() {
            return Err(BeadsError::SyncConflict {
                message:
                    "Displaced JSONL recovery leaf reappeared after exact handle-relative cleanup"
                        .to_string(),
            });
        }
        self.parent.verify_route()?;
        Ok(())
    }

    /// Captures the exact current generation of this pinned leaf, if present.
    pub(crate) fn capture_optional(&self) -> Result<Option<JsonlSourceSnapshot>> {
        self.open_optional_regular()?
            .map(|opened| {
                capture_opened_jsonl_source_snapshot_with_verifier(
                    &self.display_path,
                    opened,
                    None,
                    |identity| self.verify_relative_identity(identity),
                )
            })
            .transpose()
    }

    /// Captures the exact current generation of this pinned leaf.
    pub(crate) fn capture(&self) -> Result<JsonlSourceSnapshot> {
        self.capture_optional()?.ok_or_else(|| {
            BeadsError::Config(format!(
                "Pinned JSONL leaf {} does not exist",
                external_path_descriptor(&self.display_path)
            ))
        })
    }
}

#[cfg(windows)]
impl PinnedJsonlName {
    const FILE_SHARE_READ: u32 = 0x0000_0001;
    const FILE_SHARE_WRITE: u32 = 0x0000_0002;

    fn open_relative_regular_once_with_share_mode(&self, share_mode: u32) -> Result<Option<File>> {
        use cap_primitives::fs::{FollowSymlinks, OpenOptions, OpenOptionsExt, open};

        let descriptor = external_path_descriptor(&self.display_path);
        let mut options = OpenOptions::new();
        options.read(true);
        options._cap_fs_ext_follow(FollowSymlinks::No);
        options.share_mode(share_mode);
        let file = match open(self.parent.as_file(), Path::new(&self.leaf), &options) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => {
                return Err(BeadsError::Config(format!(
                    "Could not open pinned Windows JSONL leaf {descriptor} without following reparse points: {error}"
                )));
            }
        };
        regular_jsonl_fd_metadata(&file, &self.display_path)?;
        Ok(Some(file))
    }

    fn verify_relative_identity_with_share_mode(
        &self,
        expected: JsonlFileIdentity,
        share_mode: u32,
    ) -> Result<()> {
        let Some(observed) = self.open_relative_regular_once_with_share_mode(share_mode)? else {
            return Err(BeadsError::SyncConflict {
                message: "Pinned Windows JSONL leaf disappeared during identity verification"
                    .to_string(),
            });
        };
        let observed = windows_jsonl_file_identity(&observed, &self.display_path)?;
        if observed != expected {
            return Err(BeadsError::SyncConflict {
                message:
                    "Pinned Windows JSONL leaf changed between capability-relative open and identity verification"
                        .to_string(),
            });
        }
        Ok(())
    }

    fn verify_relative_identity(&self, expected: JsonlFileIdentity) -> Result<()> {
        self.verify_relative_identity_with_share_mode(expected, Self::FILE_SHARE_READ)
    }

    /// Opens an optional regular Windows leaf relative to the retained parent.
    ///
    /// The handle shares reads only. Existing writers prevent the open, and
    /// after it succeeds new writers, renames, and deletions remain blocked
    /// until the returned handle is closed.
    pub(crate) fn open_optional_regular(&self) -> Result<Option<OpenedJsonlSource>> {
        let Some(file) = self.open_relative_regular_once_with_share_mode(Self::FILE_SHARE_READ)?
        else {
            return Ok(None);
        };
        let identity = windows_jsonl_file_identity(&file, &self.display_path)?;
        self.verify_relative_identity(identity)?;
        Ok(Some(OpenedJsonlSource { file, identity }))
    }

    /// Opens a regular Windows leaf for an exact authority identity check.
    ///
    /// Database and lock-sidecar handles legitimately remain open for writing
    /// while their authority is re-witnessed. Share reads and writes so this
    /// probe composes with those handles, but deliberately omit delete sharing:
    /// the opened leaf cannot be renamed or replaced until its stable file ID
    /// has been compared with the retained authority handle.
    fn open_optional_regular_for_authority_identity(&self) -> Result<Option<OpenedJsonlSource>> {
        let share_mode = Self::FILE_SHARE_READ | Self::FILE_SHARE_WRITE;
        let Some(file) = self.open_relative_regular_once_with_share_mode(share_mode)? else {
            return Ok(None);
        };
        let identity = windows_jsonl_file_identity(&file, &self.display_path)?;
        self.verify_relative_identity_with_share_mode(identity, share_mode)?;
        Ok(Some(OpenedJsonlSource { file, identity }))
    }

    /// Creates a new regular Windows sibling relative to the retained parent.
    ///
    /// `CREATE_NEW` provides the exact no-clobber allocation guarantee. The
    /// returned writable handle denies delete sharing, so the allocated name
    /// cannot be replaced while the caller stages and syncs its content.
    pub(crate) fn create_new_regular_if_absent(&self) -> Result<Option<File>> {
        use cap_primitives::fs::{FollowSymlinks, OpenOptions, OpenOptionsExt, open};

        let descriptor = external_path_descriptor(&self.display_path);
        let mut options = OpenOptions::new();
        options.read(true).write(true).create_new(true);
        options._cap_fs_ext_follow(FollowSymlinks::No);
        options.share_mode(Self::FILE_SHARE_READ | Self::FILE_SHARE_WRITE);
        let file = match open(self.parent.as_file(), Path::new(&self.leaf), &options) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => return Ok(None),
            Err(error) => {
                return Err(BeadsError::Config(format!(
                    "Could not create pinned Windows JSONL leaf {descriptor}: {error}"
                )));
            }
        };
        regular_jsonl_fd_metadata(&file, &self.display_path)?;
        let identity = windows_jsonl_file_identity(&file, &self.display_path)?;
        self.verify_relative_identity_with_share_mode(
            identity,
            Self::FILE_SHARE_READ | Self::FILE_SHARE_WRITE,
        )?;
        Ok(Some(file))
    }

    /// Creates a new regular sibling and fails if its exact name exists.
    #[cfg(test)]
    pub(crate) fn create_new_regular(&self) -> Result<File> {
        self.create_new_regular_if_absent()?.ok_or_else(|| {
            BeadsError::Config(format!(
                "Pinned Windows JSONL leaf already exists: {}",
                external_path_descriptor(&self.display_path)
            ))
        })
    }

    /// Atomically publishes this exact regular generation at a missing sibling.
    ///
    /// Windows hard-link creation is an atomic no-replace namespace operation.
    /// A read-only, no-write/no-delete-share handle pins the source generation
    /// across the link and both names are identity-checked afterward. The
    /// source name is intentionally retained: current safe dependencies do not
    /// expose by-handle disposition, so deleting it after closing the pinned
    /// handle would reintroduce a hostile-swap race.
    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) fn link_regular_no_replace_to(
        &self,
        destination: &Self,
    ) -> Result<JsonlFileIdentity> {
        use cap_primitives::fs::hard_link;

        if self.parent.identity() != destination.parent.identity() {
            return Err(BeadsError::SyncConflict {
                message:
                    "Windows no-replace JSONL publication names do not share one retained parent capability"
                        .to_string(),
            });
        }

        self.parent.verify_route()?;
        let source = self
            .open_optional_regular()?
            .ok_or_else(|| BeadsError::SyncConflict {
                message:
                    "Pinned Windows staged JSONL generation disappeared before no-replace publication"
                        .to_string(),
            })?;
        let source_identity = source.identity();

        hard_link(
            self.parent.as_file(),
            Path::new(&self.leaf),
            destination.parent.as_file(),
            Path::new(&destination.leaf),
        )
        .map_err(|error| {
            if error.kind() == std::io::ErrorKind::AlreadyExists {
                BeadsError::SyncConflict {
                    message:
                        "JSONL appeared before atomic Windows no-replace publication; refusing to overwrite it"
                            .to_string(),
                }
            } else {
                BeadsError::Io(error)
            }
        })?;

        let published =
            destination
                .open_optional_regular()?
                .ok_or_else(|| BeadsError::SyncConflict {
                    message:
                        "Atomically linked Windows JSONL generation disappeared before verification"
                            .to_string(),
                })?;
        if published.identity() != source_identity {
            return Err(BeadsError::SyncConflict {
                message:
                    "Windows no-replace JSONL publication did not preserve the staged file identity"
                        .to_string(),
            });
        }
        self.verify_relative_identity(source_identity)?;
        destination.verify_relative_identity(source_identity)?;
        self.parent.verify_route()?;
        Ok(source_identity)
    }

    /// Captures the exact current generation of this pinned leaf, if present.
    pub(crate) fn capture_optional(&self) -> Result<Option<JsonlSourceSnapshot>> {
        self.open_optional_regular()?
            .map(|opened| {
                capture_opened_jsonl_source_snapshot_with_verifier(
                    &self.display_path,
                    opened,
                    None,
                    |identity| self.verify_relative_identity(identity),
                )
            })
            .transpose()
    }

    /// Captures the exact current generation of this pinned leaf.
    pub(crate) fn capture(&self) -> Result<JsonlSourceSnapshot> {
        self.capture_optional()?.ok_or_else(|| {
            BeadsError::Config(format!(
                "Pinned Windows JSONL leaf {} does not exist",
                external_path_descriptor(&self.display_path)
            ))
        })
    }
}

#[cfg(not(any(unix, windows)))]
impl PinnedJsonlName {
    pub(crate) fn create_new_regular_if_absent(&self) -> Result<Option<File>> {
        Err(BeadsError::Config(
            "Pinned JSONL file creation is unavailable on this platform".to_string(),
        ))
    }

    #[cfg(test)]
    pub(crate) fn create_new_regular(&self) -> Result<File> {
        Err(BeadsError::Config(
            "Pinned JSONL file creation is unavailable on this platform".to_string(),
        ))
    }

    pub(crate) fn capture_optional(&self) -> Result<Option<JsonlSourceSnapshot>> {
        Err(BeadsError::Config(
            "Pinned JSONL source capture is unavailable on this platform".to_string(),
        ))
    }

    pub(crate) fn capture(&self) -> Result<JsonlSourceSnapshot> {
        Err(BeadsError::Config(
            "Pinned JSONL source capture is unavailable on this platform".to_string(),
        ))
    }
}

/// Pins the parent directory and exact leaf for a JSONL target.
///
/// Existing leaves must be regular files. Missing leaves are accepted so the
/// returned capability can be used for atomic creation.
#[cfg(unix)]
pub(crate) fn pin_jsonl_target(path: &Path) -> Result<PinnedJsonlName> {
    let absolute_target = absolute_jsonl_source_path(path)?;
    let leaf = absolute_target.file_name().ok_or_else(|| {
        BeadsError::Config(format!(
            "JSONL target {} has no leaf name",
            external_path_descriptor(path)
        ))
    })?;
    validate_pinned_jsonl_leaf(leaf)?;
    let parent_path = absolute_target.parent().ok_or_else(|| {
        BeadsError::Config(format!(
            "JSONL target {} has no parent directory",
            external_path_descriptor(path)
        ))
    })?;
    let directory = open_jsonl_directory_via_stable_route(path, parent_path)?;
    let identity = jsonl_file_identity(&directory.metadata().map_err(|error| {
        BeadsError::Config(format!(
            "Could not inspect pinned JSONL parent {}: {error}",
            external_path_descriptor(path)
        ))
    })?);
    let parent = std::sync::Arc::new(PinnedJsonlParent {
        directory,
        canonical_path: parent_path.to_path_buf(),
        identity,
    });
    let pinned = PinnedJsonlName {
        parent,
        leaf: leaf.to_os_string(),
        display_path: absolute_target,
    };
    pinned.parent.verify_route()?;
    let _ = pinned.open_optional_regular()?;
    pinned.parent.verify_route()?;
    Ok(pinned)
}

#[cfg(windows)]
fn pin_windows_name_without_leaf_open(path: &Path) -> Result<PinnedJsonlName> {
    let absolute_target = absolute_jsonl_source_path(path)?;
    let leaf = absolute_target.file_name().ok_or_else(|| {
        BeadsError::Config(format!(
            "JSONL target {} has no leaf name",
            external_path_descriptor(path)
        ))
    })?;
    validate_pinned_jsonl_leaf(leaf)?;
    let parent_path = absolute_target.parent().ok_or_else(|| {
        BeadsError::Config(format!(
            "JSONL target {} has no parent directory",
            external_path_descriptor(path)
        ))
    })?;
    let directory = open_jsonl_directory_via_stable_route(path, parent_path)?;
    let identity = windows_jsonl_file_identity(&directory, parent_path)?;
    let parent = std::sync::Arc::new(PinnedJsonlParent {
        directory,
        canonical_path: parent_path.to_path_buf(),
        identity,
    });
    let pinned = PinnedJsonlName {
        parent,
        leaf: leaf.to_os_string(),
        display_path: absolute_target,
    };
    pinned.parent.verify_route()?;
    Ok(pinned)
}

#[cfg(windows)]
pub(crate) fn pin_jsonl_target(path: &Path) -> Result<PinnedJsonlName> {
    let pinned = pin_windows_name_without_leaf_open(path)?;
    let _ = pinned.open_optional_regular()?;
    pinned.parent.verify_route()?;
    Ok(pinned)
}

/// Opens one Windows authority path through a retained no-follow parent
/// capability and retains the delete-denying leaf handle.
///
/// Unlike [`pin_jsonl_target`], this probe shares writes because database and
/// lock-sidecar handles remain writable while their authority is verified. It
/// still denies delete sharing, so the named leaf cannot be replaced until the
/// caller has compared its identity and drops the returned guard.
#[cfg(windows)]
pub(crate) fn open_regular_authority_source(path: &Path) -> Result<Option<OpenedJsonlSource>> {
    let pinned = pin_windows_name_without_leaf_open(path)?;
    let opened = pinned.open_optional_regular_for_authority_identity()?;
    pinned.parent.verify_route()?;
    Ok(opened)
}

/// Convenience identity-only probe for callers that do not compare against a
/// second retained handle. Exact authority comparisons must keep the source
/// returned by [`open_regular_authority_source`] alive through the comparison.
#[cfg(windows)]
pub(super) fn open_regular_authority_identity(path: &Path) -> Result<Option<JsonlFileIdentity>> {
    Ok(open_regular_authority_source(path)?.map(|source| source.identity()))
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn pin_jsonl_target(_path: &Path) -> Result<PinnedJsonlName> {
    Err(BeadsError::Config(
        "Pinned JSONL parent handles are unavailable on this platform".to_string(),
    ))
}

/// A securely opened JSONL source and the stable identity observed on its fd.
///
/// Keeping the identity beside the `File` makes it possible for callers to
/// retain an auditable witness for the exact filesystem object they read.
#[cfg(any(unix, windows))]
#[derive(Debug)]
pub struct OpenedJsonlSource {
    file: File,
    identity: JsonlFileIdentity,
}

#[cfg(any(unix, windows))]
impl OpenedJsonlSource {
    /// Borrows the securely opened file.
    #[must_use]
    pub const fn as_file(&self) -> &File {
        &self.file
    }

    /// Returns the stable identity captured from the opened fd.
    #[must_use]
    pub const fn identity(&self) -> JsonlFileIdentity {
        self.identity
    }

    /// Consumes the wrapper and returns the securely opened file.
    #[must_use]
    pub fn into_file(self) -> File {
        self.file
    }
}

fn regular_jsonl_fd_metadata(file: &File, path: &Path) -> Result<std::fs::Metadata> {
    let descriptor = external_path_descriptor(path);
    let metadata = file.metadata().map_err(|err| {
        BeadsError::Config(format!(
            "Failed to read metadata on opened JSONL fd for {descriptor}: {err}"
        ))
    })?;

    if !metadata.is_file() {
        return Err(BeadsError::Config(format!(
            "Opened fd for {descriptor} is not a regular file (possible TOCTOU swap after path validation)"
        )));
    }

    Ok(metadata)
}

#[cfg(unix)]
fn jsonl_file_identity(metadata: &std::fs::Metadata) -> JsonlFileIdentity {
    use std::os::unix::fs::MetadataExt;

    JsonlFileIdentity {
        device_id: metadata.dev(),
        inode: metadata.ino(),
    }
}

#[cfg(windows)]
pub(super) fn windows_jsonl_file_identity(file: &File, path: &Path) -> Result<JsonlFileIdentity> {
    use cap_primitives::fs::{_WindowsByHandle, Metadata};

    let descriptor = external_path_descriptor(path);
    let metadata = Metadata::from_file(file).map_err(|error| {
        BeadsError::Config(format!(
            "Could not inspect the stable Windows file identity for {descriptor}: {error}"
        ))
    })?;
    let volume_serial_number =
        _WindowsByHandle::volume_serial_number(&metadata).ok_or_else(|| {
            BeadsError::Config(format!(
                "Windows volume serial number is unavailable for {descriptor}"
            ))
        })?;
    let file_index = _WindowsByHandle::file_index(&metadata).ok_or_else(|| {
        BeadsError::Config(format!(
            "Windows file index is unavailable for {descriptor}"
        ))
    })?;
    Ok(JsonlFileIdentity {
        device_id: u64::from(volume_serial_number),
        inode: file_index,
    })
}

#[cfg(any(unix, windows))]
fn absolute_jsonl_source_path(path: &Path) -> Result<PathBuf> {
    let descriptor = external_path_descriptor(path);
    if path
        .components()
        .any(|component| matches!(component, std::path::Component::ParentDir))
    {
        return Err(BeadsError::Config(format!(
            "{descriptor} contains traversal sequences"
        )));
    }

    let anchored = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|error| {
                BeadsError::Config(format!(
                    "Could not resolve JSONL source {descriptor} against the current directory: {error}"
                ))
            })?
            .join(path)
    };

    normalize_path_lexically(&anchored).ok_or_else(|| {
        BeadsError::Config(format!(
            "Could not normalize JSONL source {descriptor} without escaping its filesystem root"
        ))
    })
}

#[cfg(unix)]
fn reject_symlinked_jsonl_source_route(absolute_path: &Path, display_path: &Path) -> Result<()> {
    let descriptor = external_path_descriptor(display_path);

    for (depth, component_path) in absolute_path.ancestors().enumerate() {
        let metadata = std::fs::symlink_metadata(component_path).map_err(|error| {
            BeadsError::Config(format!(
                "Could not inspect the filesystem route for JSONL source {descriptor}: {error}"
            ))
        })?;

        if metadata.file_type().is_symlink() {
            let route_part = if depth == 0 {
                "source leaf"
            } else {
                "parent component"
            };
            return Err(BeadsError::Config(format!(
                "JSONL {route_part} for {descriptor} must not be a symlink"
            )));
        }
    }

    Ok(())
}

#[cfg(unix)]
fn verify_jsonl_source_path_identity(
    absolute_path: &Path,
    display_path: &Path,
    fd_identity: JsonlFileIdentity,
) -> Result<()> {
    let descriptor = external_path_descriptor(display_path);
    reject_symlinked_jsonl_source_route(absolute_path, display_path)?;

    let path_metadata = std::fs::symlink_metadata(absolute_path).map_err(|error| {
        BeadsError::Config(format!(
            "Could not re-read filesystem identity for JSONL source {descriptor}: {error}"
        ))
    })?;
    if !path_metadata.is_file() {
        return Err(BeadsError::Config(format!(
            "Filesystem path for JSONL source {descriptor} is not a regular file"
        )));
    }

    let path_identity = jsonl_file_identity(&path_metadata);
    if path_identity != fd_identity {
        return Err(BeadsError::Config(format!(
            "JSONL source {descriptor} changed between secure open and identity verification"
        )));
    }

    Ok(())
}

#[cfg(unix)]
fn open_jsonl_source_via_stable_route(path: &Path, absolute_path: &Path) -> Result<Option<File>> {
    use rustix::fs::{CWD, Mode, OFlags, openat};
    use rustix::io::Errno;

    let descriptor = external_path_descriptor(path);
    let leaf_flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC | OFlags::NONBLOCK;
    // Every directory on the way to the leaf is a traversal-only anchor (see
    // `STABLE_ROUTE_TRAVERSAL_FLAGS`); only the regular-file leaf is opened
    // for reading.
    let mut route = openat(CWD, "/", STABLE_ROUTE_TRAVERSAL_FLAGS, Mode::empty()).map_err(
        |error| {
            BeadsError::Config(format!(
                "Could not open the filesystem root while securing JSONL source {descriptor}: {error}"
            ))
        },
    )?;
    let mut components = absolute_path.components().peekable();
    if !matches!(components.next(), Some(std::path::Component::RootDir)) {
        return Err(BeadsError::Config(format!(
            "Could not anchor JSONL source {descriptor} at the filesystem root"
        )));
    }
    while let Some(component) = components.next() {
        let std::path::Component::Normal(name) = component else {
            return Err(BeadsError::Config(format!(
                "JSONL source {descriptor} contains an unsupported filesystem route component"
            )));
        };
        let is_leaf = components.peek().is_none();
        let flags = if is_leaf {
            leaf_flags
        } else {
            STABLE_ROUTE_TRAVERSAL_FLAGS
        };
        route = match openat(&route, name, flags, Mode::empty()) {
            Ok(next) => next,
            Err(Errno::NOENT) if is_leaf => return Ok(None),
            Err(error) if is_leaf && error == Errno::LOOP => {
                return Err(BeadsError::Config(format!(
                    "JSONL source leaf for {descriptor} must not be a symlink"
                )));
            }
            Err(error) if !is_leaf && (error == Errno::LOOP || error == Errno::NOTDIR) => {
                return Err(BeadsError::Config(format!(
                    "JSONL parent component for {descriptor} must not be a symlink and must be a directory"
                )));
            }
            Err(error) => {
                return Err(BeadsError::Config(format!(
                    "Could not securely traverse JSONL source {descriptor}: {error}"
                )));
            }
        };
    }
    Ok(Some(File::from(route)))
}

#[cfg(unix)]
fn finish_opened_jsonl_source(
    path: &Path,
    absolute_path: &Path,
    file: File,
) -> Result<OpenedJsonlSource> {
    let identity = jsonl_file_identity(&regular_jsonl_fd_metadata(&file, path)?);
    verify_jsonl_source_path_identity(absolute_path, path, identity)?;
    Ok(OpenedJsonlSource { file, identity })
}

#[cfg(unix)]
fn open_jsonl_source_nofollow_impl<F>(path: &Path, after_open: F) -> Result<OpenedJsonlSource>
where
    F: FnOnce() -> std::io::Result<()>,
{
    let descriptor = external_path_descriptor(path);
    let absolute_path = absolute_jsonl_source_path(path)?;
    let file = open_jsonl_source_via_stable_route(path, &absolute_path)?
        .ok_or_else(|| BeadsError::Config(format!("JSONL source {descriptor} does not exist")))?;

    after_open().map_err(|error| {
        BeadsError::Config(format!(
            "Post-open JSONL source verification hook failed for {descriptor}: {error}"
        ))
    })?;
    finish_opened_jsonl_source(path, &absolute_path, file)
}

#[cfg(windows)]
fn open_jsonl_source_nofollow_impl<F>(path: &Path, after_open: F) -> Result<OpenedJsonlSource>
where
    F: FnOnce() -> std::io::Result<()>,
{
    let descriptor = external_path_descriptor(path);
    let pinned = pin_jsonl_target(path)?;
    let opened = pinned
        .open_optional_regular()?
        .ok_or_else(|| BeadsError::Config(format!("JSONL source {descriptor} does not exist")))?;

    after_open().map_err(|error| {
        BeadsError::Config(format!(
            "Post-open Windows JSONL source verification hook failed for {descriptor}: {error}"
        ))
    })?;
    pinned.verify_relative_identity(opened.identity())?;
    pinned.parent.verify_route()?;
    Ok(opened)
}

/// Opens an existing JSONL source without following symlinks.
///
/// This platform capability primitive:
///
/// 1. rejects traversal and opens every route component relative to a retained
///    parent handle without following symlinks or Windows reparse points;
/// 2. opens read-only and retains the exact opened generation;
/// 3. requires the opened fd to identify a regular file; and
/// 4. compares the handle's stable filesystem identity with a fresh
///    capability-relative lookup.
///
/// The returned `File` remains authoritative even if the path is replaced
/// after this function returns.
///
/// # Errors
///
/// Returns `BeadsError::Config` if the path cannot be inspected or securely
/// opened, names a symlink or non-regular file, or changes during the
/// open-and-verify sequence.
#[cfg(any(unix, windows))]
pub fn open_jsonl_source_nofollow(path: &Path) -> Result<OpenedJsonlSource> {
    open_jsonl_source_nofollow_impl(path, || Ok(()))
}

#[cfg(unix)]
fn open_optional_jsonl_source_nofollow(path: &Path) -> Result<Option<OpenedJsonlSource>> {
    let absolute_path = absolute_jsonl_source_path(path)?;
    open_jsonl_source_via_stable_route(path, &absolute_path)?
        .map(|file| finish_opened_jsonl_source(path, &absolute_path, file))
        .transpose()
}

#[cfg(windows)]
fn open_optional_jsonl_source_nofollow(path: &Path) -> Result<Option<OpenedJsonlSource>> {
    pin_jsonl_target(path)?.open_optional_regular()
}

/// Exact immutable content captured from one securely opened JSONL file.
///
/// Every parser, hash, prefix probe, and import phase for a logical operation
/// can open an independent reader on this value instead of reopening a mutable
/// path. Unix and Windows snapshots use a private temporary spool so
/// arbitrarily large or sparse sources do not require a whole-file heap
/// allocation. The snapshot deliberately keeps the exact raw digest separate
/// from higher-level canonical content hashes: whitespace-only changes still
/// matter to overwrite guards.
#[derive(Debug)]
pub(crate) struct JsonlSourceSnapshot {
    display_path: PathBuf,
    #[cfg(any(unix, windows))]
    backing: File,
    #[cfg(not(any(unix, windows)))]
    bytes: Arc<[u8]>,
    raw_sha256: String,
    content_sha256: String,
    modified: SystemTime,
    size: u64,
    #[cfg(any(unix, windows))]
    // The Windows receipt integration consumes this once sync/mod.rs enables
    // native publication; keep the capability witness without a broad allow.
    #[cfg_attr(windows, allow(dead_code))]
    identity: JsonlFileIdentity,
}

impl JsonlSourceSnapshot {
    #[must_use]
    pub(crate) fn display_path(&self) -> &Path {
        &self.display_path
    }

    #[cfg(any(unix, windows))]
    pub(crate) fn reader(&self) -> std::io::BufReader<JsonlSnapshotReader<'_>> {
        std::io::BufReader::new(JsonlSnapshotReader {
            file: &self.backing,
            offset: 0,
        })
    }

    #[cfg(not(any(unix, windows)))]
    pub(crate) fn reader(&self) -> std::io::BufReader<std::io::Cursor<&[u8]>> {
        std::io::BufReader::new(std::io::Cursor::new(self.bytes.as_ref()))
    }

    #[must_use]
    pub(crate) fn raw_sha256(&self) -> &str {
        &self.raw_sha256
    }

    #[must_use]
    pub(crate) fn content_sha256(&self) -> &str {
        &self.content_sha256
    }

    #[must_use]
    pub(crate) const fn modified(&self) -> SystemTime {
        self.modified
    }

    #[must_use]
    pub(crate) const fn size(&self) -> u64 {
        self.size
    }

    #[cfg(any(unix, windows))]
    // See the field-level note: Windows path capture is implemented before
    // the higher-level publication receipt is wired into sync/mod.rs.
    #[cfg_attr(windows, allow(dead_code))]
    #[must_use]
    pub(crate) const fn identity(&self) -> JsonlFileIdentity {
        self.identity
    }
}

#[cfg(any(unix, windows))]
pub(crate) struct JsonlSnapshotReader<'a> {
    file: &'a File,
    offset: u64,
}

#[cfg(any(unix, windows))]
impl std::io::Read for JsonlSnapshotReader<'_> {
    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
        #[cfg(unix)]
        use std::os::unix::fs::FileExt;
        #[cfg(windows)]
        use std::os::windows::fs::FileExt;

        #[cfg(unix)]
        let read = self.file.read_at(buffer, self.offset)?;
        #[cfg(windows)]
        let read = self.file.seek_read(buffer, self.offset)?;
        self.offset = self
            .offset
            .checked_add(read as u64)
            .ok_or_else(|| std::io::Error::other("JSONL snapshot reader offset overflow"))?;
        Ok(read)
    }
}

#[cfg(any(unix, windows))]
fn jsonl_capture_timeout() -> BeadsError {
    BeadsError::Io(std::io::Error::new(
        std::io::ErrorKind::TimedOut,
        "immutable JSONL source capture exceeded its observation deadline",
    ))
}

#[cfg(any(unix, windows))]
fn ensure_jsonl_capture_deadline(deadline: Option<Instant>) -> Result<()> {
    if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
        return Err(jsonl_capture_timeout());
    }
    Ok(())
}

#[cfg(any(unix, windows))]
struct DeadlineReader<R> {
    inner: R,
    deadline: Option<Instant>,
}

#[cfg(any(unix, windows))]
impl<R: std::io::Read> std::io::Read for DeadlineReader<R> {
    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
        if self
            .deadline
            .is_some_and(|deadline| Instant::now() >= deadline)
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "immutable JSONL source capture exceeded its observation deadline",
            ));
        }
        let read = self.inner.read(buffer)?;
        if self
            .deadline
            .is_some_and(|deadline| Instant::now() >= deadline)
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "immutable JSONL source capture exceeded its observation deadline",
            ));
        }
        Ok(read)
    }
}

#[cfg(any(unix, windows))]
fn compute_snapshot_content_sha256(backing: &File, deadline: Option<Instant>) -> Result<String> {
    use std::io::BufRead;

    ensure_jsonl_capture_deadline(deadline)?;
    let mut reader = std::io::BufReader::new(DeadlineReader {
        inner: JsonlSnapshotReader {
            file: backing,
            offset: 0,
        },
        deadline,
    });
    let mut hasher = Sha256::new();
    let mut line = Vec::with_capacity(4096);
    loop {
        ensure_jsonl_capture_deadline(deadline)?;
        line.clear();
        if reader.read_until(b'\n', &mut line)? == 0 {
            break;
        }
        let trimmed = line.trim_ascii();
        if !trimmed.is_empty() {
            hasher.update(trimmed);
            hasher.update(b"\n");
        }
    }
    ensure_jsonl_capture_deadline(deadline)?;
    Ok(crate::util::hex_encode(&hasher.finalize()))
}

#[cfg(unix)]
fn jsonl_fd_stability_witness(metadata: &std::fs::Metadata) -> Result<(u64, SystemTime, i64, i64)> {
    use std::os::unix::fs::MetadataExt;

    Ok((
        metadata.len(),
        metadata.modified()?,
        metadata.ctime(),
        metadata.ctime_nsec(),
    ))
}

#[cfg(windows)]
fn jsonl_fd_stability_witness(metadata: &std::fs::Metadata) -> Result<(u64, SystemTime, u64, u64)> {
    use std::os::windows::fs::MetadataExt;

    Ok((
        metadata.file_size(),
        metadata.modified()?,
        metadata.last_write_time(),
        metadata.creation_time(),
    ))
}

/// Open the anonymous, never-linked file that backs an immutable JSONL
/// snapshot.
///
/// The backing lives beside the source (its parent directory is exactly where
/// `br` already holds write authority for locks, temp exports, and history),
/// so a sandbox that confines `br` to the workspace — Landlock via `nono`,
/// for one (#436) — never sees a write outside the tree. The process-wide
/// temp directory is only a fallback for read-only checkouts whose `.beads/`
/// cannot host even an unlinked file. `tempfile` uses `O_TMPFILE` where the
/// filesystem supports it and otherwise creates and immediately unlinks a
/// random name, so nothing is left behind on either route.
fn open_private_snapshot_backing(parent: Option<&Path>) -> std::io::Result<File> {
    let beside_source = parent
        .filter(|dir| !dir.as_os_str().is_empty())
        .map(tempfile::tempfile_in);
    match beside_source {
        Some(Ok(file)) => Ok(file),
        Some(Err(beside_error)) => tempfile::tempfile().map_err(|global_error| {
            std::io::Error::new(
                global_error.kind(),
                format!(
                    "neither the source directory ({beside_error}) nor the temp directory \
                     ({global_error}) could host the snapshot"
                ),
            )
        }),
        None => tempfile::tempfile(),
    }
}

/// Captures one exact, stable JSONL source generation without following
/// symlinks.
///
/// The secure fd is opened once, copied through a fixed-size buffer into a
/// private anonymous backing file, and checked for ordinary in-place mutation
/// before the path-to-fd identity is checked again. Callers must perform every
/// semantic pass through `reader()` rather than reopening `display_path()`.
///
/// # Errors
///
/// Returns a deterministic configuration or synchronization error when the
/// source is unsafe, changes during capture, cannot be represented in memory,
/// or cannot be read completely.
#[cfg(any(unix, windows))]
fn capture_opened_jsonl_source_snapshot_with_verifier<VerifyIdentity>(
    path: &Path,
    opened: OpenedJsonlSource,
    deadline: Option<Instant>,
    verify_identity: VerifyIdentity,
) -> Result<JsonlSourceSnapshot>
where
    VerifyIdentity: FnOnce(JsonlFileIdentity) -> Result<()>,
{
    use std::io::{Read, Write};

    ensure_jsonl_capture_deadline(deadline)?;
    let identity = opened.identity();
    let before_metadata = regular_jsonl_fd_metadata(opened.as_file(), path)?;
    let before_witness = jsonl_fd_stability_witness(&before_metadata)?;
    ensure_jsonl_capture_deadline(deadline)?;
    let mut backing = open_private_snapshot_backing(path.parent()).map_err(|error| {
        BeadsError::Config(format!(
            "Could not create private backing for JSONL source {}: {error}",
            external_path_descriptor(path)
        ))
    })?;
    ensure_jsonl_capture_deadline(deadline)?;
    let mut file = opened.into_file();
    let mut hasher = Sha256::new();
    let mut remaining = before_metadata.len();
    let mut buffer = vec![0_u8; 64 * 1024];
    while remaining > 0 {
        ensure_jsonl_capture_deadline(deadline)?;
        let wanted = usize::try_from(remaining.min(buffer.len() as u64))
            .expect("bounded snapshot read size fits usize");
        let read = file.read(&mut buffer[..wanted])?;
        ensure_jsonl_capture_deadline(deadline)?;
        if read == 0 {
            return Err(BeadsError::SyncConflict {
                message:
                    "JSONL source became shorter while its immutable snapshot was being captured"
                        .to_string(),
            });
        }
        backing.write_all(&buffer[..read])?;
        ensure_jsonl_capture_deadline(deadline)?;
        hasher.update(&buffer[..read]);
        remaining -= read as u64;
    }
    ensure_jsonl_capture_deadline(deadline)?;
    let mut eof_probe = [0_u8; 1];
    if file.read(&mut eof_probe)? != 0 {
        return Err(BeadsError::SyncConflict {
            message: "JSONL source grew while its immutable snapshot was being captured"
                .to_string(),
        });
    }
    ensure_jsonl_capture_deadline(deadline)?;
    let after_metadata = regular_jsonl_fd_metadata(&file, path)?;
    let after_witness = jsonl_fd_stability_witness(&after_metadata)?;
    if before_witness != after_witness {
        return Err(BeadsError::SyncConflict {
            message: "JSONL source changed while its immutable snapshot was being captured"
                .to_string(),
        });
    }

    ensure_jsonl_capture_deadline(deadline)?;
    verify_identity(identity)?;
    ensure_jsonl_capture_deadline(deadline)?;
    let content_sha256 = compute_snapshot_content_sha256(&backing, deadline)?;
    ensure_jsonl_capture_deadline(deadline)?;

    Ok(JsonlSourceSnapshot {
        display_path: path.to_path_buf(),
        backing,
        raw_sha256: crate::util::hex_encode(&hasher.finalize()),
        content_sha256,
        modified: before_witness.1,
        size: before_witness.0,
        identity,
    })
}

#[cfg(unix)]
fn capture_opened_jsonl_source_snapshot(
    path: &Path,
    opened: OpenedJsonlSource,
) -> Result<JsonlSourceSnapshot> {
    let absolute_path = absolute_jsonl_source_path(path)?;
    capture_opened_jsonl_source_snapshot_with_verifier(path, opened, None, |identity| {
        verify_jsonl_source_path_identity(&absolute_path, path, identity)
    })
}

#[cfg(windows)]
fn capture_opened_jsonl_source_snapshot(
    path: &Path,
    opened: OpenedJsonlSource,
) -> Result<JsonlSourceSnapshot> {
    let pinned = pin_jsonl_target(path)?;
    capture_opened_jsonl_source_snapshot_with_verifier(path, opened, None, |identity| {
        pinned.verify_relative_identity(identity)
    })
}

#[cfg(unix)]
fn capture_opened_jsonl_source_snapshot_until(
    path: &Path,
    opened: OpenedJsonlSource,
    deadline: Instant,
) -> Result<JsonlSourceSnapshot> {
    ensure_jsonl_capture_deadline(Some(deadline))?;
    let absolute_path = absolute_jsonl_source_path(path)?;
    ensure_jsonl_capture_deadline(Some(deadline))?;
    capture_opened_jsonl_source_snapshot_with_verifier(path, opened, Some(deadline), |identity| {
        verify_jsonl_source_path_identity(&absolute_path, path, identity)
    })
}

#[cfg(windows)]
fn capture_opened_jsonl_source_snapshot_until(
    path: &Path,
    opened: OpenedJsonlSource,
    deadline: Instant,
) -> Result<JsonlSourceSnapshot> {
    ensure_jsonl_capture_deadline(Some(deadline))?;
    let pinned = pin_jsonl_target(path)?;
    ensure_jsonl_capture_deadline(Some(deadline))?;
    capture_opened_jsonl_source_snapshot_with_verifier(path, opened, Some(deadline), |identity| {
        pinned.verify_relative_identity(identity)
    })
}

#[cfg(any(unix, windows))]
pub(crate) fn capture_jsonl_source_snapshot(path: &Path) -> Result<JsonlSourceSnapshot> {
    let opened = open_jsonl_source_nofollow(path)?;
    capture_opened_jsonl_source_snapshot(path, opened)
}

#[cfg(any(unix, windows))]
pub(crate) fn capture_optional_jsonl_source_snapshot(
    path: &Path,
) -> Result<Option<JsonlSourceSnapshot>> {
    open_optional_jsonl_source_nofollow(path)?
        .map(|opened| capture_opened_jsonl_source_snapshot(path, opened))
        .transpose()
}

/// Captures an optional immutable JSONL generation while cooperatively
/// enforcing an absolute observation deadline.
///
/// Regular-file reads and writes cannot be preempted portably once the kernel
/// has accepted them, so one individual filesystem call may finish after the
/// deadline. The capture checks the deadline before and after every bounded
/// chunk, throughout both hashes, and around identity verification; an
/// over-budget result is never returned as a successful snapshot.
#[cfg(any(unix, windows))]
pub(crate) fn capture_optional_jsonl_source_snapshot_until(
    path: &Path,
    deadline: Instant,
) -> Result<Option<JsonlSourceSnapshot>> {
    ensure_jsonl_capture_deadline(Some(deadline))?;
    let opened = open_optional_jsonl_source_nofollow(path)?;
    ensure_jsonl_capture_deadline(Some(deadline))?;
    opened
        .map(|opened| capture_opened_jsonl_source_snapshot_until(path, opened, deadline))
        .transpose()
}

/// Other native builds fail closed until they have an equivalent
/// reparse-point-resistant stable-handle implementation.
#[cfg(not(any(unix, windows)))]
pub(crate) fn capture_jsonl_source_snapshot(_path: &Path) -> Result<JsonlSourceSnapshot> {
    Err(BeadsError::Config(
        "Immutable JSONL source capture is unavailable on this platform; refusing to read or mutate SQLite without stable file identity"
            .to_string(),
    ))
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn capture_optional_jsonl_source_snapshot(
    _path: &Path,
) -> Result<Option<JsonlSourceSnapshot>> {
    Err(BeadsError::Config(
        "Immutable JSONL source capture is unavailable on this platform; refusing to read or mutate SQLite without stable file identity"
            .to_string(),
    ))
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn capture_optional_jsonl_source_snapshot_until(
    _path: &Path,
    _deadline: Instant,
) -> Result<Option<JsonlSourceSnapshot>> {
    Err(BeadsError::Config(
        "Immutable JSONL source capture is unavailable on this platform; refusing to read or mutate SQLite without stable file identity"
            .to_string(),
    ))
}

/// Validate metadata on an already-opened file descriptor.
///
/// Pre-open path checks (`validate_sync_path`) race against the filesystem:
/// between validation and `File::open` a same-user attacker could swap the
/// path to a symlink, device, or FIFO. This function closes that TOCTOU gap
/// by inspecting the fd-level metadata (`fstat`) of the already-opened file.
///
/// # Errors
///
/// Returns `BeadsError::Config` if the opened file is not a regular file.
pub fn validate_jsonl_fd_metadata(file: &File, path: &Path) -> Result<()> {
    regular_jsonl_fd_metadata(file, path).map(|_| ())
}

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

    fn setup_test_beads_dir() -> (TempDir, PathBuf) {
        let temp = TempDir::new().expect("create temp dir");
        let beads_dir = temp.path().join(".beads");
        std::fs::create_dir_all(&beads_dir).expect("create beads dir");
        (temp, beads_dir)
    }

    /// #413: the shared comparison convention must treat one route as equal
    /// to itself (existing or not yet created) and must never merge two
    /// genuinely different routes, on every platform.
    #[test]
    fn authority_path_comparison_contract_holds_for_shared_and_distinct_routes() {
        let (temp, beads_dir) = setup_test_beads_dir();
        let target = beads_dir.join("issues.jsonl");
        std::fs::write(&target, b"{}\n").expect("write JSONL fixture");
        let sibling = beads_dir.join("other.jsonl");
        std::fs::write(&sibling, b"{}\n").expect("write sibling fixture");
        let missing = beads_dir.join("missing.jsonl");

        assert!(authority_paths_equivalent(&target, &target));
        assert!(authority_paths_equivalent(
            &missing,
            &beads_dir.join("missing.jsonl")
        ));
        assert!(
            !authority_paths_equivalent(&target, &sibling),
            "distinct existing routes must never compare equal"
        );
        assert!(
            !authority_paths_equivalent(&missing, &target),
            "a missing route must never match an existing sibling"
        );

        assert!(authority_path_within(&target, &beads_dir));
        assert!(authority_path_within(&missing, &beads_dir));
        let external = temp.path().join("elsewhere").join("issues.jsonl");
        assert!(
            !authority_path_within(&external, &beads_dir),
            "a genuinely external route must stay outside the beads directory"
        );
    }

    /// #413: on non-Windows targets the shared spelling is the identity, so
    /// every pre-existing byte-exact comparison stays byte-identical.
    #[cfg(not(windows))]
    #[test]
    fn comparable_authority_path_is_identity_off_windows() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let target = beads_dir.join("issues.jsonl");
        assert_eq!(comparable_authority_path(&target), target);
        assert_eq!(
            comparable_authority_path(Path::new("relative/route.jsonl")),
            Path::new("relative/route.jsonl")
        );
    }

    /// #413: a `fs::canonicalize` verbatim (`\\?\`) spelling and the plain
    /// pinned spelling of one Windows target must compare equal, for both an
    /// existing leaf and a not-yet-created one, while different targets keep
    /// failing the comparison.
    #[cfg(windows)]
    #[test]
    fn windows_verbatim_and_plain_spellings_of_one_route_are_equivalent() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let target = beads_dir.join("issues.jsonl");
        std::fs::write(&target, b"{}\n").expect("write JSONL fixture");
        let sibling = beads_dir.join("other.jsonl");
        std::fs::write(&sibling, b"{}\n").expect("write sibling fixture");

        let plain = dunce::canonicalize(&target).expect("dunce-canonicalize target");
        let verbatim = std::fs::canonicalize(&target).expect("std-canonicalize target");
        assert!(authority_paths_equivalent(&plain, &verbatim));
        assert!(authority_paths_equivalent(&target, &verbatim));
        assert!(
            !authority_paths_equivalent(&verbatim, &sibling),
            "a verbatim spelling must still refuse a genuinely different leaf"
        );

        let verbatim_parent = std::fs::canonicalize(&beads_dir).expect("std-canonicalize parent");
        let missing_plain = beads_dir.join("missing.jsonl");
        let missing_verbatim = verbatim_parent.join("missing.jsonl");
        assert!(authority_paths_equivalent(
            &missing_plain,
            &missing_verbatim
        ));
        assert!(!authority_paths_equivalent(
            &missing_verbatim,
            &beads_dir.join("different.jsonl")
        ));
    }

    /// #413: a verbatim child of a plain `.beads` directory is contained; a
    /// genuinely external verbatim path stays outside and is still refused by
    /// the sync-path boundary.
    #[cfg(windows)]
    #[test]
    fn windows_verbatim_child_of_plain_beads_dir_classifies_internal() {
        let (temp, beads_dir) = setup_test_beads_dir();
        let target = beads_dir.join("issues.jsonl");
        std::fs::write(&target, b"{}\n").expect("write JSONL fixture");
        let verbatim_child = std::fs::canonicalize(&target).expect("std-canonicalize target");
        assert!(authority_path_within(&verbatim_child, &beads_dir));
        validate_sync_path_with_external(&verbatim_child, &beads_dir, false)
            .expect("verbatim descendant of a plain beads dir must classify internal");

        let external_dir = temp.path().join("external");
        std::fs::create_dir_all(&external_dir).expect("create external dir");
        let external = external_dir.join("escape.jsonl");
        std::fs::write(&external, b"{}\n").expect("write external fixture");
        let verbatim_external = std::fs::canonicalize(&external).expect("canonicalize external");
        assert!(!authority_path_within(&verbatim_external, &beads_dir));
        validate_sync_path_with_external(&verbatim_external, &beads_dir, false)
            .expect_err("a genuinely external verbatim path must still be refused");
    }

    /// #413: the lexical verbatim strip is a pure spelling reduction — it
    /// never touches the filesystem and leaves non-verbatim and device
    /// prefixes alone.
    #[cfg(windows)]
    #[test]
    fn windows_strip_verbatim_prefix_is_lexical_only() {
        assert_eq!(
            strip_verbatim_prefix_lexically(Path::new(r"\\?\C:\does\not\exist.jsonl")),
            Path::new(r"C:\does\not\exist.jsonl")
        );
        assert_eq!(
            strip_verbatim_prefix_lexically(Path::new(r"\\?\UNC\server\share\x.jsonl")),
            Path::new(r"\\server\share\x.jsonl")
        );
        assert_eq!(
            strip_verbatim_prefix_lexically(Path::new(r"C:\plain\route.jsonl")),
            Path::new(r"C:\plain\route.jsonl")
        );
        assert_eq!(
            strip_verbatim_prefix_lexically(Path::new(r"\\.\PIPE\name")),
            Path::new(r"\\.\PIPE\name")
        );
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn deadline_aware_snapshot_matches_the_unbounded_capture() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("issues.jsonl");
        std::fs::write(&path, b"  {\"id\":\"br-a\"}  \n\n{\"id\":\"br-b\"}\n")
            .expect("write JSONL fixture");

        let ordinary = capture_optional_jsonl_source_snapshot(&path)
            .expect("capture ordinary snapshot")
            .expect("ordinary source should be present");
        let bounded = capture_optional_jsonl_source_snapshot_until(
            &path,
            Instant::now() + std::time::Duration::from_secs(5),
        )
        .expect("capture deadline-aware snapshot")
        .expect("deadline-aware source should be present");

        assert_eq!(bounded.size(), ordinary.size());
        assert_eq!(bounded.raw_sha256(), ordinary.raw_sha256());
        assert_eq!(bounded.content_sha256(), ordinary.content_sha256());
        assert_eq!(bounded.identity(), ordinary.identity());
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn deadline_aware_snapshot_refuses_expired_and_overrun_reads() {
        use std::io::Read;

        struct SlowReader;
        impl Read for SlowReader {
            fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
                std::thread::sleep(std::time::Duration::from_millis(5));
                buffer[0] = b'x';
                Ok(1)
            }
        }

        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("issues.jsonl");
        std::fs::write(&path, b"{\"id\":\"br-timeout\"}\n").expect("write JSONL fixture");

        let expired = capture_optional_jsonl_source_snapshot_until(&path, Instant::now())
            .expect_err("an expired observation deadline must fail");
        assert!(
            matches!(
                expired,
                BeadsError::Io(ref error) if error.kind() == std::io::ErrorKind::TimedOut
            ),
            "unexpected expired-deadline error: {expired}"
        );

        let mut reader = DeadlineReader {
            inner: SlowReader,
            deadline: Some(Instant::now() + std::time::Duration::from_millis(1)),
        };
        let error = reader
            .read(&mut [0_u8; 1])
            .expect_err("a read that crosses the deadline must not be accepted");
        assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
    }

    #[test]
    fn test_allowed_jsonl_file() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("issues.jsonl");
        std::fs::write(&path, "{}").expect("write");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(result.is_allowed(), "JSONL files should be allowed");
    }

    #[test]
    fn test_allowed_db_file() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("beads.db");
        std::fs::write(&path, "").expect("write");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(result.is_allowed(), "DB files should be allowed");
    }

    #[test]
    fn test_allowed_db_wal_file() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("beads.db-wal");
        std::fs::write(&path, "").expect("write");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(result.is_allowed(), "DB-WAL files should be allowed");
    }

    #[test]
    fn test_allowed_db_journal_file() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("beads.db-journal");
        std::fs::write(&path, "").expect("write");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(result.is_allowed(), "DB journal files should be allowed");
    }

    #[test]
    fn test_allowed_manifest_file() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join(".manifest.json");
        std::fs::write(&path, "{}").expect("write");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(result.is_allowed(), "Manifest files should be allowed");
    }

    #[test]
    fn test_allowed_normalized_internal_path_with_parent_component() {
        let (temp, beads_dir) = setup_test_beads_dir();
        let subdir = temp.path().join("subdir");
        std::fs::create_dir_all(&subdir).expect("create subdir");
        std::fs::write(beads_dir.join("issues.jsonl"), "{}").expect("write issues.jsonl");

        let path = subdir.join("..").join(".beads").join("issues.jsonl");
        let result = validate_sync_path(&path, &beads_dir);
        assert!(
            result.is_allowed(),
            "Normalized in-tree paths should be allowed"
        );
    }

    #[test]
    fn test_allowed_metadata_file() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("metadata.json");
        std::fs::write(&path, "{}").expect("write");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(result.is_allowed(), "Metadata files should be allowed");
    }

    #[test]
    fn test_allowed_temp_file() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("issues.jsonl.tmp");
        std::fs::write(&path, "").expect("write");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(result.is_allowed(), "Temp JSONL files should be allowed");
    }

    #[test]
    fn test_allowed_pid_scoped_temp_file() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("issues.jsonl.12345.tmp");
        std::fs::write(&path, "").expect("write");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(
            result.is_allowed(),
            "PID-scoped temp JSONL files should be allowed"
        );
    }

    #[test]
    fn test_rejected_outside_beads_dir() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let outside_path = beads_dir.parent().unwrap().join("outside.jsonl");
        std::fs::write(&outside_path, "").expect("write");

        let result = validate_sync_path(&outside_path, &beads_dir);
        assert!(
            matches!(result, PathValidation::OutsideBeadsDir { .. }),
            "Files outside beads dir should be rejected"
        );
    }

    #[test]
    fn test_rejected_traversal() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let traversal_path = beads_dir.join("../../../etc/passwd");

        let result = validate_sync_path(&traversal_path, &beads_dir);
        assert!(
            matches!(result, PathValidation::TraversalAttempt { .. }),
            "Traversal attempts should be rejected"
        );
    }

    #[test]
    fn test_rejected_disallowed_extension() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("config.yaml");
        std::fs::write(&path, "").expect("write");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(
            matches!(result, PathValidation::DisallowedExtension { .. }),
            "Disallowed extensions should be rejected"
        );
    }

    #[test]
    fn test_rejected_source_file() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("main.rs");
        std::fs::write(&path, "").expect("write");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(
            matches!(result, PathValidation::DisallowedExtension { .. }),
            "Source files should be rejected"
        );
    }

    #[test]
    fn test_rejected_directory_named_like_jsonl() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("issues.jsonl");
        std::fs::create_dir_all(&path).expect("create directory");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(
            matches!(result, PathValidation::NonRegularFile { .. }),
            "Directories named like JSONL files should be rejected"
        );
    }

    #[test]
    fn test_rejected_absolute_path_outside() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = PathBuf::from("/etc/passwd");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(
            !result.is_allowed(),
            "Absolute paths outside beads dir should be rejected"
        );
    }

    #[test]
    fn test_rejected_git_path_component() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join(".git").join("config");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(
            matches!(result, PathValidation::GitPathAttempt { .. }),
            ".git paths should be rejected"
        );
    }

    #[test]
    fn test_new_file_in_beads_dir() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        // File doesn't exist yet but is in beads_dir with allowed extension
        let path = beads_dir.join("new.jsonl");

        let result = validate_sync_path(&path, &beads_dir);
        assert!(
            result.is_allowed(),
            "New JSONL files in beads dir should be allowed"
        );
    }

    #[test]
    fn test_require_valid_sync_path_ok() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("issues.jsonl");
        std::fs::write(&path, "").expect("write");

        let result = require_valid_sync_path(&path, &beads_dir);
        assert!(result.is_ok(), "Valid paths should return Ok");
    }

    #[test]
    fn test_require_valid_sync_path_error() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("../../../etc/passwd");

        let result = require_valid_sync_path(&path, &beads_dir);
        assert!(result.is_err(), "Invalid paths should return Err");
        assert!(result.unwrap_err().to_string().contains("traversal"));
    }

    #[test]
    fn test_is_sync_path_allowed_quick_check() {
        let (_temp, beads_dir) = setup_test_beads_dir();

        assert!(is_sync_path_allowed(
            &beads_dir.join("issues.jsonl"),
            &beads_dir
        ));
        assert!(!is_sync_path_allowed(
            &beads_dir.join("../evil.jsonl"),
            &beads_dir
        ));
    }

    #[test]
    fn test_is_sync_path_allowed_accepts_normalized_internal_path() {
        let (temp, beads_dir) = setup_test_beads_dir();
        let subdir = temp.path().join("subdir");
        std::fs::create_dir_all(&subdir).expect("create subdir");

        assert!(is_sync_path_allowed(
            &subdir.join("..").join(".beads").join("issues.jsonl"),
            &beads_dir
        ));
    }

    #[cfg(unix)]
    #[test]
    fn test_symlink_escape_rejected() {
        use std::os::unix::fs::symlink;

        let temp = TempDir::new().expect("create temp dir");
        let beads_dir = temp.path().join(".beads");
        std::fs::create_dir_all(&beads_dir).expect("create beads dir");

        // Create a target outside beads dir
        let outside_target = temp.path().join("secret.txt");
        std::fs::write(&outside_target, "secret data").expect("write");

        // Create symlink inside beads dir pointing outside
        let symlink_path = beads_dir.join("evil.jsonl");
        symlink(&outside_target, &symlink_path).expect("create symlink");

        let result = validate_sync_path(&symlink_path, &beads_dir);
        assert!(
            matches!(result, PathValidation::SymlinkEscape { .. }),
            "Symlinks escaping beads dir should be rejected"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_relative_internal_symlink_is_not_misclassified_as_escape() {
        use std::os::unix::fs::symlink;

        let (_temp, beads_dir) = setup_test_beads_dir();
        let target_path = beads_dir.join("actual.jsonl");
        std::fs::write(&target_path, "{}\n").expect("write target");
        let symlink_path = beads_dir.join("linked.jsonl");
        symlink("actual.jsonl", &symlink_path).expect("create relative symlink");

        let result = validate_sync_path(&symlink_path, &beads_dir);

        assert!(
            matches!(result, PathValidation::NonRegularFile { .. }),
            "internal relative symlink should be rejected as non-regular, not as an escape: {result:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_validate_no_git_path_rejects_symlinked_git_parent() {
        use std::os::unix::fs::symlink;

        let temp = TempDir::new().expect("create temp dir");
        let git_dir = temp.path().join(".git");
        std::fs::create_dir_all(&git_dir).expect("create .git dir");

        let symlink_parent = temp.path().join("gitlink");
        symlink(&git_dir, &symlink_parent).expect("create git symlink");

        let candidate = symlink_parent.join("issues.jsonl");
        let result = validate_no_git_path(&candidate);
        assert!(
            matches!(result, PathValidation::GitPathAttempt { .. }),
            "Symlinked parents targeting .git should be rejected"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_validate_no_git_path_rejects_missing_descendant_under_symlinked_git_parent() {
        use std::os::unix::fs::symlink;

        let temp = TempDir::new().expect("create temp dir");
        let git_dir = temp.path().join(".git");
        std::fs::create_dir_all(&git_dir).expect("create .git dir");

        let symlink_parent = temp.path().join("gitlink");
        symlink(&git_dir, &symlink_parent).expect("create git symlink");

        let candidate = symlink_parent.join("missing").join("issues.jsonl");
        let result = validate_no_git_path(&candidate);
        assert!(
            matches!(result, PathValidation::GitPathAttempt { .. }),
            "Missing descendants under symlinked .git parents should be rejected"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_validate_sync_path_with_external_rejects_missing_descendant_under_symlinked_git_parent()
    {
        use std::os::unix::fs::symlink;

        let temp = TempDir::new().expect("create temp dir");
        let beads_dir = temp.path().join(".beads");
        let git_dir = temp.path().join(".git");
        std::fs::create_dir_all(&beads_dir).expect("create beads dir");
        std::fs::create_dir_all(&git_dir).expect("create .git dir");

        let symlink_parent = temp.path().join("gitlink");
        symlink(&git_dir, &symlink_parent).expect("create git symlink");

        let candidate = symlink_parent.join("missing").join("issues.jsonl");
        let result = validate_sync_path_with_external(&candidate, &beads_dir, true);
        assert!(
            result.is_err(),
            "External JSONL opt-in must not permit missing descendants under symlinked .git parents"
        );
        assert!(
            result.unwrap_err().to_string().contains("git"),
            "error should mention git path rejection"
        );
        assert!(
            !git_dir.join("missing").exists(),
            "validation must not create missing directories inside .git"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_validate_sync_path_with_external_rejects_symlinked_jsonl() {
        use std::os::unix::fs::symlink;

        let temp = TempDir::new().expect("create temp dir");
        let beads_dir = temp.path().join(".beads");
        std::fs::create_dir_all(&beads_dir).expect("create beads dir");

        let outside_target = temp.path().join("secret.txt");
        std::fs::write(&outside_target, "secret data").expect("write");

        let symlink_path = temp.path().join("outside.jsonl");
        symlink(&outside_target, &symlink_path).expect("create symlink");

        let result = validate_sync_path_with_external(&symlink_path, &beads_dir, true);
        assert!(
            result.is_err(),
            "External symlinked JSONL paths should be rejected"
        );
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("must not be a symlink"),
            "Error should explain why the external path was rejected"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_validate_sync_path_with_external_keeps_internal_symlink_escape_checks() {
        use std::os::unix::fs::symlink;

        let (temp, beads_dir) = setup_test_beads_dir();
        let outside_dir = temp.path().join("outside");
        std::fs::create_dir_all(&outside_dir).expect("create outside dir");
        let symlink_parent = beads_dir.join("linked");
        symlink(&outside_dir, &symlink_parent).expect("create symlinked parent");

        let path = symlink_parent.join("issues.jsonl");
        let result = validate_sync_path_with_external(&path, &beads_dir, true);

        assert!(
            result.is_err(),
            "Internal-looking paths must not bypass .beads symlink-escape checks"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_validate_sync_path_rejects_missing_descendant_under_symlinked_parent() {
        use std::os::unix::fs::symlink;

        let (temp, beads_dir) = setup_test_beads_dir();
        let outside_dir = temp.path().join("outside");
        std::fs::create_dir_all(&outside_dir).expect("create outside dir");
        let symlink_parent = beads_dir.join("linked");
        symlink(&outside_dir, &symlink_parent).expect("create symlinked parent");

        let path = symlink_parent.join("nested").join("issues.jsonl");
        let result = validate_sync_path(&path, &beads_dir);

        assert!(
            matches!(result, PathValidation::SymlinkEscape { .. }),
            "Missing descendants below an escaping symlink parent must be rejected"
        );
        assert!(
            !outside_dir.join("nested").exists(),
            "validation must not create external parent directories"
        );
    }

    #[test]
    fn test_validation_logs_rejection() {
        // This test verifies the logging behavior by checking the return value
        // which includes the reason that would be logged
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("../../../etc/passwd");

        let result = validate_sync_path(&path, &beads_dir);
        let reason = result.rejection_reason();
        assert!(reason.is_some(), "Rejected paths should have a reason");
        assert!(
            reason.unwrap().contains("traversal"),
            "Reason should mention traversal"
        );
    }

    #[test]
    fn test_safe_overwrite_blocks_external_without_flag() {
        let (temp, beads_dir) = setup_test_beads_dir();
        let path = temp.path().join("outside.jsonl");

        let result = require_safe_sync_overwrite_path(&path, &beads_dir, false, "overwrite");
        assert!(
            result.is_err(),
            "External overwrite should be rejected without flag"
        );
    }

    #[test]
    fn test_safe_overwrite_allows_external_jsonl_with_flag() {
        let (temp, beads_dir) = setup_test_beads_dir();
        let path = temp.path().join("outside.jsonl");

        let result = require_safe_sync_overwrite_path(&path, &beads_dir, true, "overwrite");
        assert!(
            result.is_ok(),
            "External JSONL overwrite should be allowed with flag"
        );
    }

    #[test]
    fn test_safe_overwrite_rejects_external_non_jsonl() {
        let (temp, beads_dir) = setup_test_beads_dir();
        let path = temp.path().join("outside.txt");

        let result = require_safe_sync_overwrite_path(&path, &beads_dir, true, "overwrite");
        assert!(
            result.is_err(),
            "External non-JSONL overwrite should be rejected"
        );
    }

    #[test]
    fn test_safe_overwrite_rejects_external_directory_named_jsonl() {
        let (temp, beads_dir) = setup_test_beads_dir();
        let path = temp.path().join("outside.jsonl");
        std::fs::create_dir_all(&path).expect("create directory");

        let result = require_safe_sync_overwrite_path(&path, &beads_dir, true, "overwrite");
        assert!(
            result.is_err(),
            "External directories should be rejected even if they look like JSONL files"
        );
    }

    #[test]
    fn test_safe_overwrite_allows_manifest_inside_beads() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join(".manifest.json");

        let result = require_safe_sync_overwrite_path(&path, &beads_dir, true, "overwrite");
        assert!(
            result.is_ok(),
            "Manifest overwrite should be allowed inside .beads"
        );
    }

    // =========================================================================
    // Tests for validate_temp_file_path (PC-4 safety invariant)
    // =========================================================================

    #[test]
    fn test_temp_file_valid_same_directory() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let target = beads_dir.join("issues.jsonl");
        let temp = beads_dir.join("issues.jsonl.tmp");

        let result = validate_temp_file_path(&temp, &target, &beads_dir, false);
        assert!(
            result.is_ok(),
            "Temp file in same directory with .tmp extension should be valid"
        );
    }

    #[test]
    fn test_temp_file_valid_same_directory_with_pid_scoped_name() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let target = beads_dir.join("issues.jsonl");
        let temp = beads_dir.join("issues.jsonl.12345.tmp");

        let result = validate_temp_file_path(&temp, &target, &beads_dir, false);
        assert!(
            result.is_ok(),
            "PID-scoped temp file in same directory should be valid"
        );
    }

    #[test]
    fn test_temp_file_rejects_different_directory() {
        let (temp_dir, beads_dir) = setup_test_beads_dir();
        let target = beads_dir.join("issues.jsonl");
        let temp = temp_dir.path().join("issues.jsonl.tmp"); // Parent dir, not beads_dir

        let result = validate_temp_file_path(&temp, &target, &beads_dir, false);
        assert!(
            result.is_err(),
            "Temp file in different directory should be rejected (PC-4)"
        );
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("same directory") || err.contains("PC-4"),
            "Error should mention same directory requirement: {err}"
        );
    }

    #[test]
    fn test_temp_file_rejects_missing_tmp_extension() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let target = beads_dir.join("issues.jsonl");
        let temp = beads_dir.join("issues.jsonl.bak"); // Wrong extension

        let result = validate_temp_file_path(&temp, &target, &beads_dir, false);
        assert!(
            result.is_err(),
            "Temp file without .tmp extension should be rejected"
        );
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains(".tmp"),
            "Error should mention .tmp extension requirement: {err}"
        );
    }

    #[test]
    fn test_temp_file_rejects_git_path() {
        let (temp_dir, beads_dir) = setup_test_beads_dir();
        let git_dir = temp_dir.path().join(".git");
        std::fs::create_dir_all(&git_dir).expect("create .git dir");
        let target = git_dir.join("config");
        let temp = git_dir.join("config.tmp");

        let result = validate_temp_file_path(&temp, &target, &beads_dir, true);
        assert!(
            result.is_err(),
            "Temp file in .git directory should always be rejected"
        );
    }

    #[test]
    fn test_temp_file_allows_external_with_flag() {
        let (temp_dir, beads_dir) = setup_test_beads_dir();
        let external_dir = temp_dir.path().join("external");
        std::fs::create_dir_all(&external_dir).expect("create external dir");
        let target = external_dir.join("issues.jsonl");
        let temp = external_dir.join("issues.jsonl.tmp");

        let result = validate_temp_file_path(&temp, &target, &beads_dir, true);
        assert!(
            result.is_ok(),
            "External temp file should be allowed when allow_external is true"
        );
    }

    #[test]
    fn test_temp_file_rejects_external_without_flag() {
        let (temp_dir, beads_dir) = setup_test_beads_dir();
        let external_dir = temp_dir.path().join("external");
        std::fs::create_dir_all(&external_dir).expect("create external dir");
        let target = external_dir.join("issues.jsonl");
        let temp = external_dir.join("issues.jsonl.tmp");

        let result = validate_temp_file_path(&temp, &target, &beads_dir, false);
        assert!(
            result.is_err(),
            "External temp file should be rejected when allow_external is false"
        );
    }

    #[test]
    fn test_temp_file_nested_beads_subdir() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let subdir = beads_dir.join("history");
        std::fs::create_dir_all(&subdir).expect("create history subdir");
        let target = subdir.join("backup.jsonl");
        let temp = subdir.join("backup.jsonl.tmp");

        let result = validate_temp_file_path(&temp, &target, &beads_dir, false);
        assert!(
            result.is_ok(),
            "Temp file in nested .beads subdir should be valid"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_temp_file_rejects_existing_symlink() {
        use std::os::unix::fs::symlink;

        let (temp_dir, beads_dir) = setup_test_beads_dir();
        let external_dir = temp_dir.path().join("external");
        std::fs::create_dir_all(&external_dir).expect("create external dir");
        let target = beads_dir.join("issues.jsonl");
        let temp = beads_dir.join("issues.jsonl.tmp");
        symlink(external_dir.join("capture.jsonl"), &temp).expect("create symlink");

        let result = validate_temp_file_path(&temp, &target, &beads_dir, false);
        assert!(
            result.is_err(),
            "Existing symlink temp paths should be rejected"
        );
    }

    #[test]
    fn test_validate_jsonl_fd_metadata_accepts_regular_file() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("issues.jsonl");
        std::fs::write(&path, "{}\n").expect("write");

        let file = File::open(&path).expect("open");
        assert!(
            validate_jsonl_fd_metadata(&file, &path).is_ok(),
            "regular file fd should pass metadata validation"
        );
    }

    #[test]
    fn test_validate_jsonl_fd_metadata_rejects_directory_fd() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let dir_path = beads_dir.join("subdir");
        std::fs::create_dir(&dir_path).expect("create dir");

        let file = File::open(&dir_path).expect("open directory");
        let result = validate_jsonl_fd_metadata(&file, &dir_path);
        assert!(
            result.is_err(),
            "directory fd should fail metadata validation"
        );
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("not a regular file"),
            "error should mention regular file"
        );
    }

    #[cfg(unix)]
    #[test]
    fn open_jsonl_source_nofollow_accepts_regular_file() {
        use std::io::Read;
        use std::os::unix::fs::MetadataExt;

        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("issues.jsonl");
        std::fs::write(&path, "{\"id\":\"br-test\"}\n").expect("write JSONL source");

        let opened = open_jsonl_source_nofollow(&path).expect("securely open regular JSONL");
        let metadata = opened
            .as_file()
            .metadata()
            .expect("read opened fd metadata");
        assert_eq!(opened.identity().device_id(), metadata.dev());
        assert_eq!(opened.identity().inode(), metadata.ino());

        let mut contents = String::new();
        opened
            .into_file()
            .read_to_string(&mut contents)
            .expect("read securely opened JSONL");
        assert_eq!(contents, "{\"id\":\"br-test\"}\n");
    }

    #[cfg(unix)]
    #[test]
    fn open_jsonl_source_nofollow_rejects_directory() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("directory.jsonl");
        std::fs::create_dir(&path).expect("create directory");

        let error =
            open_jsonl_source_nofollow(&path).expect_err("directory must not open as JSONL");
        assert!(
            error.to_string().contains("not a regular file"),
            "error should identify the regular-file requirement: {error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn open_jsonl_source_nofollow_rejects_leaf_symlink_without_mutating_target() {
        use std::os::unix::fs::symlink;

        let (temp, beads_dir) = setup_test_beads_dir();
        let target = temp.path().join("target.jsonl");
        let target_contents = b"{\"protected\":true}\n";
        std::fs::write(&target, target_contents).expect("write symlink target");
        let path = beads_dir.join("issues.jsonl");
        symlink(&target, &path).expect("create leaf symlink");

        let error = open_jsonl_source_nofollow(&path).expect_err("leaf symlink must be rejected");
        assert!(
            error.to_string().contains("source leaf")
                && error.to_string().contains("must not be a symlink"),
            "error should identify the leaf symlink: {error}"
        );
        assert_eq!(
            std::fs::read(&target).expect("read symlink target after rejection"),
            target_contents,
            "rejecting a source symlink must not mutate its target"
        );
    }

    #[cfg(unix)]
    #[test]
    fn open_jsonl_source_nofollow_rejects_parent_symlink_escape() {
        use std::os::unix::fs::symlink;

        let (temp, beads_dir) = setup_test_beads_dir();
        let outside = temp.path().join("outside");
        std::fs::create_dir(&outside).expect("create outside directory");
        std::fs::write(outside.join("issues.jsonl"), "{}\n").expect("write outside JSONL");

        let linked_parent = beads_dir.join("linked");
        symlink(&outside, &linked_parent).expect("create escaping parent symlink");
        let path = linked_parent.join("issues.jsonl");

        let error = open_jsonl_source_nofollow(&path)
            .expect_err("source below a symlinked parent must be rejected");
        assert!(
            error.to_string().contains("parent component")
                && error.to_string().contains("must not be a symlink"),
            "error should identify the parent symlink: {error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn open_jsonl_source_nofollow_rejects_path_replacement_before_identity_recheck() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let path = beads_dir.join("issues.jsonl");
        let replacement = beads_dir.join("replacement.jsonl");
        let displaced = beads_dir.join("displaced.jsonl");
        std::fs::write(&path, "{\"source\":\"original\"}\n").expect("write original source");
        std::fs::write(&replacement, "{\"source\":\"replacement\"}\n")
            .expect("write replacement source");

        let error = open_jsonl_source_nofollow_impl(&path, || {
            std::fs::rename(&path, &displaced)?;
            std::fs::rename(&replacement, &path)
        })
        .expect_err("path replacement must fail identity verification");

        assert!(
            error
                .to_string()
                .contains("changed between secure open and identity verification"),
            "error should identify the fd/path identity mismatch: {error}"
        );
        assert_eq!(
            std::fs::read_to_string(&displaced).expect("read displaced original"),
            "{\"source\":\"original\"}\n"
        );
        assert_eq!(
            std::fs::read_to_string(&path).expect("read installed replacement"),
            "{\"source\":\"replacement\"}\n"
        );
    }

    #[cfg(unix)]
    #[test]
    fn pin_jsonl_target_rejects_symlinked_and_non_directory_parents() {
        use std::os::unix::fs::symlink;

        let temp = TempDir::new().expect("create temp directory");
        let outside = temp.path().join("outside");
        let linked_parent = temp.path().join("linked-parent");
        let non_directory_parent = temp.path().join("not-a-directory");
        std::fs::create_dir(&outside).expect("create outside directory");
        symlink(&outside, &linked_parent).expect("create parent symlink");
        std::fs::write(&non_directory_parent, b"not a directory")
            .expect("write non-directory parent");

        let symlink_error = pin_jsonl_target(&linked_parent.join("issues.jsonl"))
            .expect_err("symlinked parent must be rejected");
        assert!(
            symlink_error.to_string().contains("parent component")
                && symlink_error.to_string().contains("must not be a symlink"),
            "unexpected symlinked-parent error: {symlink_error}"
        );

        let non_directory_error = pin_jsonl_target(&non_directory_parent.join("issues.jsonl"))
            .expect_err("non-directory parent must be rejected");
        assert!(
            non_directory_error
                .to_string()
                .contains("must be a directory"),
            "unexpected non-directory-parent error: {non_directory_error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn pin_jsonl_target_rejects_symlinked_and_nonregular_leaves() {
        use std::os::unix::fs::symlink;

        let temp = TempDir::new().expect("create temp directory");
        let parent = temp.path().join("parent");
        let outside = temp.path().join("outside.jsonl");
        let symlink_leaf = parent.join("linked.jsonl");
        let directory_leaf = parent.join("directory.jsonl");
        std::fs::create_dir(&parent).expect("create parent directory");
        std::fs::write(&outside, b"{\"outside\":true}\n").expect("write outside target");
        symlink(&outside, &symlink_leaf).expect("create leaf symlink");
        std::fs::create_dir(&directory_leaf).expect("create directory leaf");

        let symlink_error =
            pin_jsonl_target(&symlink_leaf).expect_err("symlinked leaf must be rejected");
        assert!(
            symlink_error.to_string().contains("leaf")
                && symlink_error.to_string().contains("must not be a symlink"),
            "unexpected symlinked-leaf error: {symlink_error}"
        );
        assert_eq!(
            std::fs::read(&outside).expect("read outside target"),
            b"{\"outside\":true}\n"
        );

        let directory_error =
            pin_jsonl_target(&directory_leaf).expect_err("directory leaf must be rejected");
        assert!(
            directory_error.to_string().contains("not a regular file"),
            "unexpected directory-leaf error: {directory_error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn pinned_jsonl_name_rejects_non_leaf_components_and_nul() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        let temp = TempDir::new().expect("create temp directory");
        let parent = temp.path().join("parent");
        std::fs::create_dir(&parent).expect("create parent directory");
        let pinned =
            pin_jsonl_target(&parent.join("issues.jsonl")).expect("pin missing JSONL target");

        for invalid in ["", ".", "..", "nested/name", "/absolute"] {
            let error = pinned
                .with_leaf(OsStr::new(invalid))
                .expect_err("non-leaf component must be rejected");
            assert!(
                error
                    .to_string()
                    .contains("one normal filesystem component"),
                "unexpected invalid-leaf error for {invalid:?}: {error}"
            );
        }

        let nul_name = OsString::from_vec(b"nul\0name.jsonl".to_vec());
        let error = pinned
            .with_leaf(&nul_name)
            .expect_err("embedded NUL must be rejected");
        assert!(
            error.to_string().contains("embedded NUL"),
            "unexpected embedded-NUL error: {error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn pinned_jsonl_parent_detects_route_replacement() {
        let temp = TempDir::new().expect("create temp directory");
        let routed_parent = temp.path().join("live");
        let displaced_parent = temp.path().join("displaced");
        std::fs::create_dir(&routed_parent).expect("create routed parent");
        let pinned = pin_jsonl_target(&routed_parent.join("issues.jsonl"))
            .expect("pin missing JSONL target");

        std::fs::rename(&routed_parent, &displaced_parent).expect("displace pinned parent");
        std::fs::create_dir(&routed_parent).expect("create replacement parent");

        let error = pinned
            .parent()
            .verify_route()
            .expect_err("replacement route must not match pinned parent");
        assert!(
            matches!(error, BeadsError::SyncConflict { .. }),
            "route replacement should be a synchronization conflict: {error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn pinned_jsonl_parent_reports_disappeared_or_symlinked_route_as_conflict() {
        use std::os::unix::fs::symlink;

        let temp = TempDir::new().expect("create temp directory");
        let routed_parent = temp.path().join("live");
        let displaced_parent = temp.path().join("displaced");
        std::fs::create_dir(&routed_parent).expect("create routed parent");
        let pinned = pin_jsonl_target(&routed_parent.join("issues.jsonl"))
            .expect("pin missing JSONL target");

        std::fs::rename(&routed_parent, &displaced_parent).expect("displace pinned parent");
        let missing_error = pinned
            .parent()
            .verify_route()
            .expect_err("missing route must be a conflict");
        assert!(
            matches!(missing_error, BeadsError::SyncConflict { .. }),
            "missing route should be a synchronization conflict: {missing_error}"
        );

        symlink(&displaced_parent, &routed_parent).expect("replace route with symlink");
        let symlink_error = pinned
            .parent()
            .verify_route()
            .expect_err("symlinked replacement route must be a conflict");
        assert!(
            matches!(symlink_error, BeadsError::SyncConflict { .. }),
            "symlinked route should be a synchronization conflict: {symlink_error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn stable_parent_traversal_handles_root_but_root_is_not_a_target_leaf() {
        let root = open_jsonl_directory_via_stable_route(Path::new("/"), Path::new("/"))
            .expect("pin filesystem root");
        assert!(
            root.metadata()
                .expect("inspect pinned filesystem root")
                .is_dir()
        );

        let error =
            pin_jsonl_target(Path::new("/")).expect_err("filesystem root has no target leaf");
        assert!(
            error.to_string().contains("has no leaf name"),
            "unexpected root-target error: {error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn pinned_jsonl_operations_remain_on_retained_parent_after_route_swap() {
        use std::io::{Read, Write};
        use std::os::unix::fs::PermissionsExt;

        let temp = TempDir::new().expect("create temp directory");
        let routed_parent = temp.path().join("live");
        let displaced_parent = temp.path().join("displaced");
        let target_path = routed_parent.join("issues.jsonl");
        std::fs::create_dir(&routed_parent).expect("create routed parent");
        std::fs::write(&target_path, b"{\"source\":\"pinned\"}\n")
            .expect("write pinned generation");
        let pinned = pin_jsonl_target(&target_path).expect("pin existing JSONL target");
        let sibling = pinned
            .with_leaf(OsStr::new("sibling.jsonl"))
            .expect("derive pinned sibling");

        std::fs::rename(&routed_parent, &displaced_parent).expect("displace pinned parent");
        std::fs::create_dir(&routed_parent).expect("create replacement route");
        std::fs::write(&target_path, b"{\"source\":\"replacement\"}\n")
            .expect("write replacement-route generation");

        let mut opened = pinned
            .open_optional_regular()
            .expect("open through retained parent")
            .expect("pinned target remains present")
            .into_file();
        let mut opened_contents = String::new();
        opened
            .read_to_string(&mut opened_contents)
            .expect("read pinned target");
        assert_eq!(opened_contents, "{\"source\":\"pinned\"}\n");

        let snapshot = pinned.capture().expect("capture through retained parent");
        let mut captured_contents = String::new();
        snapshot
            .reader()
            .read_to_string(&mut captured_contents)
            .expect("read pinned snapshot");
        assert_eq!(captured_contents, "{\"source\":\"pinned\"}\n");

        drop(pinned);
        let mut sibling_file = sibling
            .create_new_regular()
            .expect("derived sibling must retain the pinned parent fd");
        sibling_file
            .write_all(b"{\"sibling\":\"pinned\"}\n")
            .expect("write pinned sibling");
        sibling_file.sync_all().expect("sync pinned sibling");
        assert_eq!(
            sibling_file
                .metadata()
                .expect("inspect pinned sibling")
                .permissions()
                .mode()
                & 0o077,
            0,
            "handle-relative creation must not grant group or other permissions"
        );
        sibling.parent().fsync().expect("sync pinned parent");
        assert_eq!(
            std::fs::read(displaced_parent.join("sibling.jsonl"))
                .expect("read sibling in retained parent"),
            b"{\"sibling\":\"pinned\"}\n"
        );
        assert!(
            !routed_parent.join("sibling.jsonl").exists(),
            "handle-relative creation must not reach the replacement route"
        );
        assert_eq!(
            std::fs::read(&target_path).expect("read replacement-route target"),
            b"{\"source\":\"replacement\"}\n"
        );
    }

    #[cfg(unix)]
    #[test]
    fn raw_hashes_distinguish_invalid_utf8_sibling_names() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        let temp = TempDir::new().expect("create temp directory");
        let parent = temp.path().join("parent");
        std::fs::create_dir(&parent).expect("create parent directory");
        let pinned =
            pin_jsonl_target(&parent.join("issues.jsonl")).expect("pin missing JSONL target");
        let first_leaf = OsString::from_vec(b"sibling-\x80.jsonl".to_vec());
        let second_leaf = OsString::from_vec(b"sibling-\x81.jsonl".to_vec());
        let first = pinned
            .with_leaf(&first_leaf)
            .expect("derive first invalid-UTF8 sibling");
        let second = pinned
            .with_leaf(&second_leaf)
            .expect("derive second invalid-UTF8 sibling");

        assert_ne!(first.leaf(), second.leaf());
        assert_ne!(first.display_path(), second.display_path());
        assert_ne!(first.leaf_sha256(), second.leaf_sha256());
        assert_ne!(
            external_path_sha256(first.display_path()),
            external_path_sha256(second.display_path())
        );
    }

    #[cfg(not(any(unix, windows)))]
    #[test]
    fn pinned_jsonl_target_fails_closed_without_native_handles() {
        let error = pin_jsonl_target(Path::new("issues.jsonl"))
            .expect_err("unsupported native pinning must fail closed");
        assert!(
            error
                .to_string()
                .contains("Pinned JSONL parent handles are unavailable"),
            "unexpected unsupported-platform pinning error: {error}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn windows_pinned_jsonl_open_capture_and_identity_are_handle_stable() {
        use std::io::Read;

        let temp = TempDir::new().expect("create Windows temp directory");
        let parent = temp.path().join("parent");
        let target = parent.join("issues.jsonl");
        std::fs::create_dir(&parent).expect("create Windows JSONL parent");
        std::fs::write(&target, b"{\"id\":\"br-windows\"}\n").expect("write Windows JSONL source");

        let pinned = pin_jsonl_target(&target).expect("pin Windows JSONL target");
        let opened = pinned
            .open_optional_regular()
            .expect("open Windows JSONL through retained parent")
            .expect("Windows JSONL target should exist");
        assert_eq!(
            opened.identity().volume_serial_number(),
            pinned.parent().identity().volume_serial_number(),
            "file and parent should reside on the same Windows volume"
        );
        assert_eq!(opened.identity().file_index(), opened.identity().inode());

        let snapshot = pinned.capture().expect("capture pinned Windows JSONL");
        assert_eq!(snapshot.identity(), opened.identity());
        let mut contents = String::new();
        snapshot
            .reader()
            .read_to_string(&mut contents)
            .expect("read Windows JSONL snapshot");
        assert_eq!(contents, "{\"id\":\"br-windows\"}\n");
        assert_eq!(
            snapshot.raw_sha256(),
            crate::util::hex_encode(&Sha256::digest(contents.as_bytes()))
        );

        let durability_error = pinned
            .parent()
            .fsync()
            .expect_err("Windows namespace durability must not be falsely certified");
        assert_eq!(durability_error.kind(), std::io::ErrorKind::Unsupported);
        assert!(
            durability_error
                .to_string()
                .contains("cannot certify directory-entry durability")
        );
    }

    #[cfg(windows)]
    #[test]
    fn windows_generic_jsonl_pin_rejects_an_existing_writer() {
        use std::os::windows::fs::OpenOptionsExt;

        const FILE_SHARE_DELETE: u32 = 0x0000_0004;

        let temp = TempDir::new().expect("create Windows temp directory");
        let parent = temp.path().join("parent");
        let target = parent.join("issues.jsonl");
        std::fs::create_dir(&parent).expect("create Windows JSONL parent");
        std::fs::write(&target, b"{\"id\":\"br-writer\"}\n").expect("write Windows JSONL source");
        let writer = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .share_mode(
                PinnedJsonlName::FILE_SHARE_READ
                    | PinnedJsonlName::FILE_SHARE_WRITE
                    | FILE_SHARE_DELETE,
            )
            .open(&target)
            .expect("open compatible Windows writer");

        let error = pin_jsonl_target(&target)
            .expect_err("generic JSONL pin must not admit an existing writer");
        assert!(
            error
                .to_string()
                .contains("Could not open pinned Windows JSONL leaf"),
            "unexpected writer-exclusion error: {error}"
        );

        drop(writer);
        pin_jsonl_target(&target).expect("JSONL pin should succeed after the writer closes");
    }

    #[cfg(windows)]
    #[test]
    fn windows_authority_identity_guard_denies_replacement_until_comparison_finishes() {
        let temp = TempDir::new().expect("create Windows temp directory");
        let parent = temp.path().join("parent");
        let target = parent.join("database-authority.lock");
        let displaced = parent.join("database-authority.displaced");
        std::fs::create_dir(&parent).expect("create Windows authority parent");
        std::fs::write(&target, b"authority generation").expect("write authority file");

        let guard = open_regular_authority_source(&target)
            .expect("open Windows authority identity guard")
            .expect("authority target exists");
        assert_ne!(guard.identity().file_index(), 0);
        let rename_error = std::fs::rename(&target, &displaced)
            .expect_err("the retained comparison guard must deny path replacement");
        assert!(
            matches!(
                rename_error.kind(),
                std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::Other
            ),
            "unexpected Windows sharing-violation error: {rename_error}"
        );

        drop(guard);
        std::fs::rename(&target, &displaced)
            .expect("replacement may proceed only after the comparison guard drops");
    }

    #[cfg(windows)]
    #[test]
    fn windows_pinned_jsonl_create_and_link_no_replace_retain_recovery() {
        use std::io::{Read, Write};

        let temp = TempDir::new().expect("create Windows temp directory");
        let parent = temp.path().join("parent");
        std::fs::create_dir(&parent).expect("create Windows JSONL parent");
        let staged_path = parent.join("issues.jsonl.staged.tmp");
        let output_path = parent.join("issues.jsonl");
        let staged = pin_jsonl_target(&staged_path).expect("pin missing Windows staging leaf");
        let output = staged
            .with_sibling_path(&output_path)
            .expect("derive Windows output sibling");

        let mut staged_file = staged
            .create_new_regular()
            .expect("create Windows staging file without clobber");
        staged_file
            .write_all(b"{\"published\":true}\n")
            .expect("write Windows staging file");
        staged_file.sync_all().expect("sync Windows staging file");
        drop(staged_file);

        let staged_identity = staged
            .capture()
            .expect("capture staged Windows generation")
            .identity();
        let linked_identity = staged
            .link_regular_no_replace_to(&output)
            .expect("atomically link staged generation at missing output");
        assert_eq!(linked_identity, staged_identity);
        assert!(
            staged_path.exists(),
            "staged recovery name must remain until exact by-handle cleanup exists"
        );

        let published = output
            .capture()
            .expect("capture published Windows generation");
        assert_eq!(published.identity(), staged_identity);
        let mut contents = String::new();
        published
            .reader()
            .read_to_string(&mut contents)
            .expect("read published Windows generation");
        assert_eq!(contents, "{\"published\":true}\n");

        let error = staged
            .link_regular_no_replace_to(&output)
            .expect_err("no-replace publication must reject an existing output");
        assert!(
            matches!(error, BeadsError::SyncConflict { .. }),
            "existing Windows output should be a synchronization conflict: {error}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn windows_pinned_jsonl_leaf_rejects_alternate_stream_and_hashes_raw_utf16() {
        use std::ffi::OsString;
        use std::os::windows::ffi::OsStringExt;

        let temp = TempDir::new().expect("create Windows temp directory");
        let parent = temp.path().join("parent");
        std::fs::create_dir(&parent).expect("create Windows JSONL parent");
        let pinned =
            pin_jsonl_target(&parent.join("issues.jsonl")).expect("pin Windows JSONL target");

        let alternate_stream_error = pinned
            .with_leaf(OsStr::new("issues.jsonl:stream"))
            .expect_err("Windows alternate data streams must not be accepted as leaves");
        assert!(
            alternate_stream_error
                .to_string()
                .contains("alternate-data-stream separator")
        );

        let first_leaf = OsString::from_wide(&[
            u16::from(b's'),
            u16::from(b'i'),
            u16::from(b'b'),
            u16::from(b'l'),
            u16::from(b'i'),
            u16::from(b'n'),
            u16::from(b'g'),
            u16::from(b'-'),
            0xd800,
        ]);
        let second_leaf = OsString::from_wide(&[
            u16::from(b's'),
            u16::from(b'i'),
            u16::from(b'b'),
            u16::from(b'l'),
            u16::from(b'i'),
            u16::from(b'n'),
            u16::from(b'g'),
            u16::from(b'-'),
            0xd801,
        ]);
        let first = pinned
            .with_leaf(&first_leaf)
            .expect("derive first raw UTF-16 Windows sibling");
        let second = pinned
            .with_leaf(&second_leaf)
            .expect("derive second raw UTF-16 Windows sibling");
        assert_ne!(first.leaf(), second.leaf());
        assert_ne!(first.leaf_sha256(), second.leaf_sha256());
    }

    #[cfg(windows)]
    #[test]
    fn windows_pinned_jsonl_rejects_reparse_routes_and_pins_open_leaf() {
        use std::os::windows::fs::{symlink_dir, symlink_file};

        let temp = TempDir::new().expect("create Windows temp directory");
        let outside = temp.path().join("outside");
        let parent = temp.path().join("parent");
        std::fs::create_dir(&outside).expect("create outside directory");
        std::fs::create_dir(&parent).expect("create Windows JSONL parent");
        let outside_file = outside.join("outside.jsonl");
        std::fs::write(&outside_file, b"{\"outside\":true}\n")
            .expect("write outside Windows JSONL");

        let linked_parent = temp.path().join("linked-parent");
        match symlink_dir(&outside, &linked_parent) {
            Ok(()) => {
                let error = pin_jsonl_target(&linked_parent.join("issues.jsonl"))
                    .expect_err("Windows parent reparse point must be rejected");
                assert!(
                    error.to_string().contains("non-reparse directory"),
                    "unexpected Windows parent-reparse error: {error}"
                );
            }
            Err(error) if error.raw_os_error() == Some(1314) => {
                eprintln!(
                    "skipping Windows directory-symlink assertion: symbolic-link privilege unavailable"
                );
            }
            Err(error) => assert_eq!(
                error.raw_os_error(),
                Some(1314),
                "create Windows directory symlink: {error}"
            ),
        }

        let linked_leaf = parent.join("linked.jsonl");
        match symlink_file(&outside_file, &linked_leaf) {
            Ok(()) => {
                let error = pin_jsonl_target(&linked_leaf)
                    .expect_err("Windows leaf reparse point must be rejected");
                assert!(
                    error
                        .to_string()
                        .contains("without following reparse points"),
                    "unexpected Windows leaf-reparse error: {error}"
                );
            }
            Err(error) if error.raw_os_error() == Some(1314) => {
                eprintln!(
                    "skipping Windows file-symlink assertion: symbolic-link privilege unavailable"
                );
            }
            Err(error) => assert_eq!(
                error.raw_os_error(),
                Some(1314),
                "create Windows file symlink: {error}"
            ),
        }

        let target = parent.join("issues.jsonl");
        let displaced = parent.join("displaced.jsonl");
        std::fs::write(&target, b"{\"pinned\":true}\n").expect("write pinned Windows JSONL");
        let opened =
            open_jsonl_source_nofollow(&target).expect("open pinned Windows JSONL generation");
        let rename_error = std::fs::rename(&target, &displaced)
            .expect_err("read-only pinned handle must deny Windows rename/delete sharing");
        assert!(
            matches!(
                rename_error.kind(),
                std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::Other
            ),
            "unexpected Windows sharing-violation error: {rename_error}"
        );
        drop(opened);
        std::fs::rename(&target, &displaced)
            .expect("rename should succeed after pinned Windows handle closes");
    }

    // ========================================================================
    // beads_rust-yyxo: tests for sync-safety invariants under SYNC_SAFETY_INVARIANTS.md
    // PC-1, PC-3, PC-RECOVERY (added 2026-05-09 by audit-2026-05-09)
    // ========================================================================

    /// PC-1 / PC-3: a symlink inside `.beads/` whose canonicalized target
    /// escapes via `..` must be rejected as a SymlinkEscape, not silently
    /// accepted via lexical normalization. Linux-only because Windows
    /// symlink semantics differ.
    #[cfg(unix)]
    #[test]
    fn validate_sync_path_rejects_canonicalized_traversal() {
        use std::os::unix::fs::symlink;

        let (temp, beads_dir) = setup_test_beads_dir();
        // External target outside .beads/
        let external = temp.path().join("external");
        std::fs::create_dir_all(&external).expect("create external");
        let external_target = external.join("escape.jsonl");
        std::fs::write(&external_target, "{}").expect("write external");

        // Create a symlink inside .beads/ that points to the external file
        let symlink_path = beads_dir.join("issues.jsonl");
        symlink(&external_target, &symlink_path).expect("create escape symlink");

        let result = validate_sync_path(&symlink_path, &beads_dir);
        assert!(
            !result.is_allowed(),
            "symlink whose target escapes .beads/ must be rejected; got {result:?}"
        );
        assert!(
            matches!(result, PathValidation::SymlinkEscape { .. }),
            "expected SymlinkEscape, got {result:?}"
        );
    }

    /// PC-RECOVERY: paths under `.beads/.br_recovery/` are NOT directly
    /// validated by `validate_sync_path` (recovery has its own path
    /// validation in `src/config/mod.rs`). This test asserts the contract
    /// boundary: `.bak` extension is NOT in the sync-direct allowlist
    /// (it was never written through sync's path), but the test
    /// allowlist in `tests/e2e_sync_git_safety.rs` recognizes them as
    /// legitimate side-effect writes during sync invocation.
    #[test]
    fn validate_sync_path_does_not_accept_recovery_bak_directly() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let recovery = beads_dir.join(".br_recovery");
        std::fs::create_dir_all(&recovery).expect("create recovery dir");
        let bak = recovery.join("beads.db.20260101_000000_0.bak");
        std::fs::write(&bak, "").expect("write");

        let result = validate_sync_path(&bak, &beads_dir);
        assert!(
            !result.is_allowed(),
            "sync's validate_sync_path must NOT accept .bak (recovery owns its own path validation); got {result:?}"
        );
        assert!(
            matches!(result, PathValidation::DisallowedExtension { .. }),
            "expected DisallowedExtension, got {result:?}"
        );
    }

    /// PC-1 / PC-3: a path constructed to look like `.beads/.git/foo` must
    /// be rejected as `GitPathAttempt` regardless of whether `.beads/.git`
    /// exists or contains the actual repo. Hard invariant NGI-3.
    #[test]
    fn validate_sync_path_rejects_dotgit_under_beads() {
        let (_temp, beads_dir) = setup_test_beads_dir();
        let git_path = beads_dir.join(".git").join("HEAD");

        let result = validate_sync_path(&git_path, &beads_dir);
        assert!(
            !result.is_allowed(),
            ".beads/.git/* must always be rejected; got {result:?}"
        );
        assert!(
            matches!(result, PathValidation::GitPathAttempt { .. }),
            "expected GitPathAttempt, got {result:?}"
        );
    }

    /// PC-1: `validate_sync_path` (the in-tree validator) MUST reject
    /// arbitrary external paths even when `BEADS_JSONL`-style env vars
    /// are NOT in play. Use `validate_sync_path_with_external` when the
    /// caller has explicit external-jsonl authorization.
    #[test]
    fn validate_sync_path_rejects_absolute_external_path() {
        let (temp, beads_dir) = setup_test_beads_dir();
        let external = temp.path().join("outside");
        std::fs::create_dir_all(&external).expect("create external");
        let outside = external.join("issues.jsonl");
        std::fs::write(&outside, "{}").expect("write");

        let result = validate_sync_path(&outside, &beads_dir);
        assert!(
            !result.is_allowed(),
            "external path must be rejected by in-tree validator; got {result:?}"
        );
        assert!(
            matches!(result, PathValidation::OutsideBeadsDir { .. }),
            "expected OutsideBeadsDir, got {result:?}"
        );
    }

    /// PC-1: the explicit-external-jsonl validator
    /// (`validate_sync_path_with_external`) MUST accept a non-`.beads/`
    /// path when `allow_external` is true, but still reject
    /// `.beads/.git/*` and traversal attempts.
    #[test]
    fn validate_sync_path_with_external_accepts_explicit_outside_target() {
        let (temp, beads_dir) = setup_test_beads_dir();
        let external_root = temp.path().join("custom-jsonl-store");
        std::fs::create_dir_all(&external_root).expect("create external root");
        let external_target = external_root.join("my-issues.jsonl");
        std::fs::write(&external_target, "{}").expect("write external");

        let result = validate_sync_path_with_external(&external_target, &beads_dir, true);
        assert!(
            result.is_ok(),
            "explicit external path must be allowed when allow_external=true; got {result:?}"
        );

        // But .git rejection still applies
        let git_under_external = external_root.join(".git").join("HEAD");
        let git_result = validate_sync_path_with_external(&git_under_external, &beads_dir, true);
        assert!(
            git_result.is_err(),
            "explicit external must STILL reject .git/* even with allow_external=true; got {git_result:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn private_snapshot_backing_lives_beside_the_source_and_is_never_linked() {
        use std::io::{Read, Seek, SeekFrom, Write};
        use std::os::unix::fs::MetadataExt;

        let temp = TempDir::new().expect("create temp directory");
        let beads_dir = temp.path().join(".beads");
        std::fs::create_dir(&beads_dir).expect("create .beads");

        let mut backing = open_private_snapshot_backing(Some(&beads_dir))
            .expect("backing beside the source must open");
        assert_eq!(
            backing.metadata().expect("backing metadata").dev(),
            std::fs::metadata(&beads_dir)
                .expect(".beads metadata")
                .dev(),
            "the backing must be allocated on the source's own filesystem"
        );
        assert!(
            std::fs::read_dir(&beads_dir)
                .expect("list .beads")
                .next()
                .is_none(),
            "an anonymous backing must leave no directory entry behind"
        );
        backing
            .write_all(b"{\"id\":\"x\"}\n")
            .expect("write backing");
        backing.seek(SeekFrom::Start(0)).expect("rewind backing");
        let mut contents = String::new();
        backing
            .read_to_string(&mut contents)
            .expect("read backing back");
        assert_eq!(contents, "{\"id\":\"x\"}\n");
    }

    #[test]
    fn private_snapshot_backing_falls_back_to_the_temp_directory() {
        let temp = TempDir::new().expect("create temp directory");
        let missing_parent = temp.path().join("does-not-exist");

        open_private_snapshot_backing(Some(&missing_parent))
            .expect("an unusable source directory must fall back to the temp directory");
        open_private_snapshot_backing(Some(Path::new("")))
            .expect("an empty (relative) parent must fall back to the temp directory");
        open_private_snapshot_backing(None)
            .expect("no parent at all must fall back to the temp directory");
    }
}