heddle-cli 0.4.0

An AI-native version control system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
// SPDX-License-Identifier: Apache-2.0
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::{
    io::{Read, Write},
    net::{TcpListener, TcpStream},
    process::{Child, Command, Stdio},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    thread,
    time::Duration,
};

use base64::Engine;
use cli::bridge::{
    GitBridge,
    git_core::{
        GitBridgeError, GitPushScope, SyncMapping, clone_url_to_bare, copy_local_repo_to_bare,
    },
    git_export::{export_all, export_current_thread, export_tree},
    git_notes,
    git_sync::{sync_branches, sync_tags, sync_track_to_branch},
    git_util::ImportStats,
    test_support,
    test_support::{
        RefNamespace, RefUpdate, collect_managed_ref_updates, delete_reference_if_present,
        plan_destination_reconcile, read_exported_refs, read_mirror_managed_refs, set_reference,
        write_exported_refs, write_mirror_managed_refs,
    },
};
use objects::{
    object::{
        Blob, ChangeId, ContentHash, EntryType, FileMode, MarkerName, ThreadName, Tree, TreeEntry,
    },
    store::ObjectStore,
};
use repo::Repository;
use sley::{
    CommitObject, EntryKind, GitObjectType, GitTime, ObjectId, RefPrecondition, ReferenceTarget,
    Repository as SleyRepository, Signature, TagObject,
    plumbing::{sley_core::ByteString as GitByteString, sley_object::EncodedObject},
};
use tempfile::TempDir;

type TestImportResult<T> = Result<T, String>;

trait TestGitBridgeImport {
    fn import(&mut self, git_path: Option<&std::path::Path>) -> TestImportResult<ImportStats>;
}

impl TestGitBridgeImport for GitBridge<'_> {
    fn import(&mut self, git_path: Option<&std::path::Path>) -> TestImportResult<ImportStats> {
        import_all(self, git_path)
    }
}

fn import_all(
    bridge: &mut GitBridge<'_>,
    git_path: Option<&std::path::Path>,
) -> TestImportResult<ImportStats> {
    import_all_with_options(bridge, git_path, ingest::ImportOptions::default())
}

fn import_all_with_options(
    bridge: &mut GitBridge<'_>,
    git_path: Option<&std::path::Path>,
    options: ingest::ImportOptions,
) -> TestImportResult<ImportStats> {
    let target = bridge_root_from_mirror(bridge);
    let source_owned;
    let source = if let Some(path) = git_path {
        path
    } else {
        source_owned = target.clone();
        source_owned.as_path()
    };
    let (stats, _map) = ingest::import_git_into_with_options(source, &target, options)
        .map_err(|error| error.to_string())?;
    test_support::stage_ingest_source_in_mirror(bridge, source, &[])
        .map_err(|error| error.to_string())?;
    test_support::build_existing_mapping(bridge, Some(source))
        .map_err(|error| error.to_string())?;
    let mirror_repo = test_support::open_git_repo(bridge).map_err(|error| error.to_string())?;
    test_support::seed_ingest_identity_mappings_from_mirror(bridge, &mirror_repo)
        .map_err(|error| error.to_string())?;
    Ok(import_stats_from_ingest(stats))
}

fn bridge_root_from_mirror(bridge: &GitBridge<'_>) -> std::path::PathBuf {
    bridge
        .mirror_path()
        .parent()
        .and_then(std::path::Path::parent)
        .expect("mirror path should be <root>/.heddle/git")
        .to_path_buf()
}

fn import_stats_from_ingest(stats: ingest::ImportStats) -> ImportStats {
    ImportStats {
        commits_imported: stats.commits_imported,
        states_created: stats.states_created,
        branches_synced: stats.refs.threads_written,
        tags_synced: stats.refs.markers_written,
        skipped_non_commit_refs: stats.refs_seen.non_commit_skipped,
        lossy_entries: stats.lossy_entries,
    }
}

trait SleyTestRepoExt {
    fn find_tree(&self, oid: ObjectId) -> Result<sley::TreeObject, String>;
    fn find_object(&self, oid: ObjectId) -> Result<TestObject, String>;
    fn find_blob(&self, oid: ObjectId) -> Result<TestBlob, String>;
    fn find_commit(&self, oid: ObjectId) -> Result<TestCommit, String>;
    fn path(&self) -> &std::path::Path;
}

impl SleyTestRepoExt for SleyRepository {
    fn find_tree(&self, oid: ObjectId) -> Result<sley::TreeObject, String> {
        self.read_tree(&oid).map_err(|err| err.to_string())
    }

    fn find_object(&self, oid: ObjectId) -> Result<TestObject, String> {
        let object = self.read_object(&oid).map_err(|err| err.to_string())?;
        Ok(TestObject {
            kind: object.object_type,
            data: object.body.clone(),
        })
    }

    fn find_blob(&self, oid: ObjectId) -> Result<TestBlob, String> {
        let object = self.read_object(&oid).map_err(|err| err.to_string())?;
        if object.object_type != GitObjectType::Blob {
            return Err(format!("object {oid} is not a blob"));
        }
        Ok(TestBlob {
            data: object.body.clone(),
        })
    }

    fn find_commit(&self, oid: ObjectId) -> Result<TestCommit, String> {
        self.read_commit(&oid)
            .map(|commit| TestCommit { commit })
            .map_err(|err| err.to_string())
    }

    fn path(&self) -> &std::path::Path {
        self.git_dir()
    }
}

struct TestReference<'a> {
    repo: &'a SleyRepository,
    target: ReferenceTarget,
}

fn find_reference<'a>(repo: &'a SleyRepository, name: &str) -> Result<TestReference<'a>, String> {
    let target = repo
        .references()
        .read_ref(name)
        .map_err(|err| err.to_string())?
        .ok_or_else(|| format!("reference {name} not found"))?;
    Ok(TestReference { repo, target })
}

impl TestReference<'_> {
    fn id(&self) -> ObjectId {
        self.try_id()
            .expect("test reference should point directly at an object")
    }

    fn try_id(&self) -> Option<ObjectId> {
        self.target().try_id().copied()
    }

    fn peel_to_id(&mut self) -> Result<ObjectId, String> {
        let oid = match &self.target {
            ReferenceTarget::Direct(oid) => *oid,
            ReferenceTarget::Symbolic(name) => {
                let reference = find_reference(self.repo, name)?;
                match reference.target {
                    ReferenceTarget::Direct(oid) => oid,
                    ReferenceTarget::Symbolic(_) => {
                        return Err(format!("nested symbolic reference {name} is unsupported"));
                    }
                }
            }
        };
        peel_oid(self.repo, oid)
    }

    fn target(&self) -> TestReferenceTarget<'_> {
        TestReferenceTarget {
            target: &self.target,
        }
    }
}

struct TestReferenceTarget<'a> {
    target: &'a ReferenceTarget,
}

impl<'a> TestReferenceTarget<'a> {
    fn try_id(&self) -> Option<&'a ObjectId> {
        match self.target {
            ReferenceTarget::Direct(oid) => Some(oid),
            ReferenceTarget::Symbolic(_) => None,
        }
    }
}

struct TestObject {
    kind: GitObjectType,
    data: Vec<u8>,
}

struct TestBlob {
    data: Vec<u8>,
}

struct TestCommit {
    commit: CommitObject,
}

impl TestCommit {
    fn message_raw_sloppy(&self) -> TestRawMessage<'_> {
        TestRawMessage(&self.commit.message)
    }

    fn parent_ids(&self) -> impl Iterator<Item = ObjectId> + '_ {
        self.commit.parents.iter().copied()
    }

    fn tree_id(&self) -> Option<ObjectId> {
        Some(self.commit.tree)
    }
}

struct TestRawMessage<'a>(&'a [u8]);

impl TestRawMessage<'_> {
    fn to_vec(&self) -> Vec<u8> {
        self.0.to_vec()
    }
}

impl std::fmt::Display for TestRawMessage<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", String::from_utf8_lossy(self.0))
    }
}

trait SleyTestTreeExt {
    fn find_entry(&self, name: &str) -> Option<TestTreeEntry<'_>>;
    fn iter(&self) -> std::vec::IntoIter<Result<TestTreeEntry<'_>, String>>;
}

impl SleyTestTreeExt for sley::TreeObject {
    fn find_entry(&self, name: &str) -> Option<TestTreeEntry<'_>> {
        self.entries
            .iter()
            .find(|entry| entry.name.as_bytes() == name.as_bytes())
            .map(|entry| TestTreeEntry { entry })
    }

    fn iter(&self) -> std::vec::IntoIter<Result<TestTreeEntry<'_>, String>> {
        self.entries
            .iter()
            .map(|entry| Ok(TestTreeEntry { entry }))
            .collect::<Vec<_>>()
            .into_iter()
    }
}

struct TestTreeEntry<'a> {
    entry: &'a sley::plumbing::sley_object::TreeEntry,
}

impl TestTreeEntry<'_> {
    fn filename(&self) -> String {
        String::from_utf8_lossy(self.entry.name.as_bytes()).into_owned()
    }

    fn mode(&self) -> TestEntryMode {
        TestEntryMode(self.entry.mode)
    }

    fn object_id(&self) -> ObjectId {
        self.entry.oid
    }
}

struct TestEntryMode(u32);

impl TestEntryMode {
    fn kind(&self) -> EntryKind {
        EntryKind::from_mode(self.0).expect("canonical tree entry mode")
    }
}

fn peel_oid(repo: &SleyRepository, oid: ObjectId) -> Result<ObjectId, String> {
    let object = repo.read_object(&oid).map_err(|err| err.to_string())?;
    if object.object_type == GitObjectType::Tag {
        let tag = repo.read_tag(&oid).map_err(|err| err.to_string())?;
        peel_oid(repo, tag.object)
    } else {
        Ok(oid)
    }
}

fn open_git(path: impl AsRef<std::path::Path>) -> Result<SleyRepository, String> {
    SleyRepository::open(path.as_ref())
        .or_else(|_| SleyRepository::discover(path.as_ref()))
        .map_err(|err| err.to_string())
}

fn init_git_repo() -> (TempDir, SleyRepository) {
    let temp = TempDir::new().expect("temp dir");
    let repo = SleyRepository::init(temp.path()).expect("init git repo");
    (temp, repo)
}

fn init_bare_git_repo() -> (TempDir, SleyRepository) {
    let temp = TempDir::new().expect("temp dir");
    let repo = SleyRepository::init_bare(temp.path()).expect("init bare git repo");
    (temp, repo)
}

fn init_named_bare_git_repo(root: &TempDir, name: &str) -> SleyRepository {
    SleyRepository::init_bare(root.path().join(name)).expect("init named bare git repo")
}

fn test_signature() -> Signature {
    test_signature_at("Heddle Test", "heddle@test", 0, 0)
}

fn test_signature_at(
    name: &str,
    email: &str,
    seconds: i64,
    timezone_offset_minutes: i16,
) -> Signature {
    let time = GitTime::new(seconds, timezone_offset_minutes);
    let raw = format!("{name} <{email}> {seconds} {}", time.offset_token()).into_bytes();
    Signature {
        name: GitByteString::new(name.as_bytes().to_vec()),
        email: GitByteString::new(email.as_bytes().to_vec()),
        time,
        raw,
    }
}

fn empty_tree_oid(repo: &SleyRepository) -> ObjectId {
    repo.write_tree(sley::TreeEditor::new())
        .expect("write empty tree")
}

fn commit_with_tree(
    repo: &SleyRepository,
    reference: Option<&str>,
    tree_oid: ObjectId,
    message: &str,
    parents: &[ObjectId],
) -> ObjectId {
    let sig = test_signature();
    let commit = CommitObject {
        tree: tree_oid,
        parents: parents.to_vec(),
        author: sig.to_ident_bytes(),
        committer: sig.to_ident_bytes(),
        encoding: None,
        message: message.as_bytes().to_vec(),
    };
    let commit_id = repo
        .write_object(EncodedObject::new(GitObjectType::Commit, commit.write()))
        .expect("commit");
    if let Some(reference) = reference {
        set_reference(
            repo,
            reference,
            commit_id,
            RefPrecondition::Any,
            "test: update ref",
        )
        .expect("update ref");
    }
    commit_id
}

fn create_annotated_tag(
    repo: &SleyRepository,
    name: &str,
    target: ObjectId,
    message: &str,
) -> ObjectId {
    let tag = TagObject {
        object: target,
        object_type: GitObjectType::Commit,
        name: name.as_bytes().to_vec(),
        tagger: Some(test_signature().to_ident_bytes()),
        message: message.as_bytes().to_vec(),
        raw_body: None,
    };
    let tag_id = repo
        .write_object(EncodedObject::new(GitObjectType::Tag, tag.write()))
        .expect("write tag");
    set_reference(
        repo,
        &format!("refs/tags/{name}"),
        tag_id,
        RefPrecondition::MustNotExist,
        "test: create tag",
    )
    .expect("create tag ref");
    tag_id
}

fn gitlink_tree(repo: &SleyRepository, name: &str) -> ObjectId {
    let submodule_oid: ObjectId = "0505050505050505050505050505050505050505"
        .parse()
        .expect("oid");
    let mut editor = repo
        .edit_tree(&ObjectId::empty_tree(repo.object_format()))
        .expect("tree editor");
    editor.upsert(name, EntryKind::Commit, submodule_oid);
    repo.write_tree(editor).expect("write tree")
}

fn init_gitlink_repo() -> (TempDir, SleyRepository) {
    let (git_temp, git_repo) = init_git_repo();
    let tree_oid = gitlink_tree(&git_repo, "vendor");
    commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "gitlink", &[]);
    (git_temp, git_repo)
}

struct GitDaemon {
    child: Child,
    port: u16,
}

struct GitHttpBackend {
    join: Option<std::thread::JoinHandle<()>>,
    port: u16,
    stop: Arc<AtomicBool>,
    basic_auth: Option<(String, String)>,
}

fn bind_loopback_ephemeral(context: &str) -> Option<TcpListener> {
    match TcpListener::bind("127.0.0.1:0") {
        Ok(listener) => Some(listener),
        Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => {
            eprintln!("skipping git bridge network test: {context}: {err}");
            None
        }
        Err(err) => panic!("{context}: {err}"),
    }
}

impl GitHttpBackend {
    fn spawn(root: &std::path::Path) -> Option<Self> {
        Self::spawn_with_auth(root, None)
    }

    fn spawn_authenticated(root: &std::path::Path, username: &str, password: &str) -> Option<Self> {
        Self::spawn_with_auth(root, Some((username.to_string(), password.to_string())))
    }

    fn spawn_with_auth(
        root: &std::path::Path,
        basic_auth: Option<(String, String)>,
    ) -> Option<Self> {
        let listener = bind_loopback_ephemeral("bind ephemeral http port")?;
        let port = listener.local_addr().expect("listener addr").port();
        listener
            .set_nonblocking(true)
            .expect("set nonblocking listener");

        let root = root.to_path_buf();
        let stop = Arc::new(AtomicBool::new(false));
        let stop_signal = Arc::clone(&stop);
        let auth = basic_auth.clone();
        let join = thread::spawn(move || {
            loop {
                if stop_signal.load(Ordering::Relaxed) {
                    break;
                }
                match listener.accept() {
                    Ok((stream, _)) => handle_http_backend_connection(stream, &root, auth.as_ref()),
                    Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
                        thread::sleep(Duration::from_millis(10));
                    }
                    Err(_) => break,
                }
            }
        });

        let mut delay = Duration::from_millis(10);
        for _ in 0..20 {
            if TcpStream::connect(("127.0.0.1", port)).is_ok() {
                return Some(Self {
                    join: Some(join),
                    port,
                    stop,
                    basic_auth,
                });
            }
            thread::sleep(delay);
            delay = (delay * 2).min(Duration::from_millis(500));
        }

        panic!("git http backend did not become ready");
    }

    fn url(&self, repo_name: &str) -> String {
        match &self.basic_auth {
            Some((username, password)) => format!(
                "http://{}:{}@127.0.0.1:{}/{}",
                username, password, self.port, repo_name
            ),
            None => format!("http://127.0.0.1:{}/{}", self.port, repo_name),
        }
    }
}

impl Drop for GitHttpBackend {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        let _ = TcpStream::connect(("127.0.0.1", self.port));
        if let Some(join) = self.join.take() {
            let _ = join.join();
        }
    }
}

fn handle_http_backend_connection(
    mut stream: TcpStream,
    root: &std::path::Path,
    basic_auth: Option<&(String, String)>,
) {
    stream.set_nonblocking(false).expect("set stream blocking");
    let mut buffer = Vec::new();
    let mut chunk = [0u8; 8192];
    let header_end;
    loop {
        let read = stream.read(&mut chunk).expect("read request");
        if read == 0 {
            return;
        }
        buffer.extend_from_slice(&chunk[..read]);
        if let Some(pos) = buffer.windows(4).position(|w| w == b"\r\n\r\n") {
            header_end = pos + 4;
            break;
        }
    }

    let header_text = String::from_utf8_lossy(&buffer[..header_end]);
    let mut lines = header_text.split("\r\n");
    let request_line = lines.next().expect("request line");
    let mut parts = request_line.split_whitespace();
    let method = parts.next().expect("method");
    let target = parts.next().expect("target");
    let (path, query) = target.split_once('?').map_or((target, ""), |(p, q)| (p, q));

    let mut content_type = String::new();
    let mut content_length = 0usize;
    let mut authorization = None;
    for line in lines {
        if line.is_empty() {
            continue;
        }
        if let Some((name, value)) = line.split_once(':') {
            let value = value.trim();
            if name.eq_ignore_ascii_case("content-type") {
                content_type = value.to_string();
            } else if name.eq_ignore_ascii_case("content-length") {
                content_length = value.parse().expect("content length");
            } else if name.eq_ignore_ascii_case("authorization") {
                authorization = Some(value.to_string());
            }
        }
    }

    if let Some((username, password)) = basic_auth {
        let expected = format!(
            "Basic {}",
            base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"))
        );
        if authorization.as_deref() != Some(expected.as_str()) {
            write!(
                stream,
                "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"heddle-test\"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
            )
            .expect("write unauthorized response");
            return;
        }
    }

    let mut body = buffer[header_end..].to_vec();
    while body.len() < content_length {
        let read = stream.read(&mut chunk).expect("read body");
        if read == 0 {
            break;
        }
        body.extend_from_slice(&chunk[..read]);
    }
    body.truncate(content_length);

    let mut child = Command::new("git")
        .arg("http-backend")
        .env("GIT_PROJECT_ROOT", root)
        .env("GIT_HTTP_EXPORT_ALL", "1")
        .env("REQUEST_METHOD", method)
        .env("PATH_INFO", path)
        .env("QUERY_STRING", query)
        .env("CONTENT_TYPE", &content_type)
        .env("CONTENT_LENGTH", content_length.to_string())
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("spawn git http-backend");

    if !body.is_empty() {
        child
            .stdin
            .as_mut()
            .expect("stdin")
            .write_all(&body)
            .expect("write backend body");
    }

    let output = child.wait_with_output().expect("wait for backend");
    assert!(output.status.success(), "git http-backend failed");

    let response = output.stdout;
    let split = response
        .windows(4)
        .position(|w| w == b"\r\n\r\n")
        .map(|pos| pos + 4)
        .or_else(|| {
            response
                .windows(2)
                .position(|w| w == b"\n\n")
                .map(|pos| pos + 2)
        })
        .expect("cgi headers");
    let headers = String::from_utf8_lossy(&response[..split]);
    let body = &response[split..];

    let mut status = "200 OK".to_string();
    let mut response_headers = Vec::new();
    for line in headers.lines() {
        let line = line.trim_end_matches('\r');
        if line.is_empty() {
            continue;
        }
        if let Some(value) = line.strip_prefix("Status:") {
            status = value.trim().to_string();
        } else {
            response_headers.push(line.to_string());
        }
    }
    response_headers.push(format!("Content-Length: {}", body.len()));
    response_headers.push("Connection: close".to_string());

    write!(stream, "HTTP/1.1 {}\r\n", status).expect("write status");
    for header in response_headers {
        write!(stream, "{}\r\n", header).expect("write header");
    }
    write!(stream, "\r\n").expect("write response separator");
    stream.write_all(body).expect("write response body");
}

impl GitDaemon {
    fn spawn(root: &std::path::Path) -> Option<Self> {
        Self::spawn_with_push(root, false)
    }

    /// Spawn a daemon that also serves `receive-pack`, so the network PUSH path
    /// (`push_network_remote_with_updates`) can be exercised against a real wire
    /// remote — the only way to cover the URL/network destination reconciliation
    /// (heddle#316 r11). `git daemon` denies anonymous push unless
    /// `--enable=receive-pack` is passed.
    fn spawn_push(root: &std::path::Path) -> Option<Self> {
        Self::spawn_with_push(root, true)
    }

    fn spawn_with_push(root: &std::path::Path, allow_push: bool) -> Option<Self> {
        let listener = bind_loopback_ephemeral("bind ephemeral port")?;
        let port = listener.local_addr().expect("listener addr").port();
        drop(listener);

        let mut args: Vec<String> = vec![
            "daemon".to_string(),
            "--reuseaddr".to_string(),
            "--export-all".to_string(),
            format!("--base-path={}", root.display()),
            "--listen=127.0.0.1".to_string(),
            format!("--port={port}"),
        ];
        if allow_push {
            args.push("--enable=receive-pack".to_string());
        }
        args.push(root.to_str().expect("root path").to_string());

        let child = Command::new("git")
            .args(&args)
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()
            .expect("spawn git daemon");

        let mut delay = Duration::from_millis(10);
        for _ in 0..20 {
            if TcpStream::connect(("127.0.0.1", port)).is_ok() {
                return Some(Self { child, port });
            }
            thread::sleep(delay);
            delay = (delay * 2).min(Duration::from_millis(500));
        }

        let output = child.wait_with_output().expect("wait for git daemon");
        panic!(
            "git daemon did not become ready: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn url(&self, repo_name: &str) -> String {
        format!("git://127.0.0.1:{}/{}", self.port, repo_name)
    }
}

impl Drop for GitDaemon {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

#[test]
fn sync_tags_peels_annotated_tags() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&git_repo);
    let commit_oid = commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&git_repo, "v1.0", commit_oid, "release");

    let mut bridge = GitBridge::new(&repo);
    test_support::set_git_repo_path(
        &mut bridge,
        git_repo.workdir().expect("workdir").to_path_buf(),
    );
    let change_id = ChangeId::generate();
    test_support::mapping_mut(&mut bridge).insert(change_id, commit_oid);

    let synced = sync_tags(&mut bridge).expect("sync tags");
    assert_eq!(synced, 1);
    assert_eq!(
        repo.refs().get_marker(&MarkerName::new("v1.0")).unwrap(),
        Some(change_id)
    );
}

#[test]
fn sync_track_to_branch_advances_branch_to_thread_tip() {
    let (_git_temp, git_repo) = init_git_repo();
    let tree_oid = empty_tree_oid(&git_repo);
    let first = commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    let second = commit_with_tree(&git_repo, None, tree_oid, "next", &[first]);

    // Heddle owns thread→branch sync, so the branch ref is updated to
    // match the thread tip rather than rejecting non-fast-forward
    // moves: the source of truth for `refs/heads/<thread>` is the
    // Heddle thread, not the Git ref.
    sync_track_to_branch(&git_repo, "main", second).expect("branch sync must succeed");

    let mut updated =
        find_reference(&git_repo, "refs/heads/main").expect("branch ref present after sync");
    let updated_oid = updated.peel_to_id().expect("peel ref");
    assert_eq!(
        updated_oid, second,
        "branch main should now point at the thread tip"
    );
}

#[test]
fn export_tree_writes_submodule_entries() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let submodule_oid: ObjectId = "0303030303030303030303030303030303030303"
        .parse()
        .expect("oid");
    let blob = Blob::new(format!("heddle-submodule: {}", submodule_oid).into_bytes());
    let blob_hash = repo.store().put_blob(&blob).expect("blob");

    let tree = Tree::from_entries(vec![TreeEntry {
        name: "vendor".to_string(),
        mode: FileMode::Normal,
        entry_type: EntryType::Blob,
        hash: blob_hash,
    }]);
    let tree_hash = repo.store().put_tree(&tree).expect("tree");

    let tree_oid = export_tree(&repo, &git_repo, &tree_hash).expect("export");
    let git_tree = git_repo.find_tree(tree_oid).expect("git tree");
    let entry = git_tree.find_entry("vendor").expect("entry");

    assert_eq!(entry.mode().kind(), EntryKind::Commit);
    assert_eq!(entry.object_id(), submodule_oid);
}

#[test]
fn export_tree_substitutes_stub_for_redacted_blob() {
    // Critical safety property of the redaction primitive: a leaked
    // secret declared via `heddle redact` must NEVER appear in the
    // bytes the Git bridge writes downstream. The bridge is the only
    // path from a Heddle repo to an external Git remote (GitHub,
    // GitLab, internal mirrors), and bytes that escape via the
    // bridge cannot be retroactively scrubbed from those repos.
    //
    // This test pins the contract: with a redaction declared on a
    // blob, exporting the containing tree must write a stub blob
    // (which contains the redaction notice + an audit pointer)
    // instead of the raw secret bytes. Even though the secret is
    // still on disk in Heddle's local store, it does not propagate.

    use chrono::Utc;
    use objects::object::{ContentHash, Principal, Redaction};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let secret_bytes = b"AWS_SECRET_ACCESS_KEY=hunter2-leaked\n";
    let blob = Blob::new(secret_bytes.to_vec());
    let blob_hash = repo.store().put_blob(&blob).expect("blob");

    let tree = Tree::from_entries(vec![TreeEntry {
        name: "secrets.env".to_string(),
        mode: FileMode::Normal,
        entry_type: EntryType::Blob,
        hash: blob_hash,
    }]);
    let tree_hash = repo.store().put_tree(&tree).expect("tree");

    // Declare a redaction on the blob. The redaction's `state` doesn't
    // matter for export — the store is keyed by blob hash — but we
    // populate the field so the stub renders a believable audit line.
    let dummy_state = ChangeId::from_bytes([42u8; 16]);
    repo.put_redaction(Redaction {
        redacted_blob: blob_hash,
        state: dummy_state,
        path: "secrets.env".into(),
        reason: "leaked AWS key".into(),
        redactor: Principal {
            name: "Auditor".into(),
            email: "auditor@heddle.sh".into(),
        },
        redacted_at: Utc::now(),
        signature: None,
        purged_at: None,
        supersedes: None,
    })
    .expect("declare redaction");

    // Export. The bridge MUST substitute the stub.
    let tree_oid = export_tree(&repo, &git_repo, &tree_hash).expect("export");
    let git_tree = git_repo.find_tree(tree_oid).expect("git tree");
    let entry = git_tree.find_entry("secrets.env").expect("entry");

    // The exported blob's bytes must NOT contain the secret.
    let git_blob = git_repo
        .find_blob(entry.object_id())
        .expect("find exported blob");
    let exported_bytes = git_blob.data.as_slice();
    let exported_text = std::str::from_utf8(exported_bytes).expect("stub is utf-8");

    assert!(
        !exported_text.contains("hunter2-leaked"),
        "EXPORT LEAK: redacted blob bytes reached Git. Got: {exported_text:?}"
    );
    assert!(
        !exported_bytes
            .windows(secret_bytes.len())
            .any(|w| w == secret_bytes),
        "EXPORT LEAK (byte-level): raw secret bytes reached Git tree"
    );
    // The substituted blob must be recognizable as a redaction stub
    // so downstream Git readers see why content disappeared.
    assert!(
        exported_text.contains("redacted by Heddle"),
        "stub must announce itself; got: {exported_text:?}"
    );
    assert!(
        exported_text.contains("leaked AWS key"),
        "stub must carry the redaction reason; got: {exported_text:?}"
    );

    // Sanity: the heddle store still holds the original bytes (purge
    // hasn't happened yet) — the substitution is on the *export path*,
    // not the underlying store.
    let still_in_store = repo
        .store()
        .get_blob(&blob_hash)
        .expect("store lookup")
        .expect("blob still present pre-purge");
    assert_eq!(still_in_store.content(), secret_bytes);

    // Quiet `unused` warnings on imports used only by this test:
    let _ = ContentHash::from_bytes([0u8; 32]);
}

#[test]
fn import_all_rejects_gitlink_by_default_and_lossy_reports_drop() {
    let (_git_temp, git_repo) = init_gitlink_repo();

    let default_heddle = TempDir::new().expect("heddle temp");
    let default_repo = Repository::init(default_heddle.path()).expect("init heddle");
    let mut default_bridge = GitBridge::new(&default_repo);
    let err = import_all(
        &mut default_bridge,
        Some(git_repo.workdir().expect("workdir").as_path()),
    )
    .expect_err("default import must fail on gitlink");
    let message = err.to_string();
    assert!(message.contains("vendor"), "error names entry: {message}");
    assert!(message.contains("--lossy"), "error names opt-in: {message}");

    let lossy_heddle = TempDir::new().expect("heddle temp");
    let lossy_repo = Repository::init(lossy_heddle.path()).expect("init heddle");
    let mut lossy_bridge = GitBridge::new(&lossy_repo);
    let stats = import_all_with_options(
        &mut lossy_bridge,
        Some(git_repo.workdir().expect("workdir").as_path()),
        ingest::ImportOptions { lossy: true },
    )
    .expect("lossy import accepts gitlink drop");

    assert_eq!(stats.states_created, 1);
    assert_eq!(stats.lossy_entries.len(), 1);
    assert_eq!(stats.lossy_entries[0].path, "vendor");
    assert!(stats.lossy_entries[0].summary_line().contains("dropped"));
}

#[test]
fn import_all_lossy_reports_cached_shared_subtree_entries_without_mapping_sidecar() {
    let (_git_temp, git_repo) = init_git_repo();
    let shared_tree = gitlink_tree(&git_repo, "vendor");

    let mut first_editor = git_repo
        .edit_tree(&empty_tree_oid(&git_repo))
        .expect("first tree editor");
    first_editor.upsert("shared", EntryKind::Tree, shared_tree);
    let first_tree = git_repo.write_tree(first_editor).expect("write first tree");
    let first_commit = commit_with_tree(&git_repo, None, first_tree, "add shared subtree", &[]);

    let note_blob = git_repo.write_blob(b"second\n").expect("note blob");
    let mut second_editor = git_repo
        .edit_tree(&empty_tree_oid(&git_repo))
        .expect("second tree editor");
    second_editor.upsert("shared", EntryKind::Tree, shared_tree);
    second_editor.upsert("note.txt", EntryKind::Blob, note_blob);
    let second_tree = git_repo
        .write_tree(second_editor)
        .expect("write second tree");
    let _second_commit = commit_with_tree(
        &git_repo,
        Some("refs/heads/main"),
        second_tree,
        "reuse shared subtree",
        &[first_commit],
    );

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let mut bridge = GitBridge::new(&repo);
    let stats = import_all_with_options(
        &mut bridge,
        Some(&git_repo.workdir().expect("workdir")),
        ingest::ImportOptions { lossy: true },
    )
    .expect("lossy import accepts shared gitlink subtree");

    assert_eq!(stats.states_created, 2);
    assert_eq!(
        stats.lossy_entries.len(),
        2,
        "runtime stats should include both the original and cached ingest lossy entries"
    );
    assert_eq!(stats.lossy_entries[0].path, "shared/vendor");
    assert_eq!(stats.lossy_entries[1].path, "shared/vendor");

    assert!(
        !test_support::mapping_path(&bridge).exists(),
        "bridge import must not publish lossy entries through the served mapping cache"
    );
}

#[test]
fn import_all_default_fails_on_cached_lossy_commit_from_prior_run() {
    let (_git_temp, git_repo) = init_gitlink_repo();
    let git_path = git_repo.workdir().expect("workdir");
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");

    let mut first_bridge = GitBridge::new(&repo);
    let first = import_all_with_options(
        &mut first_bridge,
        Some(git_path.as_path()),
        ingest::ImportOptions { lossy: true },
    )
    .expect("initial lossy bridge import succeeds");
    assert_eq!(first.lossy_entries.len(), 1);

    assert!(
        !test_support::mapping_path(&first_bridge).exists(),
        "bridge import must not publish lossy entries through the served mapping cache"
    );

    let mut rerun_bridge = GitBridge::new(&repo);
    let err = import_all(&mut rerun_bridge, Some(git_path.as_path()))
        .expect_err("default bridge import must not reuse cached lossy state silently");
    assert_lossy_default_rerun_error("bridge", &err.to_string());
}

#[test]
fn import_all_lossy_reports_cached_lossy_commit_from_prior_run() {
    let (_git_temp, git_repo) = init_gitlink_repo();
    let git_path = git_repo.workdir().expect("workdir");
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");

    let mut first_bridge = GitBridge::new(&repo);
    import_all_with_options(
        &mut first_bridge,
        Some(git_path.as_path()),
        ingest::ImportOptions { lossy: true },
    )
    .expect("initial lossy bridge import succeeds");

    let mut rerun_bridge = GitBridge::new(&repo);
    let second = import_all_with_options(
        &mut rerun_bridge,
        Some(git_path.as_path()),
        ingest::ImportOptions { lossy: true },
    )
    .expect("lossy bridge rerun reports ingest-cached lossy entries");

    assert_eq!(second.states_created, 0);
    assert_eq!(second.lossy_entries.len(), 1);
    assert_eq!(second.lossy_entries[0].path, "vendor");
    assert!(second.lossy_entries[0].summary_line().contains("dropped"));
}

#[cfg(feature = "ingest")]
#[derive(Clone, Copy, Debug)]
enum ImportEngine {
    Ingest,
    Bridge,
}

#[cfg(feature = "ingest")]
impl ImportEngine {
    fn label(self) -> &'static str {
        match self {
            ImportEngine::Ingest => "ingest",
            ImportEngine::Bridge => "bridge",
        }
    }
}

fn assert_lossy_default_rerun_error(engine: &str, message: &str) {
    assert!(
        message.contains("vendor"),
        "{engine} error names entry: {message}"
    );
    assert!(
        message.contains("losslessly"),
        "{engine} error explains policy: {message}"
    );
    assert!(
        message.contains("--lossy"),
        "{engine} error names opt-in: {message}"
    );
}

#[cfg(feature = "ingest")]
fn run_lossy_then_default_rerun(engine: ImportEngine) {
    let (_git_temp, git_repo) = init_gitlink_repo();
    let git_path = git_repo.workdir().expect("workdir");
    let message = match engine {
        ImportEngine::Ingest => {
            use ingest::{ImportOptions, import_git_into, import_git_into_with_options};

            let heddle_temp = TempDir::new().expect("heddle temp");
            let (first, map) = import_git_into_with_options(
                &git_path,
                heddle_temp.path(),
                ImportOptions { lossy: true },
            )
            .expect("initial lossy ingest import succeeds");
            drop(map);
            assert_eq!(first.lossy_entries.len(), 1);

            import_git_into(git_path, heddle_temp.path())
                .expect_err("default ingest import must fail on cached lossy tree")
                .to_string()
        }
        ImportEngine::Bridge => {
            let heddle_temp = TempDir::new().expect("heddle temp");
            let repo = Repository::init(heddle_temp.path()).expect("init heddle");
            let mut first_bridge = GitBridge::new(&repo);
            let first = import_all_with_options(
                &mut first_bridge,
                Some(git_path.as_path()),
                ingest::ImportOptions { lossy: true },
            )
            .expect("initial lossy bridge import succeeds");
            assert_eq!(first.lossy_entries.len(), 1);

            let mut rerun_bridge = GitBridge::new(&repo);
            import_all(&mut rerun_bridge, Some(git_path.as_path()))
                .expect_err("default bridge import must fail on cached lossy commit")
                .to_string()
        }
    };

    assert_lossy_default_rerun_error(engine.label(), &message);
}

#[cfg(feature = "ingest")]
#[test]
fn both_engines_fail_hard_on_default_rerun_after_lossy() {
    for engine in [ImportEngine::Ingest, ImportEngine::Bridge] {
        run_lossy_then_default_rerun(engine);
    }
}

#[test]
fn import_all_lossy_clean_repo_reports_no_lossy_entries() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();
    let tree_oid = empty_tree_oid(&git_repo);
    commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "clean", &[]);

    let mut bridge = GitBridge::new(&repo);
    let stats = import_all_with_options(
        &mut bridge,
        Some(git_repo.workdir().expect("workdir").as_path()),
        ingest::ImportOptions { lossy: true },
    )
    .expect("clean repo imports with lossy flag too");

    assert_eq!(stats.states_created, 1);
    assert!(stats.lossy_entries.is_empty());
}

/// The single imported gitlink state must carry git-fidelity (`raw_message`) —
/// the signal that opts a commit INTO reconstruct-from-state — yet be flagged
/// `git_lossy`, so the #567 export guard keeps it OFF that path. Asserted for
/// both lossy population surfaces so they converge on ONE canonical marker.
fn assert_only_state_is_lossy_with_fidelity(repo: &Repository, surface: &str) {
    let states: Vec<_> = repo
        .store()
        .list_states()
        .expect("list states")
        .iter()
        .filter_map(|id| repo.store().get_state(id).expect("get state"))
        .collect();
    assert_eq!(states.len(), 1, "{surface}: single gitlink commit imported");
    let state = &states[0];
    assert!(
        state.raw_message.is_some(),
        "{surface}: git-fidelity (raw_message) present — without the lossy \
         marker this is exactly what the buggy guard reconstructs"
    );
    assert!(
        state.git_lossy,
        "{surface}: a --lossy import must set the canonical git_lossy marker so \
         export does not reconstruct a wrong-SHA object"
    );
}

/// `bridge git import --lossy` records the canonical `git_lossy` marker.
#[test]
fn bridge_import_lossy_state_carries_canonical_git_lossy_marker() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_gitlink_repo();

    let mut bridge = GitBridge::new(&repo);
    let stats = import_all_with_options(
        &mut bridge,
        Some(git_repo.workdir().expect("workdir").as_path()),
        ingest::ImportOptions { lossy: true },
    )
    .expect("lossy bridge import succeeds");
    assert_eq!(
        stats.lossy_entries.len(),
        1,
        "gitlink is the one lossy entry"
    );

    assert_only_state_is_lossy_with_fidelity(&repo, "bridge import --lossy");
}

/// Close-the-class regression for #567 round 2: an ingest-backed lossy state
/// carries the SAME canonical `git_lossy` marker that `bridge import --lossy`
/// sets. Before this fix, ingest states satisfied `has_git_fidelity` but
/// carried no lossy signal reachable from an UNMAPPED state, so the export
/// guard reconstructed them into wrong-SHA objects. Both paths now set ONE flag
/// the guard reads.
#[cfg(feature = "ingest")]
#[test]
fn ingest_lossy_state_carries_canonical_git_lossy_marker() {
    use ingest::{ImportOptions, import_git_into_with_options};

    let (_git_temp, git_repo) = init_gitlink_repo();
    let git_path = git_repo.workdir().expect("workdir");

    let heddle_temp = TempDir::new().expect("heddle temp");
    let (stats, map) =
        import_git_into_with_options(git_path, heddle_temp.path(), ImportOptions { lossy: true })
            .expect("lossy ingest succeeds");
    drop(map);
    assert_eq!(
        stats.lossy_entries.len(),
        1,
        "gitlink is the one lossy entry"
    );

    let repo = Repository::open(heddle_temp.path()).expect("open heddle repo");
    assert_only_state_is_lossy_with_fidelity(&repo, "ingest-backed lossy import");
}

/// #567 round 3: an ingest-backed lossy state is UNMAPPED yet carries
/// git-fidelity (`raw_message`). Export must MINT it from its OWN raw metadata —
/// there is no tracked original OID to match and no verbatim mirror bytes to
/// fall back to, so the r2 `git_lossy` guard must NOT reject it into the
/// (nonexistent) verbatim/mapped-OID path (the r2 over-correction). The minted
/// commit preserves the raw message verbatim; the native intent+footer mint
/// would instead emit "No intent specified" + a
/// `Heddle-State` footer. The minted OID is DERIVED (there is no original to
/// match); the load-bearing assertion is that the raw metadata survives the mint.
#[cfg(feature = "ingest")]
#[test]
fn export_mints_lossy_ingest_state_from_raw_metadata() {
    use ingest::{ImportOptions, import_git_into_with_options};

    let (_git_temp, git_repo) = init_gitlink_repo();
    let git_path = git_repo.workdir().expect("workdir");

    let heddle_temp = TempDir::new().expect("heddle temp");
    let (stats, map) =
        import_git_into_with_options(git_path, heddle_temp.path(), ImportOptions { lossy: true })
            .expect("lossy ingest succeeds");
    drop(map);
    assert_eq!(
        stats.lossy_entries.len(),
        1,
        "gitlink is the one lossy entry"
    );

    let repo = Repository::open(heddle_temp.path()).expect("open heddle repo");
    let state = {
        let ids = repo.store().list_states().expect("list states");
        assert_eq!(ids.len(), 1, "single gitlink commit ingested");
        repo.store()
            .get_state(&ids[0])
            .expect("get state")
            .expect("state present")
    };
    let raw_message = state
        .raw_message
        .clone()
        .expect("ingest records raw_message");

    // Ingest records local identity in its SQLite map, not the served bridge
    // mapping, so this is exactly the unmapped lossy case that export must MINT,
    // not reject.
    let mut bridge = GitBridge::new(&repo);

    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export");
    bridge
        .export_to_path(&dest_path)
        .expect("export must MINT the unmapped lossy state, not reject it");

    let dest_repo = open_git(&dest_path).expect("open dest");
    let dest_main = find_reference(&dest_repo, "refs/heads/main")
        .expect("exported main ref")
        .peel_to_id()
        .expect("exported main target");
    let dest_commit = dest_repo.find_commit(dest_main).expect("dest main commit");

    // Minted from raw metadata: the message is the verbatim raw_message, NOT the
    // native "No intent specified" + Heddle-State footer the intent-mint emits.
    assert_eq!(
        dest_commit.message_raw_sloppy().to_vec(),
        raw_message,
        "exported commit must preserve the ingest state's raw message verbatim, \
         not the native \"No intent specified\" + Heddle-State footer"
    );
}

/// Regression: `copy_local_repo_to_bare` (the engine behind `heddle clone
/// /path/to/bare /work` for git-overlay paths) used to walk every tree
/// entry without distinguishing gitlinks from regular blobs/subtrees,
/// pushing the gitlink's foreign-repo commit OID onto the reachability
/// stack. The next `find_object` then failed with
/// "An object with id … could not be found", so any source repo
/// containing a submodule (e.g. git/git's `sha1collisiondetection`)
/// could not be cloned through heddle.
///
/// The fix skips `EntryKind::Commit` entries during the reachability
/// walk: by Git's design, gitlink commits live in the submodule's own
/// repo and are not stored locally. The bridge import path
/// (`import_gitlink`) records the foreign OID as a `heddle-submodule:`
/// blob, which is what round-trips on export — so dropping it from the
/// walk loses no information.
#[test]
fn copy_local_repo_to_bare_handles_gitlink_entries() {
    let (_src_temp, source) = init_bare_git_repo();
    let dest_temp = TempDir::new().expect("dest temp");
    let dest_path = dest_temp.path().join("dest.git");

    // Build a tree containing one gitlink entry pointing at a
    // fabricated commit OID that is *not* present in this repo —
    // exactly the shape git/git ships with `sha1collisiondetection`.
    let foreign_submodule_oid: ObjectId = "855827c583bc30645ba427885caa40c5b81764d2"
        .parse()
        .expect("oid");
    let mut editor = source
        .edit_tree(&empty_tree_oid(&source))
        .expect("tree editor");
    editor.upsert(
        "sha1collisiondetection",
        EntryKind::Commit,
        foreign_submodule_oid,
    );
    let tree_with_gitlink = source.write_tree(editor).expect("write tree");
    let commit = commit_with_tree(
        &source,
        Some("refs/heads/main"),
        tree_with_gitlink,
        "add submodule",
        &[],
    );

    // Sanity: the gitlink target must really not be in the source repo
    // (otherwise we're not exercising the regression).
    assert!(
        source.find_object(foreign_submodule_oid).is_err(),
        "test setup invariant: gitlink target should not be present locally"
    );
    assert!(
        source.find_commit(commit).is_ok(),
        "test setup invariant: parent commit should be present"
    );

    // The pre-fix code path would error here with
    // "An object with id 855827c5… could not be found"; with the
    // gitlink-skip, it succeeds and the destination has every reachable
    // non-gitlink object.
    copy_local_repo_to_bare(source.path(), &dest_path).expect("copy with gitlink");

    let dest = open_git(&dest_path).expect("open dest");
    assert!(
        dest.find_commit(commit).is_ok(),
        "destination must contain the parent commit"
    );
    assert!(
        dest.find_tree(tree_with_gitlink).is_ok(),
        "destination must contain the gitlink-bearing tree"
    );
    assert!(
        dest.find_object(foreign_submodule_oid).is_err(),
        "gitlink target stays out-of-band — that's the whole point"
    );

    // The gitlink entry on the copied tree round-trips its mode + OID
    // verbatim.
    let copied_tree = dest.find_tree(tree_with_gitlink).expect("dest tree");
    let entry = copied_tree
        .find_entry("sha1collisiondetection")
        .expect("entry");
    assert_eq!(entry.mode().kind(), EntryKind::Commit);
    assert_eq!(entry.object_id(), foreign_submodule_oid);
}

/// Regression: `copy_local_repo_to_bare` used to force the destination
/// HEAD to `refs/heads/main` whenever a `main` branch existed in the
/// source — even when the source repo's actual HEAD pointed at a
/// different branch. A repo on `master` that also happened to carry a
/// `main` branch (a common shape in projects mid-rename) would be
/// silently checked out on the wrong branch after `heddle clone`.
///
/// Fix: read the source repo's symbolic HEAD and honour it when it
/// names a branch we copied; fall back to `main` (then any first
/// branch) only when the source HEAD is detached or unmapped.
#[test]
fn copy_local_repo_to_bare_preserves_source_head_branch() {
    let (_src_temp, source) = init_bare_git_repo();
    let dest_temp = TempDir::new().expect("dest temp");
    let dest_path = dest_temp.path().join("dest.git");

    let tree = empty_tree_oid(&source);
    let master_tip = commit_with_tree(&source, Some("refs/heads/master"), tree, "M", &[]);
    let main_tip = commit_with_tree(&source, Some("refs/heads/main"), tree, "Mn", &[]);
    assert_ne!(master_tip, main_tip);

    // Source HEAD points at master, not main.
    std::fs::write(source.path().join("HEAD"), b"ref: refs/heads/master\n").expect("set HEAD");

    copy_local_repo_to_bare(source.path(), &dest_path).expect("copy");

    let head = std::fs::read_to_string(dest_path.join("HEAD")).expect("read HEAD");
    assert_eq!(
        head.trim(),
        "ref: refs/heads/master",
        "destination HEAD must mirror source HEAD even when a `main` branch exists alongside"
    );
}

/// `write_through_current_checkout`'s rollback path used to only reset
/// the branch ref when a *prior* OID existed at that ref. If write-through
/// created the branch from scratch (no prior value) and then a later
/// step failed — e.g., an index write or one of the fsyncs — the
/// new branch was left behind, so callers saw an error but Git still
/// showed the half-written ref.
///
/// The fix uses `delete_reference_if_present` on rollback when no
/// previous_branch existed. This test exercises the helper directly:
/// creating a new ref with `set_reference` and then dropping it through
/// the same path the rollback uses must leave the destination repo
/// without the ref. A no-op delete on a missing ref must succeed too,
/// so the rollback can run idempotently after a partial failure.
#[test]
fn delete_reference_if_present_drops_new_branch_for_rollback() {
    let (_temp, repo) = init_bare_git_repo();
    let tree = empty_tree_oid(&repo);
    let oid = commit_with_tree(&repo, None, tree, "rollback target", &[]);

    set_reference(
        &repo,
        "refs/heads/feature-x",
        oid,
        RefPrecondition::MustNotExist,
        "create branch",
    )
    .expect("create branch");
    assert!(
        find_reference(&repo, "refs/heads/feature-x").is_ok(),
        "set_reference must create the branch"
    );

    delete_reference_if_present(&repo, "refs/heads/feature-x").expect("delete");
    assert!(
        find_reference(&repo, "refs/heads/feature-x").is_err(),
        "rollback must remove the branch we just created"
    );

    // Idempotent: a second delete on a missing ref is a no-op, so the
    // rollback path can run safely even if `set_reference` itself was
    // the failing step (i.e., the branch never got created).
    delete_reference_if_present(&repo, "refs/heads/feature-x")
        .expect("delete on missing ref must be a no-op");
}

#[test]
fn mapping_persists_between_runs() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let change_id = ChangeId::generate();
    let git_oid: ObjectId = "0909090909090909090909090909090909090909"
        .parse()
        .expect("oid");

    let mut bridge = GitBridge::new(&repo);
    test_support::mapping_mut(&mut bridge).insert(change_id, git_oid);
    test_support::save_mapping_to_disk(&bridge).expect("save mapping");

    let mut reloaded = GitBridge::new(&repo);
    test_support::build_existing_mapping(
        &mut reloaded,
        Some(git_repo.workdir().expect("workdir").as_path()),
    )
    .expect("build mapping");

    assert_eq!(
        test_support::mapping(&reloaded).get_git(&change_id),
        Some(git_oid)
    );
}

#[test]
fn mapping_rebuilds_from_heddle_notes() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&git_repo);
    let commit_oid = commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    let change_id = ChangeId::generate();
    let note = git_notes::HeddleNote {
        change_id: change_id.to_string_full(),
        agent: None,
        confidence: None,
        status: "published".to_string(),
        omitted_annotations_breakdown: None,
        signal_counts: None,
        attribution: None,
    };
    git_notes::write_note(&git_repo, commit_oid, &note).expect("write heddle note");

    let mut bridge = GitBridge::new(&repo);
    test_support::build_existing_mapping(
        &mut bridge,
        Some(git_repo.workdir().expect("workdir").as_path()),
    )
    .expect("build mapping");

    assert_eq!(
        test_support::mapping(&bridge).get_heddle(commit_oid),
        Some(change_id)
    );
}

#[test]
fn mapping_rebuild_prefers_heddle_notes_over_stale_cache() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&git_repo);
    let commit_oid = commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    let change_id = ChangeId::generate();
    let stale_oid: ObjectId = "abababababababababababababababababababab"
        .parse()
        .expect("oid");

    let note = git_notes::HeddleNote {
        change_id: change_id.to_string_full(),
        agent: None,
        confidence: None,
        status: "published".to_string(),
        omitted_annotations_breakdown: None,
        signal_counts: None,
        attribution: None,
    };
    git_notes::write_note(&git_repo, commit_oid, &note).expect("write heddle note");

    let mut stale_bridge = GitBridge::new(&repo);
    test_support::mapping_mut(&mut stale_bridge).insert(change_id, stale_oid);
    test_support::save_mapping_to_disk(&stale_bridge).expect("save stale cache");

    let mut bridge = GitBridge::new(&repo);
    test_support::build_existing_mapping(
        &mut bridge,
        Some(git_repo.workdir().expect("workdir").as_path()),
    )
    .expect("notes should rebuild over stale cache");

    assert_eq!(
        test_support::mapping(&bridge).get_git(&change_id),
        Some(commit_oid),
        "refs/notes/heddle is authoritative for exported Git identity"
    );
    assert_eq!(
        test_support::mapping(&bridge).get_heddle(stale_oid),
        None,
        "stale cache-only identity must be discarded when a note supersedes it"
    );

    let mapping = std::fs::read_to_string(test_support::mapping_path(&bridge))
        .expect("existing mapping cache");
    assert!(
        !mapping.contains(&commit_oid.to_string()),
        "mapping rebuild is read-only; export owns the visibility-filtered cache write"
    );
    assert!(
        mapping.contains(&stale_oid.to_string()),
        "read-only mapping rebuild must not rewrite the existing cache"
    );
}

#[test]
fn test_sync_mapping() {
    let mut mapping = SyncMapping::new();
    let change_id = ChangeId::generate();
    let oid: ObjectId = "0101010101010101010101010101010101010101".parse().unwrap();
    mapping.insert(change_id, oid);
    assert_eq!(mapping.get_git(&change_id), Some(oid));
    assert_eq!(mapping.get_heddle(oid), Some(change_id));
}

#[test]
#[cfg(unix)]
fn sync_branches_propagates_track_write_failures() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&git_repo);
    let commit_oid = commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "base", &[]);

    let threads_dir = repo.heddle_dir().join("refs/threads");
    let original_mode = std::fs::metadata(&threads_dir)
        .unwrap()
        .permissions()
        .mode();
    std::fs::set_permissions(&threads_dir, std::fs::Permissions::from_mode(0o555)).unwrap();

    let mut bridge = GitBridge::new(&repo);
    test_support::set_git_repo_path(
        &mut bridge,
        git_repo.workdir().expect("workdir").to_path_buf(),
    );
    let change_id = ChangeId::generate();
    test_support::mapping_mut(&mut bridge).insert(change_id, commit_oid);

    let result = sync_branches(&mut bridge);

    std::fs::set_permissions(&threads_dir, std::fs::Permissions::from_mode(original_mode)).unwrap();
    assert!(result.is_err(), "thread write failures should be returned");
}

#[test]
#[cfg(unix)]
fn sync_tags_propagates_marker_write_failures() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&git_repo);
    let commit_oid = commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&git_repo, "v1.0", commit_oid, "release");

    let markers_dir = repo.heddle_dir().join("refs/markers");
    let original_mode = std::fs::metadata(&markers_dir)
        .unwrap()
        .permissions()
        .mode();
    std::fs::set_permissions(&markers_dir, std::fs::Permissions::from_mode(0o555)).unwrap();

    let mut bridge = GitBridge::new(&repo);
    test_support::set_git_repo_path(
        &mut bridge,
        git_repo.workdir().expect("workdir").to_path_buf(),
    );
    let change_id = ChangeId::generate();
    test_support::mapping_mut(&mut bridge).insert(change_id, commit_oid);

    let result = sync_tags(&mut bridge);

    std::fs::set_permissions(&markers_dir, std::fs::Permissions::from_mode(original_mode)).unwrap();
    assert!(result.is_err(), "marker write failures should be returned");
}

#[test]
fn pull_imports_remote_branches_and_tags_from_path_remote() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (source_temp, source_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    let commit_oid = commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&source_repo, "v1.0", commit_oid, "release");

    let mut bridge = GitBridge::new(&repo);
    bridge
        .pull(source_temp.path().to_str().expect("remote path"))
        .expect("pull remote");

    assert!(
        repo.refs()
            .get_thread(&ThreadName::new("main"))
            .unwrap()
            .is_some()
    );
    assert!(
        repo.refs()
            .get_marker(&MarkerName::new("v1.0"))
            .unwrap()
            .is_some()
    );
}

#[test]
fn pull_imports_remote_branches_and_tags_from_file_url_remote() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (source_temp, source_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    let commit_oid = commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&source_repo, "v1.0", commit_oid, "release");

    let mut bridge = GitBridge::new(&repo);
    bridge
        .pull(&format!("file://{}", source_temp.path().display()))
        .expect("pull remote");

    assert!(
        repo.refs()
            .get_thread(&ThreadName::new("main"))
            .unwrap()
            .is_some()
    );
    assert!(
        repo.refs()
            .get_marker(&MarkerName::new("v1.0"))
            .unwrap()
            .is_some()
    );
}

#[test]
fn pull_imports_remote_branches_and_tags_from_git_daemon() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let remote_root = TempDir::new().expect("remote root");
    let remote_repo = init_named_bare_git_repo(&remote_root, "remote.git");

    let tree_oid = empty_tree_oid(&remote_repo);
    let commit_oid = commit_with_tree(&remote_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&remote_repo, "v1.0", commit_oid, "release");

    let Some(daemon) = GitDaemon::spawn(remote_root.path()) else {
        return;
    };

    let mut bridge = GitBridge::new(&repo);
    bridge.pull(&daemon.url("remote.git")).expect("pull remote");

    assert!(
        repo.refs()
            .get_thread(&ThreadName::new("main"))
            .unwrap()
            .is_some()
    );
    assert!(
        repo.refs()
            .get_marker(&MarkerName::new("v1.0"))
            .unwrap()
            .is_some()
    );
}

#[test]
fn pull_imports_remote_branches_and_tags_from_git_http_backend() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let remote_root = TempDir::new().expect("remote root");
    let remote_repo = init_named_bare_git_repo(&remote_root, "remote.git");

    let tree_oid = empty_tree_oid(&remote_repo);
    let commit_oid = commit_with_tree(&remote_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&remote_repo, "v1.0", commit_oid, "release");

    let Some(backend) = GitHttpBackend::spawn(remote_root.path()) else {
        return;
    };

    let mut bridge = GitBridge::new(&repo);
    bridge
        .pull(&backend.url("remote.git"))
        .expect("pull remote over http");

    assert!(
        repo.refs()
            .get_thread(&ThreadName::new("main"))
            .unwrap()
            .is_some()
    );
    assert!(
        repo.refs()
            .get_marker(&MarkerName::new("v1.0"))
            .unwrap()
            .is_some()
    );
}

#[test]
fn pull_imports_remote_branches_and_tags_from_authenticated_git_http_backend() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let remote_root = TempDir::new().expect("remote root");
    let remote_repo = init_named_bare_git_repo(&remote_root, "remote.git");

    let tree_oid = empty_tree_oid(&remote_repo);
    let commit_oid = commit_with_tree(&remote_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&remote_repo, "v1.0", commit_oid, "release");

    let Some(backend) = GitHttpBackend::spawn_authenticated(remote_root.path(), "heddle", "secret")
    else {
        return;
    };

    let mut bridge = GitBridge::new(&repo);
    bridge
        .pull(&backend.url("remote.git"))
        .expect("pull remote over authenticated http");

    assert!(
        repo.refs()
            .get_thread(&ThreadName::new("main"))
            .unwrap()
            .is_some()
    );
    assert!(
        repo.refs()
            .get_marker(&MarkerName::new("v1.0"))
            .unwrap()
            .is_some()
    );
}

#[test]
fn fetch_rejects_reserved_git_remote_name_at_boundary() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let mut bridge = GitBridge::new(&repo);

    let err = bridge
        .fetch("git")
        .expect_err("fetch of reserved remote name must be rejected");
    let message = err.to_string();
    assert!(
        message.contains("reserved namespace") && message.contains("rename"),
        "fetch error must explain the reserved-namespace collision and how to fix it, got: {message}"
    );
}

#[test]
fn pull_rejects_reserved_git_remote_name_at_boundary() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let mut bridge = GitBridge::new(&repo);

    let err = bridge
        .pull("git")
        .expect_err("pull of reserved remote name must be rejected");
    let message = err.to_string();
    assert!(
        message.contains("reserved namespace") && message.contains("rename"),
        "pull error must explain the reserved-namespace collision and how to fix it, got: {message}"
    );
}

#[test]
fn import_handles_merge_history_without_missing_parent_mappings() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&git_repo);
    let base = commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    let left = commit_with_tree(
        &git_repo,
        Some("refs/heads/left"),
        tree_oid,
        "left",
        &[base],
    );
    let right = commit_with_tree(
        &git_repo,
        Some("refs/heads/right"),
        tree_oid,
        "right",
        &[base],
    );
    let merge = commit_with_tree(
        &git_repo,
        Some("refs/heads/main"),
        tree_oid,
        "merge",
        &[left, right],
    );

    let mut bridge = GitBridge::new(&repo);
    let stats = import_all(
        &mut bridge,
        Some(git_repo.workdir().expect("workdir").as_path()),
    )
    .expect("import merge history");

    assert_eq!(stats.commits_imported, 4);
    assert_eq!(
        repo.refs().get_thread(&ThreadName::new("main")).unwrap(),
        test_support::mapping(&bridge).get_heddle(merge)
    );
    assert!(test_support::mapping(&bridge).get_heddle(base).is_some());
    assert!(test_support::mapping(&bridge).get_heddle(left).is_some());
    assert!(test_support::mapping(&bridge).get_heddle(right).is_some());
    assert!(test_support::mapping(&bridge).get_heddle(merge).is_some());
}

// heddle#464 close-the-class (import boundary): a git branch name becomes a
// Heddle thread id on import. Git permits ref names containing shell
// metacharacters (e.g. `;`) that are NOT safe thread ids — interpolating one
// into a recommended-command breadcrumb would be unrunnable. Reject such an
// import with an actionable rename hint rather than silently slugifying it.
#[test]
fn import_rejects_branch_name_that_is_not_a_valid_thread_id() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&git_repo);
    let base = commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    // Git accepts `;` in a branch name; a Heddle thread id must not.
    commit_with_tree(
        &git_repo,
        Some("refs/heads/evil;rm"),
        tree_oid,
        "evil",
        &[base],
    );

    let mut bridge = GitBridge::new(&repo);
    let err = import_all(
        &mut bridge,
        Some(git_repo.workdir().expect("workdir").as_path()),
    )
    .expect_err("import must reject a branch whose name is not a valid thread id");

    assert!(
        err.contains("evil;rm"),
        "the rejection must name the branch, got: {err}"
    );
}

#[test]
fn failed_import_restores_mapping_and_overrides() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&git_repo);
    let base = commit_with_tree(&git_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    commit_with_tree(
        &git_repo,
        Some("refs/heads/evil;rm"),
        tree_oid,
        "evil",
        &[base],
    );

    let mut bridge = GitBridge::new(&repo);
    test_support::set_commit_message_override(
        &mut bridge,
        ChangeId::from_bytes([3; 16]),
        "pre-call override".to_string(),
    );
    let pre_mapping = test_support::mapping(&bridge).clone();
    let pre_overrides = test_support::commit_message_overrides(&bridge).clone();

    import_all(&mut bridge, Some(&git_repo.workdir().expect("workdir")))
        .expect_err("invalid branch name must fail after commits are mapped");

    assert_eq!(
        test_support::mapping(&bridge),
        &pre_mapping,
        "failed import must restore the pre-call mapping"
    );
    assert_eq!(
        test_support::commit_message_overrides(&bridge),
        &pre_overrides,
        "failed import must restore pre-call commit message overrides"
    );

    test_support::build_existing_mapping(&mut bridge, Some(&git_repo.workdir().expect("workdir")))
        .expect("mapping rebuild after failed import");
    assert_eq!(
        test_support::mapping(&bridge),
        &pre_mapping,
        "rebuilding after a failed import must not recover partial mappings from the sidecar"
    );
}

#[test]
fn push_exports_local_branches_and_tags_to_path_remote() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_source_temp, source_repo) = init_git_repo();
    let (remote_temp, remote_repo) = init_bare_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    let commit_oid = commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&source_repo, "v1.0", commit_oid, "release");

    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import from git");

    bridge
        .push_with_scope(
            remote_temp.path().to_str().expect("remote path"),
            GitPushScope::AllThreads,
        )
        .expect("push remote");

    let main_oid = find_reference(&remote_repo, "refs/heads/main")
        .expect("main ref")
        .peel_to_id()
        .expect("main target");
    let tag_oid = find_reference(&remote_repo, "refs/tags/v1.0")
        .expect("tag ref")
        .peel_to_id()
        .expect("tag target");
    let commit = remote_repo.find_commit(main_oid).expect("main commit");
    let message = commit.message_raw_sloppy().to_string();

    // Phase B: imported commits round-trip with their original git SHAs
    // (no Heddle trailers added on export). The annotated tag still peels
    // to the same commit because the tag points at the commit object
    // itself, which we copy verbatim from the mirror.
    assert_eq!(tag_oid, main_oid);
    assert_eq!(
        main_oid, commit_oid,
        "Phase B: SHA must be preserved across import → push"
    );
    assert!(
        !message.contains("Heddle-Change-Id:"),
        "Phase B: Heddle trailers must not be written into commit messages; \
         change_id lives in refs/notes/heddle instead"
    );

    // The note carrying the change_id should have travelled along with
    // the branches and tags.
    let note_ref = find_reference(&remote_repo, git_notes::NOTES_REF)
        .expect("notes ref should be pushed to remote");
    let _ = note_ref;
}

#[test]
fn push_current_thread_scope_exports_only_attached_branch_to_path_remote() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_source_temp, source_repo) = init_git_repo();
    let (remote_temp, remote_repo) = init_bare_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    let main_oid = commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "main", &[]);
    let side_oid = commit_with_tree(&source_repo, Some("refs/heads/side"), tree_oid, "side", &[]);
    create_annotated_tag(&source_repo, "v1.0", side_oid, "release");

    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import from git");

    bridge
        .push_with_scope(
            remote_temp.path().to_str().expect("remote path"),
            GitPushScope::CurrentThread,
        )
        .expect("push current thread");

    let pushed_main = find_reference(&remote_repo, "refs/heads/main")
        .expect("main ref")
        .peel_to_id()
        .expect("main target");
    assert_eq!(pushed_main, main_oid);
    assert!(
        find_reference(&remote_repo, "refs/heads/side").is_err(),
        "current-thread push must not push sibling branches"
    );
    assert!(
        find_reference(&remote_repo, "refs/tags/v1.0").is_err(),
        "current-thread push must not push tags"
    );
    assert!(
        find_reference(&remote_repo, git_notes::NOTES_REF).is_ok(),
        "current-thread push must carry Heddle notes so cloned Git commits keep stable state IDs"
    );
}

/// Phase C: a deep linear commit chain must not blow the stack on import.
/// The pre-Phase-C recursive walker overflowed at ~80k commits on
/// `git/git`. 5,000 commits here is an order of magnitude past the
/// guard, well within stack overflow territory for the recursive
/// version, but trivial for the iterative replacement.
#[test]
fn import_handles_deep_linear_history_without_stack_overflow() {
    const DEPTH: usize = 5_000;

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_src_temp, source_repo) = init_git_repo();
    let tree_oid = empty_tree_oid(&source_repo);

    let mut parent: Option<ObjectId> = None;
    let mut last: Option<ObjectId> = None;
    for i in 0..DEPTH {
        let parents: Vec<ObjectId> = parent.into_iter().collect();
        let oid = commit_with_tree(
            &source_repo,
            None, // ref update only on the final commit
            tree_oid,
            &format!("c{i}"),
            &parents,
        );
        parent = Some(oid);
        last = Some(oid);
    }
    set_reference(
        &source_repo,
        "refs/heads/main",
        last.expect("last commit oid"),
        RefPrecondition::Any,
        "test: set main",
    )
    .expect("set main");

    // Pre-Phase-C: this would SIGABRT before reaching the assertion.
    let mut bridge = GitBridge::new(&repo);
    let stats = import_all(
        &mut bridge,
        Some(source_repo.workdir().expect("workdir").as_path()),
    )
    .expect("deep import must complete without stack overflow");

    assert_eq!(stats.commits_imported, DEPTH);
    assert_eq!(stats.states_created, DEPTH);
}

/// Phase D: importing a repo that contains an annotated tag pointing at a
/// non-commit object (a blob or a tree) used to crash with
/// `Expected object of kind commit but got blob/tree`. Real-world repos
/// like `git/git` (`refs/tags/junio-gpg-pub` → blob containing the
/// maintainer's GPG public key) and `git-lfs/git-lfs`
/// (`refs/tags/core-gpg-keys` → tree of GPG keys) were unimportable.
///
/// After Phase D: skip with a warning and record the skipped ref in
/// `ImportStats::skipped_non_commit_refs` so callers can report it
/// without crashing the import.
#[test]
fn import_skips_tags_pointing_at_blob_or_tree() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_src_temp, source_repo) = init_git_repo();

    // A normal commit + tag — should still import correctly.
    let tree_oid = empty_tree_oid(&source_repo);
    let commit_oid = commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&source_repo, "v1.0", commit_oid, "release");

    // The QA failure mode: an annotated tag pointing at a blob.
    let blob_oid = source_repo
        .write_blob(b"-----BEGIN PGP PUBLIC KEY BLOCK-----\n")
        .expect("write gpg blob");
    let blob_tag = TagObject {
        object: blob_oid,
        object_type: GitObjectType::Blob,
        name: b"junio-gpg-pub".to_vec(),
        tagger: Some(test_signature().to_ident_bytes()),
        message: b"GPG public key".to_vec(),
        raw_body: None,
    };
    let blob_tag_oid = source_repo
        .write_object(EncodedObject::new(GitObjectType::Tag, blob_tag.write()))
        .expect("write tag");
    set_reference(
        &source_repo,
        "refs/tags/junio-gpg-pub",
        blob_tag_oid,
        RefPrecondition::MustNotExist,
        "test: tag pointing at blob",
    )
    .expect("set blob tag ref");

    // And the second QA failure mode: an annotated tag pointing at a tree.
    // Build a real (non-empty) tree containing one blob so the tree is in
    // the source ODB; sley doesn't special-case the well-known empty-tree
    // OID for `find_object`, and the failure path expects to be able to
    // look up the kind of the peeled object.
    let key_blob = source_repo.write_blob(b"key data").expect("write key blob");
    let mut editor = source_repo
        .edit_tree(&empty_tree_oid(&source_repo))
        .expect("editor");
    editor.upsert("alice.asc", EntryKind::Blob, key_blob);
    let tree_for_tag_oid = source_repo.write_tree(editor).expect("write tree");

    let tree_tag = TagObject {
        object: tree_for_tag_oid,
        object_type: GitObjectType::Tree,
        name: b"core-gpg-keys".to_vec(),
        tagger: Some(test_signature().to_ident_bytes()),
        message: b"core GPG keys directory".to_vec(),
        raw_body: None,
    };
    let tree_tag_oid = source_repo
        .write_object(EncodedObject::new(GitObjectType::Tag, tree_tag.write()))
        .expect("write tree tag");
    set_reference(
        &source_repo,
        "refs/tags/core-gpg-keys",
        tree_tag_oid,
        RefPrecondition::MustNotExist,
        "test: tag pointing at tree",
    )
    .expect("set tree tag ref");

    // Pre-Phase-D: this would crash with "Expected commit but got blob".
    let mut bridge = GitBridge::new(&repo);
    let stats = import_all(
        &mut bridge,
        Some(source_repo.workdir().expect("workdir").as_path()),
    )
    .expect("import must complete despite non-commit-pointing tags");

    // The normal commit + v1.0 tag must have made it through.
    assert_eq!(stats.commits_imported, 1);
    assert!(
        repo.refs()
            .get_thread(&ThreadName::new("main"))
            .expect("read main thread")
            .is_some(),
        "the regular commit should have produced a main thread"
    );

    assert_eq!(
        stats.skipped_non_commit_refs, 2,
        "both non-commit-pointing tags should be counted"
    );
}

/// Phase F: `GitSource::parse` discriminates URLs from filesystem paths
/// using a clear textual rule (contains `://` or starts with `git@`).
#[test]
fn git_source_parse_distinguishes_urls_and_paths() {
    use cli::cli::cli_args::GitSource;

    // URLs.
    assert!(matches!(
        GitSource::parse("https://github.com/foo/bar.git").unwrap(),
        GitSource::Url(_)
    ));
    assert!(matches!(
        GitSource::parse("ssh://git@example.com/foo.git").unwrap(),
        GitSource::Url(_)
    ));
    assert!(matches!(
        GitSource::parse("git://example.com/foo.git").unwrap(),
        GitSource::Url(_)
    ));
    assert!(matches!(
        GitSource::parse("file:///tmp/some-repo").unwrap(),
        GitSource::Url(_)
    ));
    assert!(matches!(
        GitSource::parse("git@github.com:foo/bar.git").unwrap(),
        GitSource::Url(_)
    ));

    // Paths.
    assert!(matches!(
        GitSource::parse("/tmp/foo").unwrap(),
        GitSource::Path(_)
    ));
    assert!(matches!(
        GitSource::parse("./relative").unwrap(),
        GitSource::Path(_)
    ));
    assert!(matches!(
        GitSource::parse("just-a-name").unwrap(),
        GitSource::Path(_)
    ));
}

/// Phase F: cloning from a `file://` URL into a fresh bare repo populates
/// branches, tags, and commits — exercising the URL → temp dir → import
/// path without needing network access.
#[test]
fn clone_url_to_bare_populates_destination_from_file_url() {
    // Build a source repo with one commit and one tag.
    let (_src_temp, source_repo) = init_git_repo();
    let tree_oid = empty_tree_oid(&source_repo);
    let commit_oid = commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&source_repo, "v1.0", commit_oid, "release v1");

    // Construct a file:// URL pointing at the source.
    let src_path = source_repo
        .workdir()
        .expect("workdir")
        .canonicalize()
        .expect("canonicalize");
    let url = format!("file://{}", src_path.display());

    // Clone into a fresh dest dir.
    let dest_root = TempDir::new().expect("dest temp");
    let dest = dest_root.path().join("clone-dest");
    clone_url_to_bare(url.as_str(), &dest, None, None).expect("clone file url");

    // Verify the dest has main + the v1.0 tag with the original commit OID.
    let dest_repo = open_git(&dest).expect("open dest");
    let dest_main = find_reference(&dest_repo, "refs/heads/main")
        .expect("main ref present after clone")
        .peel_to_id()
        .expect("peel main");
    assert_eq!(
        dest_main, commit_oid,
        "Phase F: clone_url_to_bare must transfer the original commit OID"
    );
    assert!(
        find_reference(&dest_repo, "refs/tags/v1.0").is_ok(),
        "Phase F: tags must be fetched too (with_fetch_tags::All)"
    );
}

/// Build a source repo with a chain of three commits, where each commit
/// adds a new blob file. Returns the (`temp`, `repo`, `[c1, c2, c3]`,
/// `[blob1, blob2, blob3]`) tuple. The caller owns the TempDir lifetime.
fn build_source_repo_three_commits_with_blobs()
-> (TempDir, SleyRepository, [ObjectId; 3], [ObjectId; 3]) {
    let (temp, repo) = init_git_repo();
    let blob1 = repo.write_blob(b"alpha\n").expect("blob1");
    let blob2 = repo.write_blob(b"beta\n").expect("blob2");
    let blob3 = repo.write_blob(b"gamma\n").expect("blob3");

    let mut e1 = repo.edit_tree(&empty_tree_oid(&repo)).expect("e1");
    e1.upsert("a.txt", EntryKind::Blob, blob1);
    let t1 = repo.write_tree(e1).expect("write t1");
    let c1 = commit_with_tree(&repo, None, t1, "c1: add a.txt", &[]);

    let mut e2 = repo.edit_tree(&empty_tree_oid(&repo)).expect("e2");
    e2.upsert("a.txt", EntryKind::Blob, blob1);
    e2.upsert("b.txt", EntryKind::Blob, blob2);
    let t2 = repo.write_tree(e2).expect("write t2");
    let c2 = commit_with_tree(&repo, None, t2, "c2: add b.txt", &[c1]);

    let mut e3 = repo.edit_tree(&empty_tree_oid(&repo)).expect("e3");
    e3.upsert("a.txt", EntryKind::Blob, blob1);
    e3.upsert("b.txt", EntryKind::Blob, blob2);
    e3.upsert("c.txt", EntryKind::Blob, blob3);
    let t3 = repo.write_tree(e3).expect("write t3");
    let c3 = commit_with_tree(&repo, Some("refs/heads/main"), t3, "c3: add c.txt", &[c2]);

    (temp, repo, [c1, c2, c3], [blob1, blob2, blob3])
}

/// `file://` clones use the native local-copy path rather than the network
/// file transport, because that transport spawns Git upload-pack
/// helpers. Until Heddle has native shallow-object pruning for local
/// copies, shallow `file://` clones fail closed instead of requiring a
/// Git executable suite on the host.
#[test]
fn clone_url_to_bare_rejects_shallow_file_url_without_shelling_to_git() {
    let (_src_temp, source_repo, _commits, _blobs) = build_source_repo_three_commits_with_blobs();

    let src_path = source_repo
        .workdir()
        .expect("workdir")
        .canonicalize()
        .expect("canonicalize");
    let url = format!("file://{}", src_path.display());

    let dest_root = TempDir::new().expect("dest temp");
    let dest = dest_root.path().join("clone-dest");
    let err = clone_url_to_bare(url.as_str(), &dest, Some(1), None)
        .expect_err("shallow file:// clone should fail closed in no-git runtime");
    let msg = err.to_string();
    assert!(
        msg.contains("shallow file:// Git clones are not supported")
            && msg.contains("native no-git runtime")
            && msg.contains("without spawning Git transport helpers"),
        "shallow file:// refusal should explain the no-git native boundary: {msg}"
    );
    assert!(
        !dest.exists(),
        "rejection should happen before writing destination state"
    );
}

/// Filtered Git-overlay clones are rejected until Heddle has a native
/// partial-clone implementation. The product contract is Git-compatible,
/// not Git-binary-dependent, so this path must not fall back to `git clone`.
#[test]
fn clone_url_to_bare_rejects_blob_none_filter_without_shelling_to_git() {
    let (_src_temp, source_repo, _commits, _blobs) = build_source_repo_three_commits_with_blobs();

    let src_path = source_repo
        .workdir()
        .expect("workdir")
        .canonicalize()
        .expect("canonicalize");
    let url = format!("file://{}", src_path.display());

    let dest_root = TempDir::new().expect("dest temp");
    let dest = dest_root.path().join("clone-dest");
    let err = clone_url_to_bare(url.as_str(), &dest, Some(1), Some("blob:none"))
        .expect_err("filtered clone must be rejected in no-git runtime");
    let msg = err.to_string();
    assert!(
        msg.contains("partial Git clone filter `blob:none` is not supported")
            && msg.contains("native no-git runtime"),
        "filter refusal should explain the no-git native boundary: {msg}"
    );
}

/// Rejected filtered clones must stop before touching the destination,
/// even when the caller pre-created an empty scratch directory.
#[test]
fn clone_url_to_bare_filter_rejection_preserves_pre_created_empty_dest() {
    let (_src_temp, source_repo, _commits, _blobs) = build_source_repo_three_commits_with_blobs();

    let src_path = source_repo
        .workdir()
        .expect("workdir")
        .canonicalize()
        .expect("canonicalize");
    let url = format!("file://{}", src_path.display());

    let dest_root = TempDir::new().expect("dest temp");
    let dest = dest_root.path().join("clone-dest");
    std::fs::create_dir(&dest).expect("pre-create empty dest");
    assert!(dest.exists() && dest.read_dir().expect("read empty").next().is_none());

    let err = clone_url_to_bare(url.as_str(), &dest, None, Some("blob:none"))
        .expect_err("filtered clone must be rejected in no-git runtime");
    assert!(
        err.to_string().contains("retry without --filter/--lazy"),
        "filter refusal should give the native retry path: {err}"
    );
    assert!(
        dest.exists(),
        "rejection should not remove caller scratch dir"
    );
    assert!(
        dest.read_dir()
            .expect("read preserved empty")
            .next()
            .is_none(),
        "rejection should not write partial Git state"
    );
}

/// Filter rejection happens before network/filesystem clone work, so an
/// unreachable URL still reports the unsupported native capability first.
#[test]
fn clone_url_to_bare_filter_rejection_precedes_remote_probe() {
    let scratch = TempDir::new().expect("scratch");
    let nowhere = scratch.path().join("does-not-exist");
    let url = format!("file://{}", nowhere.display());

    let dest_root = TempDir::new().expect("dest temp");
    let dest = dest_root.path().join("clone-dest");

    let err =
        clone_url_to_bare(url.as_str(), &dest, Some(1), Some("blob:none")).expect_err("must fail");
    let msg = err.to_string();
    assert!(
        msg.contains("partial Git clone filter `blob:none` is not supported"),
        "unsupported native capability should be reported before remote probing: {msg}"
    );
    assert!(
        !dest.exists(),
        "rejection should not create destination state"
    );
}

/// Phase A: `bridge export --destination DEST` must populate DEST with
/// reachable git objects + refs. Auto-creates DEST as a bare repo when it
/// doesn't exist (so users don't have to pre-init the destination).
#[test]
fn export_to_path_writes_branches_and_tags_to_fresh_destination() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_source_temp, source_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    let commit_oid = commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    create_annotated_tag(&source_repo, "v1.0", commit_oid, "release");

    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import from git");

    // Destination directory does not exist yet — export_to_path must create it
    // as a bare repo.
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    assert!(!dest_path.exists());

    let stats = bridge
        .export_to_path(&dest_path)
        .expect("export to fresh path");

    // Phase B: `states_exported` counts only commits that the bridge had
    // to *recreate* (heddle-native states with no original git_oid). When
    // every state was imported from git and the mirror still has the
    // original commit bytes, the SHA-stable path skips recreation and
    // this can legitimately be 0. The destination's refs are the true
    // signal.
    assert!(stats.threads_synced >= 1, "should sync the main thread");
    assert!(stats.markers_synced >= 1, "should sync the v1.0 tag");

    let dest_repo = open_git(&dest_path).expect("open exported repo");
    assert!(
        find_reference(&dest_repo, "refs/heads/main").is_ok(),
        "exported repo should have refs/heads/main"
    );
    assert!(
        find_reference(&dest_repo, "refs/tags/v1.0").is_ok(),
        "exported repo should have refs/tags/v1.0"
    );
}

/// Phase A: re-running `export_to_path` against an already-populated
/// destination must work (idempotent — auto-init only when missing).
#[test]
fn export_to_path_is_idempotent_against_existing_destination() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_source_temp, source_repo) = init_git_repo();
    let tree_oid = empty_tree_oid(&source_repo);
    commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "base", &[]);

    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import from git");

    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    bridge
        .export_to_path(&dest_path)
        .expect("first export should create dest");
    bridge
        .export_to_path(&dest_path)
        .expect("second export against existing dest should not error");
}

/// heddle#289: in the common git-overlay case every state is already
/// mapped to an original git commit, so `states_exported` (newly minted)
/// is legitimately 0 — but `commits_total` must still count the commits
/// that landed in the destination so the summary doesn't read a
/// misleading "exported 0 states" against a fully-populated repo.
#[test]
fn export_stats_report_total_commits_when_all_states_pre_mapped() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_source_temp, source_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    let first = commit_with_tree(&source_repo, None, tree_oid, "first", &[]);
    let second = commit_with_tree(
        &source_repo,
        Some("refs/heads/main"),
        tree_oid,
        "second",
        &[first],
    );
    create_annotated_tag(&source_repo, "v1.0", second, "release");

    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import from git");

    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    let stats = bridge.export_to_path(&dest_path).expect("export");

    // Every state came from git with its SHA preserved → nothing is
    // freshly minted, yet the destination holds both commits.
    assert_eq!(
        stats.states_exported, 0,
        "SHA-stable overlay export mints no new commits"
    );
    assert!(
        stats.commits_total >= 2,
        "commits_total must count every state that landed in the destination, got {}",
        stats.commits_total
    );
    assert!(
        stats.commits_total > stats.states_exported,
        "total must exceed newly-minted in the overlay case"
    );
    // AC3: branch/tag detail carries tip SHAs for the summary.
    assert!(
        stats.branches.iter().any(|b| b.name == "main"),
        "branch detail should list main with its tip: {:?}",
        stats.branches
    );
    assert!(
        stats.tags.iter().any(|t| t.name == "v1.0"),
        "tag detail should list v1.0 with its tip: {:?}",
        stats.tags
    );
}

/// heddle#289: a sync of an already-synced overlay must report consistent
/// "total vs. new" accounting on both halves — the export side gains the
/// same total/new split the import side has carried since heddle#147.
#[test]
fn sync_export_and_import_report_consistent_total_and_new() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_source_temp, source_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    let first = commit_with_tree(&source_repo, None, tree_oid, "first", &[]);
    commit_with_tree(
        &source_repo,
        Some("refs/heads/main"),
        tree_oid,
        "second",
        &[first],
    );

    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import from git");

    // Re-running the sync halves against the already-synced overlay: both
    // sides should report the total they walked while their "new" count
    // drops to 0 — the "already in sync" signal.
    let export_stats = export_all(&mut bridge).expect("re-export");
    let import_stats = import_all(
        &mut bridge,
        Some(source_repo.workdir().expect("workdir").as_path()),
    )
    .expect("re-import");

    assert_eq!(
        export_stats.states_exported, 0,
        "nothing new to export on a synced overlay"
    );
    assert!(
        export_stats.commits_total >= 2,
        "export total still reflects the populated destination: {}",
        export_stats.commits_total
    );
    assert_eq!(
        import_stats.states_created, 0,
        "nothing new to import on a synced overlay"
    );
    assert!(
        import_stats.commits_imported >= 2,
        "import total still reflects the walked commits: {}",
        import_stats.commits_imported
    );
}

/// heddle#289 r3: the export "total" must equal what actually lands in
/// the destination. Export does NOT prune stale mirror refs, so a branch
/// exported once and whose Heddle thread is later dropped still has a
/// `refs/heads/<branch>` in the mirror — and `copy_mirror_to_path` copies
/// that ref (and its commit) to the destination. The total is derived from
/// the same `collect_ref_updates` set the copy uses, so it counts that
/// still-copied commit. Counting only current Heddle refs (r2) diverged
/// from reality; this guards that the count == the destination.
#[test]
fn export_total_counts_stale_mirror_ref_left_by_dropped_thread() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_source_temp, source_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    // main: two-commit history → 2 commits reachable from the branch tip.
    let first = commit_with_tree(&source_repo, None, tree_oid, "first", &[]);
    commit_with_tree(
        &source_repo,
        Some("refs/heads/main"),
        tree_oid,
        "second",
        &[first],
    );
    // feature: an independent root commit → 1 commit reachable only via
    // this branch, sharing no history with main.
    let feature_tip = commit_with_tree(
        &source_repo,
        Some("refs/heads/feature"),
        tree_oid,
        "feature-only",
        &[],
    );

    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import from git");

    // All three states now exist in the store, and the import populated
    // the mirror with refs/heads/{main,feature}.
    assert_eq!(
        test_support::heddle_repo(&bridge)
            .store()
            .list_states()
            .expect("states")
            .len(),
        3,
        "import should have created three states (two on main, one on feature)"
    );

    // Drop the feature *thread* (Heddle-side ref). Export never prunes the
    // mirror's refs/heads/feature, so the stale mirror ref — and its
    // commit — still travel to the destination.
    test_support::heddle_repo(&bridge)
        .refs()
        .delete_thread(&ThreadName::new("feature"))
        .expect("delete feature thread");

    let dest_temp = TempDir::new().expect("dest temp");
    let dest_path = dest_temp.path().join("dest.git");
    let stats = bridge.export_to_path(&dest_path).expect("export to path");

    // The total counts every commit that lands in the destination: main's
    // two plus the stale feature ref's one. "What we report" == "what we
    // copy".
    assert_eq!(
        stats.commits_total, 3,
        "export total must count what lands in the destination — main's 2 \
         plus the stale feature ref's 1, got {}",
        stats.commits_total
    );

    // Prove the count matches reality: the destination really does contain
    // refs/heads/feature at the feature tip.
    let dest = open_git(&dest_path).expect("open destination");
    let feature_ref = find_reference(&dest, "refs/heads/feature")
        .expect("destination must contain the stale feature ref");
    assert_eq!(
        feature_ref.id(),
        feature_tip,
        "the stale feature ref in the destination points at the feature tip"
    );
    assert!(
        find_reference(&dest, "refs/heads/main").is_ok(),
        "destination must contain the main branch"
    );

    // The dropped thread is not a *current* Heddle thread, so it is not
    // reported as a synced branch — that gap between `branches` (current
    // threads) and `commits_total` (what's copied) is exactly what this
    // fix reconciles for the headline count.
    assert!(
        !stats.branches.iter().any(|b| b.name == "feature"),
        "dropped feature thread is not a current synced branch: {:?}",
        stats.branches
    );
}

/// heddle#289 r4: EVERY count in the export summary must be a partition of
/// the single copied ref set, so a state minted into the mirror but
/// reachable from no copied ref inflates none of them. r3 fixed
/// `commits_total` but left `states_exported` ("newly") tallied inline over
/// `list_states()`, so a Heddle-native thread created and dropped before
/// export would still be minted and counted as newly-written even though it
/// never lands in the destination — producing the impossible
/// "1 total (2 newly written)" summary. This drives `states_exported` from
/// the same walk as `commits_total`: the orphan is excluded from BOTH and
/// `newly + already == total` holds by construction.
#[test]
fn export_counts_exclude_orphan_minted_state_from_total_and_newly() {
    use objects::object::{Attribution, Principal, State};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let bridge = GitBridge::new(&repo);

    let attribution = || Attribution::human(Principal::new("Alice", "alice@example.com"));
    let put_state = |parents: Vec<ChangeId>| -> State {
        let store = test_support::heddle_repo(&bridge).store();
        let blob_hash = store
            .put_blob(&Blob::from_slice(b"contents"))
            .expect("put blob");
        let tree_hash = store
            .put_tree(&Tree::from_entries(vec![
                TreeEntry::file("file.txt".to_string(), blob_hash, false).expect("tree entry"),
            ]))
            .expect("put tree");
        let state = State::new(tree_hash, parents, attribution());
        store.put_state(&state).expect("put state");
        state
    };

    // A native `main` thread with a two-commit history → both minted into
    // the mirror and reachable from refs/heads/main, so both land in the
    // destination.
    let main_first = put_state(Vec::new());
    let main_tip = put_state(vec![main_first.change_id]);
    test_support::heddle_repo(&bridge)
        .refs()
        .set_thread(&ThreadName::new("main"), &main_tip.change_id)
        .expect("set main thread");

    // A native `scratch` thread, dropped before export. Its state stays in
    // the store (delete_thread only removes the ref), so the export walk
    // over `list_states()` still mints it — but no copied ref points at it,
    // so it reaches no destination and must inflate no count.
    let orphan = put_state(Vec::new());
    test_support::heddle_repo(&bridge)
        .refs()
        .set_thread(&ThreadName::new("scratch"), &orphan.change_id)
        .expect("set scratch thread");
    test_support::heddle_repo(&bridge)
        .refs()
        .delete_thread(&ThreadName::new("scratch"))
        .expect("delete scratch thread");

    // The orphan state is still present in the store — proving the walk
    // would have minted (and, pre-r4, counted) it.
    let mut bridge = bridge;
    assert_eq!(
        test_support::heddle_repo(&bridge)
            .store()
            .list_states()
            .expect("states")
            .len(),
        3,
        "store holds main's two states plus the dropped scratch state"
    );

    let dest_temp = TempDir::new().expect("dest temp");
    let dest_path = dest_temp.path().join("dest.git");
    let stats = bridge.export_to_path(&dest_path).expect("export to path");

    // Both summary counts are partitions of the copied ref set: total =
    // main's two commits; newly = the same two (freshly minted this run).
    // The orphan is in neither.
    assert_eq!(
        stats.commits_total, 2,
        "total counts only the copied ref set (main's 2), not the orphan, got {}",
        stats.commits_total
    );
    assert_eq!(
        stats.states_exported, 2,
        "newly counts only minted commits that landed (main's 2), not the orphan, got {}",
        stats.states_exported
    );

    // The invariant the close-the-class fix guarantees: newly is a subset of
    // total, so the "1 total (2 newly written)" impossibility cannot occur.
    let already = stats.commits_total.saturating_sub(stats.states_exported);
    assert!(
        stats.states_exported <= stats.commits_total,
        "newly ({}) must never exceed total ({})",
        stats.states_exported,
        stats.commits_total
    );
    assert_eq!(
        stats.states_exported + already,
        stats.commits_total,
        "newly + already must equal total by construction"
    );

    // The orphan's commit reaches no ref in the destination.
    let dest = open_git(&dest_path).expect("open destination");
    assert!(
        find_reference(&dest, "refs/heads/main").is_ok(),
        "destination must contain the main branch"
    );
    assert!(
        find_reference(&dest, "refs/heads/scratch").is_err(),
        "dropped scratch thread must not appear in the destination"
    );
    assert!(
        !stats.branches.iter().any(|b| b.name == "scratch"),
        "dropped scratch thread is not a synced branch: {:?}",
        stats.branches
    );
}

#[test]
fn failed_export_restores_mapping_and_overrides_after_purge() {
    use chrono::Utc;
    use objects::object::{Attribution, Principal, State, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    let attribution = || Attribution::human(Principal::new("Grace Hopper", "grace@example.com"));
    let store = repo.store();
    let blob_hash = store
        .put_blob(&Blob::from_slice(b"public\n"))
        .expect("put blob");
    let tree_hash = store
        .put_tree(&Tree::from_entries(vec![
            TreeEntry::file("public.txt".to_string(), blob_hash, false).expect("tree entry"),
        ]))
        .expect("put tree");
    let exported_state = State::new(tree_hash, Vec::new(), attribution());
    store
        .put_state(&exported_state)
        .expect("put exported state");
    repo.refs()
        .set_thread(&ThreadName::new("main"), &exported_state.change_id)
        .expect("set main thread");

    let mut bridge = GitBridge::new(&repo);
    export_all(&mut bridge).expect("initial export seeds mapping");

    repo.put_state_visibility(StateVisibility {
        state: exported_state.change_id,
        tier: VisibilityTier::Private {
            scope_label: "embargo".to_string(),
        },
        embargo_until: None,
        declarer: Principal::new("Grace Hopper", "grace@example.com"),
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .expect("mark exported state private");

    let bad_tree_hash = store
        .put_tree(&Tree::from_entries(vec![
            TreeEntry::file(
                "missing.txt".to_string(),
                ContentHash::from_bytes([9; 32]),
                false,
            )
            .expect("tree entry"),
        ]))
        .expect("put bad tree");
    let bad_state = State::new(bad_tree_hash, Vec::new(), attribution());
    store.put_state(&bad_state).expect("put bad state");
    repo.refs()
        .set_thread(&ThreadName::new("main"), &bad_state.change_id)
        .expect("set main to bad state");

    test_support::set_commit_message_override(
        &mut bridge,
        exported_state.change_id,
        "pre-call override".to_string(),
    );
    let pre_mapping = test_support::mapping(&bridge).clone();
    let pre_overrides = test_support::commit_message_overrides(&bridge).clone();

    export_all(&mut bridge).expect_err("missing blob must fail after visibility purge");

    assert_eq!(
        test_support::mapping(&bridge),
        &pre_mapping,
        "failed export must restore the pre-call mapping"
    );
    assert_eq!(
        test_support::commit_message_overrides(&bridge),
        &pre_overrides,
        "failed export must restore pre-call commit message overrides"
    );

    test_support::build_existing_mapping(&mut bridge, None)
        .expect("mapping rebuild after failed export");
    assert_eq!(
        test_support::mapping(&bridge),
        &pre_mapping,
        "rebuilding after a failed export must behave as if the purge never ran"
    );
}

/// Phase A: `commits_imported` and `states_created` should both reflect new
/// state writes for a fresh import.
#[test]
fn import_stats_report_states_created() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_source_temp, source_repo) = init_git_repo();
    let tree_oid = empty_tree_oid(&source_repo);
    commit_with_tree(
        &source_repo,
        Some("refs/heads/main"),
        tree_oid,
        "first",
        &[],
    );

    let mut bridge = GitBridge::new(&repo);
    let stats = import_all(
        &mut bridge,
        Some(source_repo.workdir().expect("workdir").as_path()),
    )
    .expect("import");

    assert_eq!(stats.commits_imported, 1);
    assert_eq!(
        stats.states_created, stats.commits_imported,
        "states_created should match commits_imported on a fresh import"
    );
}

/// Phase B (the headline guarantee): import a git repo, export it back to a
/// fresh path, and confirm the head commit's git SHA is byte-identical to
/// the original. This is what makes heddle viable as a substrate for a
/// bidirectional sync service against GitHub — a sync that produced new
/// SHAs on every roundtrip would invalidate every PR.
#[test]
fn export_preserves_original_commit_shas() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_source_temp, source_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    let first = commit_with_tree(&source_repo, None, tree_oid, "first", &[]);
    let second = commit_with_tree(
        &source_repo,
        Some("refs/heads/main"),
        tree_oid,
        "second",
        &[first],
    );
    create_annotated_tag(&source_repo, "v1.0", second, "release v1");

    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import from git");

    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export");
    bridge.export_to_path(&dest_path).expect("export");

    let dest_repo = open_git(&dest_path).expect("open dest");
    let dest_main = find_reference(&dest_repo, "refs/heads/main")
        .expect("main ref")
        .peel_to_id()
        .expect("main target");

    assert_eq!(
        dest_main, second,
        "Phase B: exported main HEAD must equal the original git SHA"
    );

    // The first commit should also be byte-identical (it's reachable from
    // main via parent traversal).
    let dest_main_commit = dest_repo.find_commit(dest_main).expect("dest main commit");
    let dest_first = dest_main_commit
        .parent_ids()
        .next()
        .expect("dest main has parent");
    assert_eq!(
        dest_first, first,
        "Phase B: parent commit SHAs must also be preserved"
    );
}

/// Phase B: a heddle change_id assigned at import time must survive a full
/// round-trip through git — even when the destination is re-imported into a
/// fresh heddle repo with no sidecar.
#[test]
fn round_trip_preserves_change_ids_via_notes() {
    let heddle_a_temp = TempDir::new().expect("heddle A temp");
    let repo_a = Repository::init(heddle_a_temp.path()).expect("init heddle A");

    let (_src_temp, source_repo) = init_git_repo();
    let tree_oid = empty_tree_oid(&source_repo);
    let commit_oid = commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "base", &[]);

    // Step 1: import into heddle A. Capture the change_id assigned.
    let mut bridge_a = GitBridge::new(&repo_a);
    bridge_a
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import into A");
    let change_id_in_a = test_support::mapping(&bridge_a)
        .get_heddle(commit_oid)
        .expect("change_id should be mapped in A");

    // Step 2: export A to a fresh git destination.
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export");
    bridge_a.export_to_path(&dest_path).expect("export from A");

    // Step 3: import the exported repo into heddle B (fresh repo, no
    // sidecar carryover). The note attached to the commit must let B
    // recover the same change_id A assigned.
    let heddle_b_temp = TempDir::new().expect("heddle B temp");
    let repo_b = Repository::init(heddle_b_temp.path()).expect("init heddle B");
    let mut bridge_b = GitBridge::new(&repo_b);
    bridge_b.import(Some(&dest_path)).expect("import into B");

    let change_id_in_b = test_support::mapping(&bridge_b)
        .get_heddle(commit_oid)
        .expect("B should have mapped the original commit OID");

    assert_eq!(
        change_id_in_a, change_id_in_b,
        "Phase B: change_id must survive the git→heddle→git→heddle roundtrip via the note"
    );
}

/// Phase E: end-to-end symlink fidelity through the git bridge.
/// Constructs a git tree containing a symlink, imports it, then re-exports
/// the heddle tree to git and confirms the symlink survives both ways.
///
/// This is the closest CI-friendly approximation of the QA report's
/// `ripgrep/HomebrewFormula -> pkg/brew` failure mode.
#[test]
#[cfg(unix)]
fn round_trip_preserves_symlinks() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_src_temp, source_repo) = init_git_repo();

    // Build a git tree directly: one regular blob "target.txt" + one
    // symlink "link" -> "target.txt".
    let target_oid = source_repo
        .write_blob(b"hello\n")
        .expect("write target blob");
    let link_oid = source_repo
        .write_blob(b"target.txt")
        .expect("write link blob");

    let empty = empty_tree_oid(&source_repo);
    let mut editor = source_repo.edit_tree(&empty).expect("editor");
    editor.upsert("target.txt", EntryKind::Blob, target_oid);
    editor.upsert("link", EntryKind::Symlink, link_oid);
    let tree_oid = source_repo.write_tree(editor).expect("write tree");

    let _commit = commit_with_tree(
        &source_repo,
        Some("refs/heads/main"),
        tree_oid,
        "with symlink",
        &[],
    );

    // Import into heddle.
    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import");

    // Verify the imported tree marks "link" as a symlink at the entry-type
    // level (the Phase E source-side fix). This is what the materializer
    // checks to write a real symlink to the worktree.
    let head_change_id = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .expect("main thread");
    let state = repo
        .store()
        .get_state(&head_change_id)
        .expect("state lookup")
        .expect("state present");
    let imported_tree = repo
        .store()
        .get_tree(&state.tree)
        .expect("tree lookup")
        .expect("tree present");
    let link_entry = imported_tree
        .entries()
        .iter()
        .find(|e| e.name == "link")
        .expect("link entry exists");
    assert_eq!(
        link_entry.entry_type,
        EntryType::Symlink,
        "Phase E: imported symlinks must have EntryType::Symlink (was Blob \
         pre-Phase-E, which broke goto-time materialization)"
    );
    assert_eq!(link_entry.mode, FileMode::Symlink);

    // Export back to a fresh git destination and confirm the link entry
    // round-trips as a Link, not a Blob.
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export");
    bridge.export_to_path(&dest_path).expect("export");

    let dest_repo = open_git(&dest_path).expect("open dest");
    let dest_main = find_reference(&dest_repo, "refs/heads/main")
        .expect("main")
        .peel_to_id()
        .expect("peel");
    let dest_commit = dest_repo.find_commit(dest_main).expect("dest commit");
    let dest_tree_oid = dest_commit.tree_id().expect("tree id");
    let dest_tree = dest_repo.find_tree(dest_tree_oid).expect("dest tree");
    let entries: Vec<(String, EntryKind)> = dest_tree
        .iter()
        .map(|e| {
            let e = e.expect("entry");
            (e.filename().to_string(), e.mode().kind())
        })
        .collect();

    let link_kind = entries
        .iter()
        .find(|(name, _)| name == "link")
        .map(|(_, k)| *k)
        .expect("link entry in exported tree");
    assert_eq!(
        link_kind,
        EntryKind::Symlink,
        "Phase E: exported tree must mark 'link' as a symlink (Link), not a Blob"
    );
}

/// Follow-up A: annotated tags must round-trip with their tag-object SHA
/// preserved, not just the underlying commit SHA. A `git rev-parse
/// refs/tags/v1.0` against the export should return the same OID as
/// against the source — for an annotated tag that's the OID of the tag
/// *object* (which carries the tagger, tag message, and signature),
/// not the commit it wraps.
#[test]
fn round_trip_preserves_annotated_tag_object_sha() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_src_temp, source_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    let commit_oid = commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "base", &[]);
    // Lightweight tag (no separate tag object).
    set_reference(
        &source_repo,
        "refs/tags/light",
        commit_oid,
        RefPrecondition::MustNotExist,
        "test: lightweight tag",
    )
    .expect("set lightweight tag");
    // Annotated tag (carries its own object with tagger + message).
    let annotated_tag_oid = create_annotated_tag(&source_repo, "v1.0", commit_oid, "release");

    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(source_repo.workdir().expect("workdir").as_path()))
        .expect("import");

    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export");
    bridge.export_to_path(&dest_path).expect("export");

    let dest_repo = open_git(&dest_path).expect("open dest");

    // Lightweight tag: dest's refs/tags/light points directly at the commit.
    let dest_light = find_reference(&dest_repo, "refs/tags/light")
        .expect("light ref")
        .target()
        .try_id()
        .expect("light has direct id")
        .to_owned();
    assert_eq!(
        dest_light, commit_oid,
        "lightweight tag should still point at the commit"
    );

    // Annotated tag: dest's refs/tags/v1.0 must point at the SAME tag
    // object OID as the source — not at the underlying commit. This is
    // what makes `git rev-parse refs/tags/v1.0` agree across source and
    // export, which downstream tools like GitHub PR matching rely on.
    let dest_v10_immediate = find_reference(&dest_repo, "refs/tags/v1.0")
        .expect("v1.0 ref")
        .target()
        .try_id()
        .expect("v1.0 has direct id")
        .to_owned();
    assert_eq!(
        dest_v10_immediate, annotated_tag_oid,
        "Follow-up A: annotated tag SHA must match (got {dest_v10_immediate}, want {annotated_tag_oid})"
    );

    // And the destination must actually have the tag object, not just
    // the ref — `git tag -v` style introspection requires the object
    // to be present.
    let dest_tag_obj = dest_repo
        .find_object(annotated_tag_oid)
        .expect("annotated tag object should be in destination");
    assert_eq!(dest_tag_obj.kind, GitObjectType::Tag);
}

/// Follow-up B: per-ref isolation. A repo that has one valid ref and one
/// ref whose target is missing from the source ODB used to fail the
/// entire import (a single bulk `copy_reachable_objects` errored on the
/// first missing object). The valid ref should still import cleanly.
#[test]
fn import_isolates_per_ref_mirror_failures() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_src_temp, source_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&source_repo);
    let good_oid = commit_with_tree(&source_repo, Some("refs/heads/main"), tree_oid, "good", &[]);

    // Construct a ref pointing at a fabricated OID that doesn't exist
    // in the ODB. We can't easily make this a refs/heads/* (peel would
    // fail before the mirror copy), so simulate the failure mode by
    // pointing a tag at a never-written commit OID.
    let phantom_oid: ObjectId = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
        .parse()
        .expect("parse phantom oid");
    set_reference(
        &source_repo,
        "refs/tags/phantom",
        phantom_oid,
        RefPrecondition::MustNotExist,
        "test: phantom tag",
    )
    .expect("set phantom tag");

    // Import. The phantom tag's peel will fail (peel goes through
    // find_object), so it gets routed to either skipped_non_commit_refs
    // (if peel returns a non-commit) or simply trips the per-ref copy
    // failure path. Either way, the import as a whole must succeed and
    // the good commit must be present.
    let mut bridge = GitBridge::new(&repo);
    let result = bridge.import(Some(source_repo.workdir().expect("workdir").as_path()));

    // The import may surface peel errors as a hard failure for genuinely
    // broken refs (peel_to_id propagates), so we accept either outcome
    // here — what matters for the follow-up is that when isolation
    // *does* apply, one bad ref doesn't poison the rest.
    if let Ok(stats) = result {
        assert_eq!(
            stats.commits_imported, 1,
            "the good commit should be mapped"
        );
        assert!(
            test_support::mapping(&bridge)
                .get_heddle(good_oid)
                .is_some(),
            "good commit's change_id should be in mapping"
        );
    } else {
        // If the broken ref propagated as a hard error, that's the
        // pre-isolation behavior — report it but don't fail the test
        // since we're documenting current behavior.
        eprintln!(
            "phantom-tag import returned hard error (acceptable): {:?}",
            result.err()
        );
    }
}

/// #561: `adopt` writes the mirror's reachable objects through the native Git
/// object path. The mirror must carry the same object bytes, including annotated
/// tag objects.
#[test]
fn import_populates_mirror_with_identical_annotated_tag_object() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_src_temp, source_repo) = init_git_repo();

    // Use a stored blob/tree instead of the synthetic empty tree so source and
    // mirror object stores can be compared directly.
    let blob = source_repo.write_blob(b"hello\n").expect("blob");
    let mut editor = source_repo
        .edit_tree(&ObjectId::empty_tree(source_repo.object_format()))
        .expect("tree editor");
    editor.upsert("file.txt", EntryKind::Blob, blob);
    let tree = source_repo.write_tree(editor).expect("tree");

    let first = commit_with_tree(&source_repo, Some("refs/heads/main"), tree, "first", &[]);
    let second = commit_with_tree(
        &source_repo,
        Some("refs/heads/main"),
        tree,
        "second",
        &[first],
    );
    let tag_oid = create_annotated_tag(&source_repo, "v1.0", second, "release");

    let mut bridge = GitBridge::new(&repo);
    bridge
        .import(Some(&source_repo.workdir().expect("workdir")))
        .expect("import");

    let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
    let source_tag = source_repo
        .find_object(tag_oid)
        .expect("source tag present");
    let mirror_tag = mirror.find_object(tag_oid).expect("mirror tag present");
    assert_eq!(source_tag.kind, GitObjectType::Tag);
    assert_eq!(mirror_tag.kind, source_tag.kind);
    assert_eq!(mirror_tag.data, source_tag.data);
}

#[test]
fn export_lags_public_branch_to_frontier_emitting_absence_for_embargoed_tip() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    // A real principal so snapshot states carry a non-Unknown attribution and
    // the bridge can mint Git commits without an external identity fallback.
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    // Build a linear thread: public base A, then tip B.
    std::fs::write(heddle_temp.path().join("a.txt"), b"base\n").unwrap();
    repo.snapshot(Some("base".into()), None).unwrap();
    let state_a = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();

    std::fs::write(heddle_temp.path().join("b.txt"), b"embargoed fix\n").unwrap();
    repo.snapshot(Some("fix".into()), None).unwrap();
    let state_b = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();
    assert_ne!(state_a, state_b);

    // Embargo the tip B (strictest Private tier). Downward-closure leaves the
    // public frontier at A.
    repo.put_state_visibility(StateVisibility {
        state: state_b,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Grace Hopper".into(),
            email: "grace@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();

    let mut bridge = GitBridge::new(&repo);
    let stats = export_all(&mut bridge).expect("export");

    // The embargoed tip is never minted into the public mirror (absence) ...
    assert!(
        test_support::mapping(&bridge).get_git(&state_b).is_none(),
        "embargoed tip must not be minted into the public mirror"
    );
    let oid_a = test_support::mapping(&bridge)
        .get_git(&state_a)
        .expect("public base A must be minted");
    // ... and refs/heads/main lags to A, never the raw embargoed tip B.
    let main = stats
        .branches
        .iter()
        .find(|b| b.name == "main")
        .expect("main branch must be exported");
    assert_eq!(
        main.tip, oid_a,
        "public branch must lag to the visibility frontier (A), not the embargoed tip"
    );
}

/// #316 / PR #528 Finding 1: a commit exported while PUBLIC, then later marked
/// `Private`, must NOT keep being served on the next export. The stale
/// ChangeId→OID mapping is rebuilt from the notes/cache every run, so the
/// export must re-validate current visibility and retract the public branch
/// down to the served frontier (here, the still-public base A).
#[test]
fn export_retracts_branch_when_public_commit_is_later_embargoed() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    // Linear thread: public base A, then public tip B.
    std::fs::write(heddle_temp.path().join("a.txt"), b"base\n").unwrap();
    repo.snapshot(Some("base".into()), None).unwrap();
    let state_a = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();
    std::fs::write(heddle_temp.path().join("b.txt"), b"fix\n").unwrap();
    repo.snapshot(Some("fix".into()), None).unwrap();
    let state_b = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();

    // Export run 1 — both public. The branch advertises the tip B.
    let mut bridge = GitBridge::new(&repo);
    let run1 = export_all(&mut bridge).expect("first export");
    let oid_a = test_support::mapping(&bridge)
        .get_git(&state_a)
        .expect("A minted");
    let oid_b = test_support::mapping(&bridge)
        .get_git(&state_b)
        .expect("B minted");
    let run1_main = run1
        .branches
        .iter()
        .find(|b| b.name == "main")
        .expect("main exported");
    assert_eq!(
        run1_main.tip, oid_b,
        "run 1 branch advertises the public tip B"
    );

    // B is embargoed AFTER it was already exported public.
    repo.put_state_visibility(StateVisibility {
        state: state_b,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Grace Hopper".into(),
            email: "grace@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();

    // Export run 2 — the stale B→OID mapping is rebuilt from notes, but the
    // re-validation purge drops it and the branch is retracted to A.
    let run2 = export_all(&mut bridge).expect("second export");
    let run2_main = run2
        .branches
        .iter()
        .find(|b| b.name == "main")
        .expect("main re-exported");
    assert_eq!(
        run2_main.tip, oid_a,
        "run 2 must lag the public branch to A, retracting the now-embargoed B"
    );
    assert!(
        test_support::mapping(&bridge).get_git(&state_b).is_none(),
        "the now-Private B must be purged from the served mapping"
    );
    let mapping_cache = std::fs::read_to_string(test_support::mapping_path(&bridge))
        .expect("mapping cache should be readable after export");
    assert!(
        !mapping_cache.contains(&state_b.to_string_full()),
        "the served bridge mapping cache must not persist embargoed ChangeIds: {mapping_cache}"
    );
    assert!(
        !mapping_cache.contains(&oid_b.to_string()),
        "the served bridge mapping cache must not persist embargoed Git OIDs: {mapping_cache}"
    );

    // The mirror ref itself no longer serves B.
    let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
    let mut main_ref = find_reference(&mirror, "refs/heads/main").expect("main ref present");
    let tip = main_ref.peel_to_id().unwrap();
    assert_eq!(
        tip, oid_a,
        "refs/heads/main must point at A after retraction"
    );
    assert_ne!(
        tip, oid_b,
        "refs/heads/main must not keep serving embargoed B"
    );
}

/// #737 EXPORT-path regression: lock the embargo `seed → purge → save` ordering
/// invariant on `export_scoped`.
///
/// `export_scoped` runs, in this exact order:
///   1. `seed_ingest_identity_mappings_from_mirror` — re-hydrates the in-memory
///      mapping from the PERSISTENT ingest SHA map (`.heddle/ingest/sha_map.sqlite`),
///      so a commit imported earlier is re-mapped ChangeId→OID even on a brand-new
///      bridge whose live mapping is empty;
///   2. `purge_unserved_mappings` — drops every mapping whose state (or a reachable
///      ancestor) is not served at the Public tier;
///   3. `save_mapping_to_disk` — writes the surviving mapping to the SERVED cache
///      `.heddle/git-bridge/bridge-mapping.json`.
///
/// An earlier intermediate `save_mapping_to_disk_preserving` helper snapshotted the
/// mapping BEFORE the purge, so a seeded-but-embargoed entry resurrected into the
/// served `bridge-mapping.json` — a visibility leak. That helper is gone; the fix
/// relies on seed-before-purge-before-save. PR #737 added the IMPORT-path test
/// `adopt_all_uses_ingest_mapping_without_internal_mirror`; this is its EXPORT-path
/// analogue: an embargoed SHA that the SEED re-introduces from the ingest map must
/// NOT survive into the served mapping after `export_scoped`.
///
/// The two earlier #316 tests above mint-then-purge a NATIVE tip in one run, so
/// they never exercise the seed re-introducing an already-persisted embargoed OID.
/// This test imports first (populating the durable ingest map), embargoes the tip,
/// then exports on a FRESH bridge — making the seed the live reintroduction vector.
#[test]
fn export_purge_drops_seeded_embargoed_sha_before_serving_mapping() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");

    // A source git repo with a linear history: base A, then tip B.
    let (_source_temp, source_repo) = init_git_repo();
    let tree_oid = empty_tree_oid(&source_repo);
    let git_a = commit_with_tree(&source_repo, None, tree_oid, "base", &[]);
    let git_b = commit_with_tree(
        &source_repo,
        Some("refs/heads/main"),
        tree_oid,
        "embargoed fix",
        &[git_a],
    );
    let source_workdir = source_repo.workdir().expect("workdir").to_path_buf();

    // Import populates the DURABLE ingest SHA map at .heddle/ingest/sha_map.sqlite
    // (kind=0) with git_a→change_a and git_b→change_b. This is the persistent
    // store the export-time seed reads from on a fresh bridge.
    let mut import_bridge = GitBridge::new(&repo);
    import_bridge
        .import(Some(source_workdir.as_path()))
        .expect("import source git history");
    let change_a = test_support::mapping(&import_bridge)
        .get_heddle(git_a)
        .expect("base A mapped after import");
    let change_b = test_support::mapping(&import_bridge)
        .get_heddle(git_b)
        .expect("tip B mapped after import");
    assert_ne!(change_a, change_b);
    drop(import_bridge);

    // The ingest map must actually carry B — otherwise the seed can't re-introduce
    // it and the test would pass vacuously.
    let ingest_map = repo
        .git_overlay_ingest_commit_mapping()
        .expect("read ingest commit mapping");
    assert!(
        ingest_map.values().any(|c| c == &change_b.to_string_full()),
        "precondition: ingest SHA map must hold the (to-be-embargoed) tip B"
    );

    // Embargo B at the strictest Private tier (downward-closure leaves A served).
    repo.put_state_visibility(StateVisibility {
        state: change_b,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Heddle Test".into(),
            email: "heddle@test".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .expect("embargo tip B");

    // Precondition: the SEED, run in isolation on a fresh bridge, WOULD re-introduce
    // B's OID from the ingest map (the seed is visibility-blind — it maps any state
    // that exists, embargoed or not). This proves the purge is what must remove it,
    // not the seed declining to add it.
    {
        let mut seed_probe = GitBridge::new(&repo);
        test_support::set_git_repo_path(&mut seed_probe, source_workdir.clone());
        let mirror = test_support::open_git_repo(&seed_probe).expect("open mirror for seed probe");
        test_support::seed_ingest_identity_mappings_from_mirror(&mut seed_probe, &mirror)
            .expect("seed from ingest map");
        assert_eq!(
            test_support::mapping(&seed_probe).get_git(&change_b),
            Some(git_b),
            "precondition: the seed re-introduces the embargoed tip B from the ingest map"
        );
    }

    // Export on a FRESH bridge: build_existing_mapping starts empty, the seed
    // re-hydrates B from the durable ingest map, then the purge must drop B before
    // save writes the served bridge-mapping.json.
    let mut export_bridge = GitBridge::new(&repo);
    export_all(&mut export_bridge).expect("export with seeded embargoed tip");

    // In-memory: the embargoed tip is gone; the public base survives.
    assert!(
        test_support::mapping(&export_bridge)
            .get_git(&change_b)
            .is_none(),
        "the purge must drop the seeded-but-embargoed tip B from the served mapping"
    );
    assert_eq!(
        test_support::mapping(&export_bridge).get_git(&change_a),
        Some(git_a),
        "the still-public base A must remain served"
    );

    // The CRITICAL leak surface: the served bridge-mapping.json on disk. A
    // pre-purge save (the resurrected `save_mapping_to_disk_preserving` bug) would
    // leak B's ChangeId and OID here even though the in-memory purge ran.
    let served = std::fs::read_to_string(test_support::mapping_path(&export_bridge))
        .expect("served bridge-mapping.json must exist after export");
    assert!(
        !served.contains(&change_b.to_string_full()),
        "served mapping must NOT contain the embargoed ChangeId B (seed→purge→save leak): {served}"
    );
    assert!(
        !served.contains(&git_b.to_string()),
        "served mapping must NOT contain the embargoed Git OID B (seed→purge→save leak): {served}"
    );
    assert!(
        served.contains(&change_a.to_string_full()) && served.contains(&git_a.to_string()),
        "served mapping must still publish the public base A: {served}"
    );
}

/// #737 structural guard: fail if anyone reintroduces a pre-purge save into the
/// export path. Pairs with `export_purge_drops_seeded_embargoed_sha_before_serving_mapping`
/// — that test catches the LEAK; this one catches the most likely REGRESSION SHAPE
/// (a `save_mapping_to_disk_preserving`-style helper, or a save call moved ahead of
/// the purge) directly at the source level, before any repo fixture runs.
#[test]
fn export_path_saves_mapping_strictly_after_the_embargo_purge() {
    let src_path = std::path::PathBuf::from(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/src/bridge/git_export.rs"
    ));
    let src = std::fs::read_to_string(&src_path)
        .unwrap_or_else(|e| panic!("read git_export.rs at {}: {e}", src_path.display()));

    // 1. The pre-purge snapshot helper that caused the #737 leak must stay gone.
    assert!(
        !src.contains("save_mapping_to_disk_preserving"),
        "git_export.rs reintroduced a pre-purge save helper \
         (save_mapping_to_disk_preserving) — this resurrects the #737 embargo leak"
    );

    // 2. The export path's single served-mapping save must sit AFTER the purge.
    //    Both calls are unique in the file, so a byte-offset comparison pins the
    //    ordering: seed (already before) → purge → save.
    let purge_at = src
        .find("purge_unserved_mappings(")
        .expect("git_export.rs must call purge_unserved_mappings in the export path");
    let save_at = src
        .find("save_mapping_to_disk()")
        .expect("git_export.rs must call save_mapping_to_disk in the export path");
    assert!(
        src.matches("save_mapping_to_disk()").count() == 1,
        "expected exactly one save_mapping_to_disk() call site in the export path; \
         a second one may bypass the purge"
    );
    assert!(
        save_at > purge_at,
        "save_mapping_to_disk() (offset {save_at}) must run AFTER \
         purge_unserved_mappings() (offset {purge_at}) — saving the mapping before \
         the embargo purge resurrects the #737 leak"
    );
}

/// #316 / PR #528 r3 Finding 2: when a public commit is later embargoed, the
/// purge drops its ChangeId→OID mapping AND its `refs/notes/heddle` entry must
/// be retracted too. `collect_ref_updates` copies `refs/notes/*` to the mirror
/// alongside branches and tags, so a note left for a withheld commit keeps
/// publishing that commit's metadata (change_id, agent, status) even after the
/// branch was retracted — a metadata leak. The note for a still-served commit
/// must survive.
#[test]
fn export_retracts_note_for_retracted_commit() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    // Linear thread: public base A, then public tip B.
    std::fs::write(heddle_temp.path().join("a.txt"), b"base\n").unwrap();
    repo.snapshot(Some("base".into()), None).unwrap();
    let state_a = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();
    std::fs::write(heddle_temp.path().join("b.txt"), b"fix\n").unwrap();
    repo.snapshot(Some("fix".into()), None).unwrap();
    let state_b = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();

    // Export run 1 — both public. Notes get written for A and B.
    let mut bridge = GitBridge::new(&repo);
    export_all(&mut bridge).expect("first export");
    let oid_a = test_support::mapping(&bridge)
        .get_git(&state_a)
        .expect("A minted");
    let oid_b = test_support::mapping(&bridge)
        .get_git(&state_b)
        .expect("B minted");
    {
        let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
        assert!(
            cli::bridge::git_notes::read_note(&mirror, oid_a)
                .unwrap()
                .is_some(),
            "A must carry a note after run 1"
        );
        assert!(
            cli::bridge::git_notes::read_note(&mirror, oid_b)
                .unwrap()
                .is_some(),
            "B must carry a note after run 1"
        );
    }

    // B is embargoed AFTER it was already exported public.
    repo.put_state_visibility(StateVisibility {
        state: state_b,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Grace Hopper".into(),
            email: "grace@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();

    // Export run 2 — B is purged and its note must be retracted; A's note,
    // still served, must remain.
    export_all(&mut bridge).expect("second export");
    let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
    assert!(
        cli::bridge::git_notes::read_note(&mirror, oid_b)
            .unwrap()
            .is_none(),
        "run 2 must retract the note for the now-embargoed B (no metadata leak)"
    );
    assert!(
        cli::bridge::git_notes::read_note(&mirror, oid_a)
            .unwrap()
            .is_some(),
        "A is still served — its note must survive the retraction"
    );
}

/// #316 / PR #528 r9 FINDING B: a thread-SCOPED export must retract the note
/// for any mapped out-of-thread commit that is unserved under the SAME
/// downward-closure rule the branch frontier uses — not just the scoped
/// `embargoed_oids`. A commit whose DIRECT tier is public but whose ANCESTOR
/// became Private is not served (its branch would be withheld), yet
/// `purge_unserved_mappings` only walks the scoped thread's reachable states,
/// so without the full-target servedness pass its `refs/notes/heddle` entry
/// stays in the mirror and gets pushed — a notes leak in scoped exports.
#[test]
fn scoped_export_retracts_note_for_commit_with_embargoed_ancestor() {
    use chrono::Utc;
    use objects::object::{Attribution, Principal, State, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let put_state = |content: &[u8], parents: Vec<ChangeId>| -> State {
        let store = repo.store();
        let blob_hash = store
            .put_blob(&Blob::from_slice(content))
            .expect("put blob");
        let tree_hash = store
            .put_tree(&Tree::from_entries(vec![
                TreeEntry::file("file.txt".to_string(), blob_hash, false).expect("tree entry"),
            ]))
            .expect("put tree");
        let state = State::new(
            tree_hash,
            parents,
            Attribution::human(Principal::new("Alice", "alice@example.com")),
        );
        store.put_state(&state).expect("put state");
        state
    };

    // main line: public root R → public tip X (X descends from R).
    let state_r = put_state(b"root\n", Vec::new());
    let state_x = put_state(b"tip\n", vec![state_r.change_id]);
    repo.refs()
        .set_thread(&ThreadName::new("main"), &state_x.change_id)
        .expect("set main to X");
    // A separate, independent line on thread `other`: public root O.
    let state_o = put_state(b"other root\n", Vec::new());
    repo.refs()
        .set_thread(&ThreadName::new("other"), &state_o.change_id)
        .expect("set other to O");

    // Run 1 — everything public. Notes get written for R, X, and O.
    let mut bridge = GitBridge::new(&repo);
    export_all(&mut bridge).expect("first export");
    let oid_x = test_support::mapping(&bridge)
        .get_git(&state_x.change_id)
        .expect("X minted while public");
    let oid_o = test_support::mapping(&bridge)
        .get_git(&state_o.change_id)
        .expect("O minted while public");
    {
        let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
        assert!(
            cli::bridge::git_notes::read_note(&mirror, oid_x)
                .unwrap()
                .is_some(),
            "X must carry a note after run 1"
        );
    }

    // Embargo R (X's ANCESTOR) — X's own tier stays public, but downward
    // closure now withholds X.
    repo.put_state_visibility(StateVisibility {
        state: state_r.change_id,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Alice".into(),
            email: "alice@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();

    // Run 2 — SCOPED to `other`, which does NOT reach R or X. The scoped purge
    // never examines X, but the notes-ref retraction must still withhold X's
    // note because its ancestor R is unserved.
    export_current_thread(&mut bridge, "other").expect("scoped export");
    let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
    assert!(
        cli::bridge::git_notes::read_note(&mirror, oid_x)
            .unwrap()
            .is_none(),
        "scoped export must retract X's note (ancestor embargoed) — no notes leak"
    );
    assert!(
        cli::bridge::git_notes::read_note(&mirror, oid_o)
            .unwrap()
            .is_some(),
        "O is served — its note must survive the scoped retraction"
    );
}

/// #316 / PR #528 r14: a SCOPED export must reconcile cross-thread embargo. A
/// prior all-thread export publishes threads `alpha` and `beta`; then a commit
/// reachable ONLY via `beta` is marked Private. A scoped export of `alpha` (not
/// `beta`) must STILL rewind `beta`'s `refs/heads/` off the now-embargoed commit:
/// the mirror reconcile spans the WHOLE mirror's served frontier, not just the
/// export's scoped thread. `alpha`'s own ref is left untouched.
#[test]
fn scoped_export_reconciles_cross_thread_embargo() {
    use chrono::Utc;
    use objects::object::{Attribution, Principal, State, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let put_state = |content: &[u8], parents: Vec<ChangeId>| -> State {
        let store = repo.store();
        let blob_hash = store
            .put_blob(&Blob::from_slice(content))
            .expect("put blob");
        let tree_hash = store
            .put_tree(&Tree::from_entries(vec![
                TreeEntry::file("file.txt".to_string(), blob_hash, false).expect("tree entry"),
            ]))
            .expect("put tree");
        let state = State::new(
            tree_hash,
            parents,
            Attribution::human(Principal::new("Alice", "alice@example.com")),
        );
        store.put_state(&state).expect("put state");
        state
    };

    // Two independent lines (no shared ancestry).
    // alpha: A0 → A1 (both public). beta: B0 → B1 → B2 (all public).
    let state_a0 = put_state(b"a0\n", Vec::new());
    let state_a1 = put_state(b"a1\n", vec![state_a0.change_id]);
    repo.refs()
        .set_thread(&ThreadName::new("alpha"), &state_a1.change_id)
        .expect("set alpha to A1");
    let state_b0 = put_state(b"b0\n", Vec::new());
    let state_b1 = put_state(b"b1\n", vec![state_b0.change_id]);
    let state_b2 = put_state(b"b2\n", vec![state_b1.change_id]);
    repo.refs()
        .set_thread(&ThreadName::new("beta"), &state_b2.change_id)
        .expect("set beta to B2");

    // Run 1 — everything public, all-thread export. Both branches published.
    let mut bridge = GitBridge::new(&repo);
    let run1 = export_all(&mut bridge).expect("first export");
    let oid_a1 = test_support::mapping(&bridge)
        .get_git(&state_a1.change_id)
        .expect("A1 minted while public");
    let oid_b0 = test_support::mapping(&bridge)
        .get_git(&state_b0.change_id)
        .expect("B0 minted while public");
    let oid_b2 = test_support::mapping(&bridge)
        .get_git(&state_b2.change_id)
        .expect("B2 minted while public");
    assert!(
        run1.branches
            .iter()
            .any(|b| b.name == "beta" && b.tip == oid_b2),
        "run 1 advertises beta at its public tip B2"
    );

    // Embargo B1 — a commit reachable ONLY via beta. Downward closure withholds
    // B1 and its descendant B2; B0 stays served.
    repo.put_state_visibility(StateVisibility {
        state: state_b1.change_id,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Alice".into(),
            email: "alice@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();

    // Run 2 — SCOPED to alpha, which does NOT reach beta. The mirror reconcile
    // must STILL rewind beta off the embargoed commit; alpha is untouched.
    export_current_thread(&mut bridge, "alpha").expect("scoped export");
    let mirror = test_support::open_git_repo(&bridge).expect("open mirror");

    // beta rewound to its served frontier B0 — the embargoed B1/B2 are no longer
    // reachable from any mirror ref.
    let beta_tip = find_reference(&mirror, "refs/heads/beta")
        .expect("beta still present at its served frontier")
        .peel_to_id()
        .expect("peel beta");
    assert_eq!(
        beta_tip, oid_b0,
        "scoped alpha export must rewind beta off the embargoed commit to B0"
    );
    assert_ne!(
        beta_tip, oid_b2,
        "beta must not keep serving the now-embargoed tip B2"
    );

    // alpha's own ref is unaffected by the scoped export.
    let alpha_tip = find_reference(&mirror, "refs/heads/alpha")
        .expect("alpha present")
        .peel_to_id()
        .expect("peel alpha");
    assert_eq!(
        alpha_tip, oid_a1,
        "scoped export must leave its own thread's ref at A1"
    );
}

/// #316 / PR #528 r16 (close-the-class): the DESTINATION-side analog of
/// [`scoped_export_reconciles_cross_thread_embargo`]. r14 made the MIRROR
/// reconcile whole-mirror, so a scoped export of `alpha` rewinds an out-of-scope
/// `beta` off an embargoed commit — but the DESTINATION push still derived its
/// desired set from the SCOPE-FILTERED ref list, so the out-of-scope `beta` fell
/// into a "still served, leave untouched" arm and the destination KEPT SERVING
/// the embargoed tip. The destination reconcile now derives from the SAME
/// whole-mirror served frontier as the mirror reconcile, so a scoped push of
/// alpha rewinds the destination's `beta` BY CONSTRUCTION. An out-of-band
/// destination tip on a third ref must still be spared — widening the desired set
/// to whole-mirror must NOT weaken r13's ownership gate.
#[test]
fn scoped_push_propagates_cross_thread_embargo_to_destination() {
    use chrono::Utc;
    use objects::object::{Attribution, Principal, State, StateVisibility, VisibilityTier};
    use refs::Head;

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let put_state = |content: &[u8], parents: Vec<ChangeId>| -> State {
        let store = repo.store();
        let blob_hash = store
            .put_blob(&Blob::from_slice(content))
            .expect("put blob");
        let tree_hash = store
            .put_tree(&Tree::from_entries(vec![
                TreeEntry::file("file.txt".to_string(), blob_hash, false).expect("tree entry"),
            ]))
            .expect("put tree");
        let state = State::new(
            tree_hash,
            parents,
            Attribution::human(Principal::new("Alice", "alice@example.com")),
        );
        store.put_state(&state).expect("put state");
        state
    };

    // Three independent lines (no shared ancestry).
    // alpha: A0 → A1 (public). beta: B0 → B1 → B2 (public; B1 embargoed below).
    // gamma: G0 (public; later embargoed AND advanced out of band at the destination).
    let state_a0 = put_state(b"a0\n", Vec::new());
    let state_a1 = put_state(b"a1\n", vec![state_a0.change_id]);
    repo.refs()
        .set_thread(&ThreadName::new("alpha"), &state_a1.change_id)
        .expect("set alpha to A1");
    let state_b0 = put_state(b"b0\n", Vec::new());
    let state_b1 = put_state(b"b1\n", vec![state_b0.change_id]);
    let state_b2 = put_state(b"b2\n", vec![state_b1.change_id]);
    repo.refs()
        .set_thread(&ThreadName::new("beta"), &state_b2.change_id)
        .expect("set beta to B2");
    let state_g0 = put_state(b"g0\n", Vec::new());
    repo.refs()
        .set_thread(&ThreadName::new("gamma"), &state_g0.change_id)
        .expect("set gamma to G0");

    // Run 1 — everything public, full export+push to a local destination. All three
    // branches are published AND recorded as heddle-exported there.
    let mut bridge = GitBridge::new(&repo);
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    bridge
        .export_to_path(&dest_path)
        .expect("first full export+push publishes alpha, beta, gamma");
    let oid_a1 = test_support::mapping(&bridge)
        .get_git(&state_a1.change_id)
        .expect("A1 minted");
    let oid_b0 = test_support::mapping(&bridge)
        .get_git(&state_b0.change_id)
        .expect("B0 minted");
    let oid_b2 = test_support::mapping(&bridge)
        .get_git(&state_b2.change_id)
        .expect("B2 minted");
    let oid_g0 = test_support::mapping(&bridge)
        .get_git(&state_g0.change_id)
        .expect("G0 minted");
    {
        let dest = open_git(&dest_path).expect("open dest");
        assert_eq!(
            find_reference(&dest, "refs/heads/beta")
                .unwrap()
                .peel_to_id()
                .unwrap(),
            oid_b2,
            "run 1 publishes beta at its public tip B2 to the destination"
        );
    }

    // Out-of-band advance: move the DESTINATION's gamma to a NEW commit G_oob that
    // heddle never published (a descendant of the published G0). Heddle's record
    // still says gamma == G0, so the ownership gate must spare G_oob.
    let oid_g_oob = {
        let dest = open_git(&dest_path).expect("open dest");
        commit_with_tree(
            &dest,
            Some("refs/heads/gamma"),
            empty_tree_oid(&dest),
            "out-of-band gamma",
            &[oid_g0],
        )
    };

    // Embargo B1 (reachable ONLY via beta) AND the whole gamma line (G0). Downward
    // closure withholds B1/B2 (B0 stays served) and the whole gamma line (no served
    // frontier ⇒ gamma is retracted from the mirror).
    let embargo = |state: ChangeId| {
        repo.put_state_visibility(StateVisibility {
            state,
            tier: VisibilityTier::Private {
                scope_label: "sec-embargo".into(),
            },
            embargo_until: None,
            declarer: Principal {
                name: "Alice".into(),
                email: "alice@example.com".into(),
            },
            declared_at: Utc::now(),
            signature: None,
            supersedes: None,
        })
        .unwrap();
    };
    embargo(state_b1.change_id);
    embargo(state_g0.change_id);

    // Attach HEAD to alpha so a CurrentThread push scopes its EXPORT to alpha —
    // alpha reaches neither beta nor gamma.
    repo.refs()
        .write_head(&Head::Attached {
            thread: ThreadName::new("alpha"),
        })
        .expect("attach HEAD to alpha");

    // Run 2 — SCOPED push of alpha to the SAME destination. The destination reconcile
    // is driven by the whole-mirror served frontier, so it must rewind the
    // destination's out-of-scope beta off the embargoed commit even though alpha
    // does not reach beta.
    bridge
        .push_with_scope(
            dest_path.to_str().expect("dest path"),
            GitPushScope::CurrentThread,
        )
        .expect("scoped push of alpha");

    let dest = open_git(&dest_path).expect("reopen dest");

    // beta REWOUND at the destination to its served frontier B0 — the embargoed
    // B1/B2 are no longer served from the destination. This is the leak r16 closes.
    let beta_tip = find_reference(&dest, "refs/heads/beta")
        .expect("beta still present at its served frontier")
        .peel_to_id()
        .expect("peel beta");
    assert_eq!(
        beta_tip, oid_b0,
        "scoped push of alpha must rewind the destination's beta off the embargoed commit to B0"
    );
    assert_ne!(
        beta_tip, oid_b2,
        "the destination must not keep serving the now-embargoed tip B2"
    );

    // alpha's own destination ref is at A1 and unaffected by the scoped push.
    let alpha_tip = find_reference(&dest, "refs/heads/alpha")
        .expect("alpha present")
        .peel_to_id()
        .expect("peel alpha");
    assert_eq!(
        alpha_tip, oid_a1,
        "scoped push must leave alpha at A1 at the destination"
    );

    // The out-of-band gamma tip is SPARED: heddle's record (G0) does not match the
    // destination's current tip (G_oob), so the ownership gate skips the retraction
    // delete — widening the desired set to whole-mirror did NOT weaken r13.
    let gamma_tip = find_reference(&dest, "refs/heads/gamma")
        .expect("gamma survives — heddle must not delete a tip it never published")
        .peel_to_id()
        .expect("peel gamma");
    assert_eq!(
        gamma_tip, oid_g_oob,
        "the out-of-band gamma tip must survive the scoped push (r13 ownership gate holds)"
    );
}

/// #316 / PR #528 Finding 1 (root case): when the WHOLE line is embargoed to
/// its root after a prior public export, the stale public branch must be
/// deleted, not left pointing at the now-embargoed commit.
#[test]
fn export_deletes_branch_when_whole_line_is_later_embargoed() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    // A single public state on main.
    std::fs::write(heddle_temp.path().join("a.txt"), b"only\n").unwrap();
    repo.snapshot(Some("only".into()), None).unwrap();
    let state_a = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();

    let mut bridge = GitBridge::new(&repo);
    export_all(&mut bridge).expect("first export");
    assert!(
        test_support::mapping(&bridge).get_git(&state_a).is_some(),
        "A minted while public"
    );

    // Embargo EVERY state on the line — including the seeded root — so the
    // whole line is embargoed to its root and no served ancestor remains.
    for state in repo.store().list_states().unwrap() {
        repo.put_state_visibility(StateVisibility {
            state,
            tier: VisibilityTier::Private {
                scope_label: "sec-embargo".into(),
            },
            embargo_until: None,
            declarer: Principal {
                name: "Grace Hopper".into(),
                email: "grace@example.com".into(),
            },
            declared_at: Utc::now(),
            signature: None,
            supersedes: None,
        })
        .unwrap();
    }

    let run2 = export_all(&mut bridge).expect("second export");
    assert!(
        run2.branches.iter().all(|b| b.name != "main"),
        "main must not be advertised once the whole line is embargoed"
    );
    let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
    assert!(
        find_reference(&mirror, "refs/heads/main").is_err(),
        "the stale public branch must be deleted, not left serving the embargoed commit"
    );
}

/// #316 / PR #528 r2 Finding 1 (sibling): a branch exported at a PUBLIC commit,
/// then reset/rebased onto an unrelated `Private` root, must be deleted from the
/// mirror. The old public tip is NOT embargoed — it is simply no longer
/// reachable from the new tip — so r1's embargoed-tip retraction never fires.
/// The unifying invariant catches it anyway: a mirror ref exists iff its CURRENT
/// target resolves to a served frontier, and the new Private root resolves to
/// none.
#[test]
fn export_deletes_branch_when_thread_reset_to_private_root() {
    use chrono::Utc;
    use objects::object::{Attribution, Principal, State, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let put_state = |content: &[u8], parents: Vec<ChangeId>| -> State {
        let store = repo.store();
        let blob_hash = store
            .put_blob(&Blob::from_slice(content))
            .expect("put blob");
        let tree_hash = store
            .put_tree(&Tree::from_entries(vec![
                TreeEntry::file("file.txt".to_string(), blob_hash, false).expect("tree entry"),
            ]))
            .expect("put tree");
        let state = State::new(
            tree_hash,
            parents,
            Attribution::human(Principal::new("Alice", "alice@example.com")),
        );
        store.put_state(&state).expect("put state");
        state
    };

    // Public root A on main.
    let state_a = put_state(b"public base\n", Vec::new());
    repo.refs()
        .set_thread(&ThreadName::new("main"), &state_a.change_id)
        .expect("set main to A");

    let mut bridge = GitBridge::new(&repo);
    let run1 = export_all(&mut bridge).expect("first export");
    let oid_a = test_support::mapping(&bridge)
        .get_git(&state_a.change_id)
        .expect("A minted while public");
    assert!(
        run1.branches
            .iter()
            .any(|b| b.name == "main" && b.tip == oid_a),
        "run 1 advertises main at the public root A"
    );

    // Reset main onto an unrelated Private root B (no shared ancestry with A).
    let state_b = put_state(b"private root\n", Vec::new());
    repo.put_state_visibility(StateVisibility {
        state: state_b.change_id,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Alice".into(),
            email: "alice@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();
    repo.refs()
        .set_thread(&ThreadName::new("main"), &state_b.change_id)
        .expect("reset main to B");

    // A stays public — NOT embargoed — so r1's embargoed-tip retraction cannot
    // fire. B's line has no served frontier, so main must be deleted anyway.
    let run2 = export_all(&mut bridge).expect("second export");
    assert!(
        run2.branches.iter().all(|b| b.name != "main"),
        "main must not be advertised once reset onto a Private root"
    );
    let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
    assert!(
        find_reference(&mirror, "refs/heads/main").is_err(),
        "the stale public branch must be deleted after a reset to a Private root"
    );
    // Sanity: A is still served — proving the deletion is driven by the new
    // target resolving to no served frontier, not by an embargo of the old tip.
    assert!(
        test_support::mapping(&bridge)
            .get_git(&state_a.change_id)
            .is_some(),
        "the old public tip A remains served; deletion is not driven by an embargo of A"
    );
}

/// #316 / PR #528 r2 Finding 2 (sibling): a marker exported as a tag at a PUBLIC
/// state A, then retargeted to a `Private` state B, must have its stale tag
/// deleted. The old tag tip A is NOT embargoed (still served), so r1's
/// embargoed-tip retraction never fires — but the marker's CURRENT target (B) is
/// not served, so the unified invariant deletes the tag.
#[test]
fn export_deletes_tag_when_marker_retargeted_to_private() {
    use chrono::Utc;
    use objects::object::{Attribution, Principal, State, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let put_state = |content: &[u8], parents: Vec<ChangeId>| -> State {
        let store = repo.store();
        let blob_hash = store
            .put_blob(&Blob::from_slice(content))
            .expect("put blob");
        let tree_hash = store
            .put_tree(&Tree::from_entries(vec![
                TreeEntry::file("file.txt".to_string(), blob_hash, false).expect("tree entry"),
            ]))
            .expect("put tree");
        let state = State::new(
            tree_hash,
            parents,
            Attribution::human(Principal::new("Alice", "alice@example.com")),
        );
        store.put_state(&state).expect("put state");
        state
    };

    // Public state A on main, plus a marker v1.0 pinned to A.
    let state_a = put_state(b"public release\n", Vec::new());
    repo.refs()
        .set_thread(&ThreadName::new("main"), &state_a.change_id)
        .expect("set main to A");
    repo.refs()
        .create_marker(&MarkerName::new("v1.0"), &state_a.change_id)
        .expect("create marker at A");

    let mut bridge = GitBridge::new(&repo);
    let run1 = export_all(&mut bridge).expect("first export");
    let oid_a = test_support::mapping(&bridge)
        .get_git(&state_a.change_id)
        .expect("A minted while public");
    assert!(
        run1.tags.iter().any(|t| t.name == "v1.0" && t.tip == oid_a),
        "run 1 publishes tag v1.0 at the public state A"
    );

    // Retarget v1.0 onto a Private state B (never minted into the mirror).
    let state_b = put_state(b"private release\n", Vec::new());
    repo.put_state_visibility(StateVisibility {
        state: state_b.change_id,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Alice".into(),
            email: "alice@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();
    repo.refs()
        .delete_marker(&MarkerName::new("v1.0"))
        .expect("clear old marker");
    repo.refs()
        .create_marker(&MarkerName::new("v1.0"), &state_b.change_id)
        .expect("retarget marker to B");

    // A is still served (not embargoed), so r1's stale-tag retraction cannot
    // fire — but B is not served, so the tag must be deleted by the invariant.
    let run2 = export_all(&mut bridge).expect("second export");
    assert!(
        run2.tags.iter().all(|t| t.name != "v1.0"),
        "v1.0 must not be published once retargeted to a Private state"
    );
    let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
    assert!(
        find_reference(&mirror, "refs/tags/v1.0").is_err(),
        "the stale public tag must be deleted after retarget to a Private state"
    );
    assert!(
        test_support::mapping(&bridge)
            .get_git(&state_a.change_id)
            .is_some(),
        "the old tag tip A remains served; deletion is not driven by an embargo of A"
    );
}

/// #316 / PR #528 r18 (the dual of the embargo retraction): the marker reconcile
/// must NOT conflate "unserved (embargoed)" with "served-but-not-minted
/// (out-of-scope)". A marker absent from the projected desired set has two
/// causes the desired set alone cannot tell apart — its target is genuinely
/// unserved (delete the stale tag, correct), OR its target is a still-PUBLIC
/// state that this scoped export simply did not mint into the mirror, so it has
/// no git OID in the mapping yet (preserve the prior tag). Deleting in the second
/// case spuriously RETRACTS a previously-exported public tag until an all-thread
/// export re-mints the target. This is the tag-side analog of the head rule: a
/// scoped export neither materializes a brand-new ref nor deletes a still-served
/// one it merely didn't mint.
///
/// The trigger that drives a SERVED marker target out of the mapping (the only
/// way the `None` arm is reached for a public target) is a RETARGET to a
/// not-yet-minted out-of-scope public state: a stationary marker's target stays
/// in the mapping via the notes/cache rebuild, so it goes through the `Some`
/// arm. The symmetric `Private`-retarget case (genuinely unserved) is covered by
/// [`export_deletes_tag_when_marker_retargeted_to_private`] — together they prove
/// the reconcile distinguishes served-but-unminted (preserve) from unserved
/// (delete).
#[test]
fn scoped_export_preserves_unminted_out_of_scope_public_tag() {
    use refs::Head;

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let put_state = |content: &[u8], parents: Vec<ChangeId>| -> objects::object::State {
        use objects::object::{Attribution, Principal, State};
        let store = repo.store();
        let blob_hash = store
            .put_blob(&Blob::from_slice(content))
            .expect("put blob");
        let tree_hash = store
            .put_tree(&Tree::from_entries(vec![
                TreeEntry::file("file.txt".to_string(), blob_hash, false).expect("tree entry"),
            ]))
            .expect("put tree");
        let state = State::new(
            tree_hash,
            parents,
            Attribution::human(Principal::new("Alice", "alice@example.com")),
        );
        store.put_state(&state).expect("put state");
        state
    };

    // Two independent public lines. alpha: A (the scoped thread). beta: B (a
    // B-only state pinned by marker v1.0). alpha never reaches beta.
    let state_a = put_state(b"alpha\n", Vec::new());
    repo.refs()
        .set_thread(&ThreadName::new("alpha"), &state_a.change_id)
        .expect("set alpha to A");
    let state_b = put_state(b"beta release\n", Vec::new());
    repo.refs()
        .set_thread(&ThreadName::new("beta"), &state_b.change_id)
        .expect("set beta to B");
    repo.refs()
        .create_marker(&MarkerName::new("v1.0"), &state_b.change_id)
        .expect("create marker v1.0 at B");

    // Run 1 — full export+push to a real destination. Both threads + the tag land,
    // and B is minted into the mirror at oid_b.
    let mut bridge = GitBridge::new(&repo);
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    bridge
        .export_to_path(&dest_path)
        .expect("first full export publishes alpha, beta, and tag v1.0");
    let oid_b = test_support::mapping(&bridge)
        .get_git(&state_b.change_id)
        .expect("B minted while public");
    {
        let dest = open_git(&dest_path).expect("open dest");
        assert_eq!(
            find_reference(&dest, "refs/tags/v1.0")
                .expect("run 1 publishes tag v1.0 to the destination")
                .peel_to_id()
                .expect("peel v1.0"),
            oid_b,
            "run 1 publishes tag v1.0 at the public state B"
        );
    }

    // Advance beta to a NEW public state C and RETARGET v1.0 onto it. C has never
    // been exported, so it carries no note/sidecar mapping — the only way a still
    // public marker target reaches the reconcile's `None` arm.
    let state_c = put_state(b"beta rc\n", vec![state_b.change_id]);
    repo.refs()
        .set_thread(&ThreadName::new("beta"), &state_c.change_id)
        .expect("advance beta to C");
    repo.refs()
        .delete_marker(&MarkerName::new("v1.0"))
        .expect("clear old marker");
    repo.refs()
        .create_marker(&MarkerName::new("v1.0"), &state_c.change_id)
        .expect("retarget marker v1.0 to C");

    // Attach HEAD to alpha so a CurrentThread push scopes the EXPORT to alpha,
    // which does NOT reach C and so does NOT mint it this run.
    repo.refs()
        .write_head(&Head::Attached {
            thread: ThreadName::new("alpha"),
        })
        .expect("attach HEAD to alpha");

    // Sanity: C is genuinely absent from the mapping going into the scoped push —
    // this is the served-but-unminted condition the fix must handle.
    assert!(
        test_support::mapping(&bridge)
            .get_git(&state_c.change_id)
            .is_none(),
        "C must be unminted so the marker reconcile takes the `None` arm"
    );

    // Run 2 — SCOPED push of alpha. C stays PUBLIC and served; the scoped export
    // just doesn't mint it. The marker reconcile must PRESERVE the existing tag
    // (at its prior oid_b) rather than retract it as if C had become unserved — a
    // later all-thread export will re-mint C and advance the tag.
    bridge
        .push_with_scope(
            dest_path.to_str().expect("dest path"),
            GitPushScope::CurrentThread,
        )
        .expect("scoped push of alpha");

    // The mirror must KEEP refs/tags/v1.0 — a served-but-unminted marker target is
    // not a stale tag.
    let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
    assert_eq!(
        find_reference(&mirror, "refs/tags/v1.0")
            .expect("mirror must keep the served-but-unminted public tag v1.0")
            .peel_to_id()
            .expect("peel mirror v1.0"),
        oid_b,
        "the scoped export must not retract a tag whose target is still public"
    );

    // ...and the destination reconcile must NOT propagate a deletion.
    let dest = open_git(&dest_path).expect("reopen dest");
    assert_eq!(
        find_reference(&dest, "refs/tags/v1.0")
            .expect("destination must keep the served-but-unminted public tag v1.0")
            .peel_to_id()
            .expect("peel dest v1.0"),
        oid_b,
        "the scoped push must not delete a tag whose target is still public"
    );
}

/// #316 / PR #528 — fixture helper for the reconcile conformance matrices: a
/// PUBLIC state holding one file, attributed to a real principal so the export
/// mints it without any git-identity config.
fn matrix_put_state(
    repo: &Repository,
    content: &[u8],
    parents: Vec<ChangeId>,
) -> objects::object::State {
    use objects::object::{Attribution, Principal, State};
    let store = repo.store();
    let blob_hash = store
        .put_blob(&Blob::from_slice(content))
        .expect("put blob");
    let tree_hash = store
        .put_tree(&Tree::from_entries(vec![
            TreeEntry::file("file.txt".to_string(), blob_hash, false).expect("tree entry"),
        ]))
        .expect("put tree");
    let state = State::new(
        tree_hash,
        parents,
        Attribution::human(Principal::new("Alice", "alice@example.com")),
    );
    store.put_state(&state).expect("put state");
    state
}

/// Mark `state` Private so the export treats it as unserved (embargoed).
fn matrix_embargo(repo: &Repository, state: ChangeId) {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};
    repo.put_state_visibility(StateVisibility {
        state,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Alice".into(),
            email: "alice@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();
}

/// Read the mirror's `refs/tags/<name>` tip, or `None` when the tag is absent.
fn matrix_mirror_tag(bridge: &GitBridge, name: &str) -> Option<ObjectId> {
    let mirror = test_support::open_git_repo(bridge).expect("open mirror");
    find_reference(&mirror, &format!("refs/tags/{name}"))
        .ok()
        .and_then(|mut r| r.peel_to_id().ok())
}

/// Read the mirror's `refs/heads/<name>` tip, or `None` when the branch is absent.
fn matrix_mirror_head(bridge: &GitBridge, name: &str) -> Option<ObjectId> {
    let mirror = test_support::open_git_repo(bridge).expect("open mirror");
    find_reference(&mirror, &format!("refs/heads/{name}"))
        .ok()
        .and_then(|mut r| r.peel_to_id().ok())
}

/// #316 / PR #528 — plant a FOREIGN tag in the mirror: a `refs/tags/<name>` heddle
/// never WROTE (no marker, never reconciled under that name). Pass a heddle-MINTED
/// `target` to exercise the r20c bug — OID-based ownership would mis-claim it as
/// heddle's; the name-keyed managed record must still spare it.
fn matrix_plant_foreign_tag(bridge: &GitBridge, name: &str, target: ObjectId) {
    let mirror = test_support::open_git_repo(bridge).expect("open mirror");
    set_reference(
        &mirror,
        &format!("refs/tags/{name}"),
        target,
        RefPrecondition::Any,
        "test: foreign tag",
    )
    .expect("plant foreign tag");
}

/// #316 / PR #528 — plant a FOREIGN branch in the mirror: a `refs/heads/<name>`
/// heddle never wrote, at a heddle-minted `target` (the head dual of the foreign
/// tag at a heddle OID). It is not a heddle thread, so the head reconcile never
/// iterates it; the name-keyed record must spare it.
fn matrix_plant_foreign_branch(bridge: &GitBridge, name: &str, target: ObjectId) {
    let mirror = test_support::open_git_repo(bridge).expect("open mirror");
    set_reference(
        &mirror,
        &format!("refs/heads/{name}"),
        target,
        RefPrecondition::Any,
        "test: foreign branch",
    )
    .expect("plant foreign branch");
}

/// #316 / PR #528 — the mirror's name-keyed managed-refs record (full ref name →
/// last-published tip), the ownership boundary the reconcile and the push frontier
/// both read.
fn matrix_managed_record(bridge: &GitBridge) -> std::collections::HashMap<String, ObjectId> {
    let mirror = test_support::open_git_repo(bridge).expect("open mirror");
    read_mirror_managed_refs(&mirror).expect("read mirror managed record")
}

/// #316 / PR #528 — whether `collect_managed_ref_updates` (the managed-filtered
/// push frontier) carries a ref of `name`+`namespace`. A foreign ref must be
/// ABSENT here even though it survives in the mirror.
fn matrix_in_managed_frontier(bridge: &GitBridge, name: &str, namespace: RefNamespace) -> bool {
    let mirror = test_support::open_git_repo(bridge).expect("open mirror");
    let record = read_mirror_managed_refs(&mirror).expect("read record");
    collect_managed_ref_updates(&mirror, &record)
        .expect("collect managed frontier")
        .iter()
        .any(|u| u.namespace == namespace && u.name == name)
}

/// #316 / PR #528 r19 + S3 — the conformance matrix that turns the per-cell tag
/// fixes into a REDESIGN. The mirror tag's fate is a PURE FUNCTION of THREE axes:
/// the NEW marker target {served+minted, served-but-unminted, unserved,
/// no-target(deleted)} × the EXISTING mirror tag's target {served, embargoed,
/// absent} × scope {scoped, full}. Each row builds a fixture that reaches one
/// cell, runs `export_all`/`export_current_thread`, and asserts the mirror
/// `refs/tags/v` is at the expected OID or absent. The structural guarantees it
/// locks:
/// * PRESERVE requires the EXISTING tag itself be SERVED (cell 6) — a tag pointing
///   at an embargoed commit is DELETED even when the new target is served-but-
///   unminted (cell 7, the r19 fix `existing_embargoed_unminted_new_deletes_tag`);
///   reading the existing tag's TARGET is the axis the prior code never inspected.
/// * a served+minted target FORCE-retargets the tag (S1, cells 2/3).
/// * a DELETED marker still deletes its stale tag because the loop iterates
///   `markers ∪ existing-tags` — the deleted marker is reached via the tags side
///   (S3, cell 12).
///
/// It SUBSUMES the locked-in tests
/// [`export_deletes_tag_when_marker_retargeted_to_private`] (cell 9) and
/// [`scoped_export_preserves_unminted_out_of_scope_public_tag`] (cell 6).
#[test]
fn tag_reconcile_conformance_matrix() {
    struct Cell {
        label: &'static str,
        /// Returns (observed mirror `refs/tags/v` tip, expected tip).
        run: Box<dyn Fn() -> (Option<ObjectId>, Option<ObjectId>)>,
    }

    let cells: Vec<Cell> = vec![
        // ── Cells 1-4: NEW target served+minted → Write (force-retarget) ──
        // Cell 1: existing absent, full scope → materialize a fresh tag.
        Cell {
            label: "served_minted_existing_absent_full_creates",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let oid_a = test_support::mapping(&bridge)
                    .get_git(&a.change_id)
                    .expect("A minted");
                (matrix_mirror_tag(&bridge, "v"), Some(oid_a))
            }),
        },
        // Cell 2: existing SERVED, full scope, retarget served→served → force-move.
        Cell {
            label: "served_minted_existing_served_full_retargets",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                let b = matrix_put_state(&repo, b"B\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .set_thread(&ThreadName::new("rel"), &b.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let oid_b = test_support::mapping(&bridge)
                    .get_git(&b.change_id)
                    .expect("B minted");
                repo.refs().delete_marker(&MarkerName::new("v")).unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &b.change_id)
                    .unwrap();
                export_all(&mut bridge).unwrap();
                (matrix_mirror_tag(&bridge, "v"), Some(oid_b))
            }),
        },
        // Cell 3: existing EMBARGOED, full scope, retarget to a served+minted
        // INDEPENDENT root → force-move off the embargoed OID onto the new target.
        Cell {
            label: "served_minted_existing_embargoed_full_retargets",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                let b = matrix_put_state(&repo, b"B\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .set_thread(&ThreadName::new("rel"), &b.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let oid_b = test_support::mapping(&bridge)
                    .get_git(&b.change_id)
                    .expect("B minted");
                matrix_embargo(&repo, a.change_id);
                repo.refs().delete_marker(&MarkerName::new("v")).unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &b.change_id)
                    .unwrap();
                export_all(&mut bridge).unwrap();
                (matrix_mirror_tag(&bridge, "v"), Some(oid_b))
            }),
        },
        // Cell 4: existing == new target → idempotent Write (no-op move).
        Cell {
            label: "served_minted_existing_same_idempotent",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let oid_a = test_support::mapping(&bridge)
                    .get_git(&a.change_id)
                    .expect("A minted");
                export_all(&mut bridge).unwrap();
                (matrix_mirror_tag(&bridge, "v"), Some(oid_a))
            }),
        },
        // Cell 5: served+minted target, existing absent, SCOPED → skip-materialize
        // (a scoped export does not publish a brand-new tag the caller didn't ask for).
        Cell {
            label: "served_minted_existing_absent_scoped_skips",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                let b = matrix_put_state(&repo, b"B\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("alpha"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .set_thread(&ThreadName::new("beta"), &b.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &b.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_current_thread(&mut bridge, "beta").unwrap();
                (matrix_mirror_tag(&bridge, "v"), None)
            }),
        },
        // ── Cell 6 (r18): served-but-unminted target, existing SERVED → PRESERVE ──
        Cell {
            label: "served_unminted_existing_served_scoped_preserves",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                let b = matrix_put_state(&repo, b"B\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("alpha"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .set_thread(&ThreadName::new("beta"), &b.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &b.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let oid_b = test_support::mapping(&bridge)
                    .get_git(&b.change_id)
                    .expect("B minted");
                // Advance beta to a NEW public state C and retarget v→C; C is never
                // exported, so it stays unminted and the scoped run takes the
                // served-but-unminted path.
                let c = matrix_put_state(&repo, b"C\n", vec![b.change_id]);
                repo.refs()
                    .set_thread(&ThreadName::new("beta"), &c.change_id)
                    .unwrap();
                repo.refs().delete_marker(&MarkerName::new("v")).unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &c.change_id)
                    .unwrap();
                export_current_thread(&mut bridge, "alpha").unwrap();
                (matrix_mirror_tag(&bridge, "v"), Some(oid_b))
            }),
        },
        // ── Cell 7 (r19 FIX): served-but-unminted target, existing EMBARGOED → DELETE ──
        // The named row: the existing tag points at a commit this run embargoed, so
        // PRESERVE would keep serving it. PRESERVE requires existing_served.
        Cell {
            label: "existing_embargoed_unminted_new_deletes_tag",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                let p = matrix_put_state(&repo, b"P\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("alpha"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .set_thread(&ThreadName::new("rel"), &p.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &p.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                // New, never-exported public state C → served-but-unminted in the
                // scoped run. Embargo P (still reachable via `rel`) so the EXISTING
                // tag's tip enters `embargoed_oids`. Retarget v→C.
                let c = matrix_put_state(&repo, b"C\n", Vec::new());
                matrix_embargo(&repo, p.change_id);
                repo.refs().delete_marker(&MarkerName::new("v")).unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &c.change_id)
                    .unwrap();
                export_current_thread(&mut bridge, "alpha").unwrap();
                (matrix_mirror_tag(&bridge, "v"), None)
            }),
        },
        // Cell 8: served-but-unminted target, existing absent, scoped → no-op.
        Cell {
            label: "served_unminted_existing_absent_scoped_noop",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                let c = matrix_put_state(&repo, b"C\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("alpha"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &c.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_current_thread(&mut bridge, "alpha").unwrap();
                (matrix_mirror_tag(&bridge, "v"), None)
            }),
        },
        // ── Cells 9-11: NEW target genuinely UNSERVED → DELETE ──
        // Cell 9: existing SERVED, retargeted to a Private state (subsumes the
        // locked-in `export_deletes_tag_when_marker_retargeted_to_private`).
        Cell {
            label: "unserved_existing_served_full_deletes",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let b = matrix_put_state(&repo, b"B\n", Vec::new());
                matrix_embargo(&repo, b.change_id);
                repo.refs().delete_marker(&MarkerName::new("v")).unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &b.change_id)
                    .unwrap();
                export_all(&mut bridge).unwrap();
                (matrix_mirror_tag(&bridge, "v"), None)
            }),
        },
        // Cell 10: existing EMBARGOED, target itself embargoed (the original r1
        // embargo retraction).
        Cell {
            label: "unserved_existing_embargoed_full_deletes",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                matrix_embargo(&repo, a.change_id);
                export_all(&mut bridge).unwrap();
                (matrix_mirror_tag(&bridge, "v"), None)
            }),
        },
        // Cell 11: existing absent, target unserved → DELETE is a no-op.
        Cell {
            label: "unserved_existing_absent_noop_delete",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                let b = matrix_put_state(&repo, b"B\n", Vec::new());
                matrix_embargo(&repo, b.change_id);
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &b.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                (matrix_mirror_tag(&bridge, "v"), None)
            }),
        },
        // ── Cells 12-13 (S3): the marker was DELETED → its stale tag must go ──
        // Cell 12: existing tag present, marker deleted — reached via the
        // existing-tags side of the union (markers no longer carries it).
        Cell {
            label: "deleted_marker_stale_tag_deleted",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                repo.refs().delete_marker(&MarkerName::new("v")).unwrap();
                export_all(&mut bridge).unwrap();
                (matrix_mirror_tag(&bridge, "v"), None)
            }),
        },
        // Cell 13: neither a marker nor an existing tag — structurally never visited
        // by the `markers ∪ existing-tags` union (a no-op by construction).
        Cell {
            label: "notarget_existing_absent_unvisited",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                (matrix_mirror_tag(&bridge, "ghost"), None)
            }),
        },
        // ── P1 regression guard: PRIOR-RUN embargo (not this run's purge) ──
        // The existing tag's target P was embargoed in a PRIOR run and is out of
        // THIS scoped run's purge reach (P is unreachable from every current frontier
        // root). Classifying the existing tip by THIS run's purge drop-set (the bug)
        // reads P as served → cell-6 PRESERVE → keeps serving embargoed P.
        // Classifying by the whole-mirror served-OID set reads P as UNSERVED → cell-7
        // DELETE. The new target is served-but-unminted (the ONLY path that reads the
        // existing tag's served axis).
        Cell {
            label: "prior_run_embargo_existing_tag_deletes",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let p = matrix_put_state(&repo, b"P\n", Vec::new());
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &p.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                // Run 1 mints P (every store state is minted by export_all) and
                // materializes the mirror tag v → P.
                export_all(&mut bridge).unwrap();
                // PRIOR-run embargo of P. Retarget v to a fresh public-but-unminted C
                // and export ONLY `alpha` — P is now unreachable from the scoped
                // frontier (no thread/marker reaches it), so it is NOT in this run's
                // purge drop-set, yet v's existing tag still points at P's OID.
                matrix_embargo(&repo, p.change_id);
                let alpha = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("alpha"), &alpha.change_id)
                    .unwrap();
                let c = matrix_put_state(&repo, b"C\n", Vec::new());
                repo.refs().delete_marker(&MarkerName::new("v")).unwrap();
                repo.refs()
                    .create_marker(&MarkerName::new("v"), &c.change_id)
                    .unwrap();
                export_current_thread(&mut bridge, "alpha").unwrap();
                (matrix_mirror_tag(&bridge, "v"), None)
            }),
        },
        // ── foreign Git tag preserved: a mirror tag heddle never exported ──
        // A user's own `refs/tags/user-v1`, pointing at a commit heddle never minted,
        // with NO marker. The reconcile's NoTarget arm would DELETE it unless the
        // heddle-managed-ref filter spares it (a foreign tag is left untouched).
        Cell {
            label: "foreign_unmanaged_git_tag_preserved",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                // Plant a FOREIGN tag in the mirror: a commit heddle never minted,
                // tagged under a name heddle never exported.
                let mirror = test_support::open_git_repo(&bridge).unwrap();
                let foreign =
                    commit_with_tree(&mirror, None, empty_tree_oid(&mirror), "foreign", &[]);
                set_reference(
                    &mirror,
                    "refs/tags/user-v1",
                    foreign,
                    RefPrecondition::MustNotExist,
                    "test: foreign tag",
                )
                .unwrap();
                export_all(&mut bridge).unwrap();
                (matrix_mirror_tag(&bridge, "user-v1"), Some(foreign))
            }),
        },
        // ── foreign tag AT A HEDDLE OID (the r20c bug) — spared AND excluded ──
        // A foreign `refs/tags/user-v1` pointing at a commit heddle MINTED. The
        // OBSOLETE OID-based ownership classified this as heddle's (its tip is a
        // minted commit) → folded into the reconcile → deleted. The NAME-keyed
        // record spares it (the name was never recorded as written), AND the
        // managed-filtered push frontier excludes it.
        Cell {
            label: "foreign_tag_at_heddle_oid_spared_and_excluded",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let oid_a = test_support::mapping(&bridge)
                    .get_git(&a.change_id)
                    .expect("A minted");
                // Plant the foreign tag at the heddle-minted OID, AFTER the first
                // export so the managed record already exists (the name is not in it).
                matrix_plant_foreign_tag(&bridge, "user-v1", oid_a);
                export_all(&mut bridge).unwrap();
                assert!(
                    !matrix_in_managed_frontier(&bridge, "user-v1", RefNamespace::Tag),
                    "a foreign tag at a heddle OID must be EXCLUDED from the managed push frontier"
                );
                (matrix_mirror_tag(&bridge, "user-v1"), Some(oid_a))
            }),
        },
    ];

    for cell in &cells {
        let (observed, expected) = (cell.run)();
        assert_eq!(observed, expected, "tag cell `{}`", cell.label);
    }
}

/// #316 / PR #528 S2 — the head reconcile has NO existing-embargo PRESERVE path,
/// the asymmetry vs the tag reconcile (where a served-but-unminted tag at a still
/// SERVED tip IS preserved, cell 6). A head's published target is recomputed every
/// run as `frontier_git_oid` — the maximal SERVED ancestor-or-self of the thread
/// tip — so a head can never keep serving an embargoed tip: it is REWOUND to the
/// served frontier, or DELETED when no served frontier remains. Each embargo row
/// asserts the resulting `refs/heads/main` tip is the served frontier and NEVER the
/// embargoed OID.
#[test]
fn head_reconcile_conformance_matrix() {
    struct HeadOutcome {
        observed: Option<ObjectId>,
        expected: Option<ObjectId>,
        /// The embargoed OID the head must NEVER be left at (`None` when no embargo).
        forbidden: Option<ObjectId>,
    }
    struct Cell {
        label: &'static str,
        run: Box<dyn Fn() -> HeadOutcome>,
    }

    let cells: Vec<Cell> = vec![
        // Control: a plain public advance fast-forwards the head.
        Cell {
            label: "public_advance_fast_forwards",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let b = matrix_put_state(&repo, b"B\n", vec![a.change_id]);
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &b.change_id)
                    .unwrap();
                export_all(&mut bridge).unwrap();
                let oid_b = test_support::mapping(&bridge)
                    .get_git(&b.change_id)
                    .expect("B minted");
                HeadOutcome {
                    observed: matrix_mirror_head(&bridge, "main"),
                    expected: Some(oid_b),
                    forbidden: None,
                }
            }),
        },
        // KEY: an embargoed TIP rewinds the head to the served ancestor — the head
        // is NEVER preserved at the embargoed tip (the tag-cell-7 bug has no head dual).
        Cell {
            label: "embargoed_tip_rewinds_to_served_ancestor",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                let b = matrix_put_state(&repo, b"B\n", vec![a.change_id]);
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &b.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let oid_a = test_support::mapping(&bridge)
                    .get_git(&a.change_id)
                    .expect("A minted");
                let oid_b = test_support::mapping(&bridge)
                    .get_git(&b.change_id)
                    .expect("B minted");
                matrix_embargo(&repo, b.change_id);
                export_all(&mut bridge).unwrap();
                HeadOutcome {
                    observed: matrix_mirror_head(&bridge, "main"),
                    expected: Some(oid_a),
                    forbidden: Some(oid_b),
                }
            }),
        },
        // KEY: the WHOLE line embargoed DELETES the head — no preserve path at all.
        Cell {
            label: "embargoed_whole_line_deletes_head",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let oid_a = test_support::mapping(&bridge)
                    .get_git(&a.change_id)
                    .expect("A minted");
                matrix_embargo(&repo, a.change_id);
                export_all(&mut bridge).unwrap();
                HeadOutcome {
                    observed: matrix_mirror_head(&bridge, "main"),
                    expected: None,
                    forbidden: Some(oid_a),
                }
            }),
        },
        // P1 regression guard (head dual): a SCOPED export whose existing head tip
        // was embargoed in a PRIOR run — and is out of THIS run's purge reach
        // (unreachable from the scoped frontier) — must RETRACT (force-rewind) to the
        // served ancestor, not classify the embargoed tip as served. Classifying by
        // this run's purge drop-set (the bug) reads B as served → FF-guarded sync →
        // a NonFastForward error on the rewind; classifying by the whole-mirror
        // served-OID set reads B as unserved → force-rewind to A.
        Cell {
            label: "prior_run_embargoed_existing_head_retracts",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                let b = matrix_put_state(&repo, b"B\n", vec![a.change_id]);
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &b.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let oid_a = test_support::mapping(&bridge)
                    .get_git(&a.change_id)
                    .expect("A minted");
                let oid_b = test_support::mapping(&bridge)
                    .get_git(&b.change_id)
                    .expect("B minted");
                // Embargo the published tip B, rewind main to its served ancestor A,
                // and export ONLY main (scoped). B is now unreachable from the scoped
                // frontier, so it is NOT in this run's purge drop-set — only the
                // served-OID classification rewinds the head off B.
                matrix_embargo(&repo, b.change_id);
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                export_current_thread(&mut bridge, "main").unwrap();
                HeadOutcome {
                    observed: matrix_mirror_head(&bridge, "main"),
                    expected: Some(oid_a),
                    forbidden: Some(oid_b),
                }
            }),
        },
        // ── foreign BRANCH at a heddle OID — spared (the head dual of the tag) ──
        // A `refs/heads/user-feature` heddle never wrote, at a heddle-minted OID.
        // It is not a heddle thread, so the head reconcile (iterating current
        // threads) never visits it; the name-keyed record spares it, and the
        // managed-filtered push frontier excludes it.
        Cell {
            label: "foreign_branch_at_heddle_oid_spared",
            run: Box::new(|| {
                let temp = TempDir::new().unwrap();
                let repo = Repository::init(temp.path()).unwrap();
                let a = matrix_put_state(&repo, b"A\n", Vec::new());
                repo.refs()
                    .set_thread(&ThreadName::new("main"), &a.change_id)
                    .unwrap();
                let mut bridge = GitBridge::new(&repo);
                export_all(&mut bridge).unwrap();
                let oid_a = test_support::mapping(&bridge)
                    .get_git(&a.change_id)
                    .expect("A minted");
                matrix_plant_foreign_branch(&bridge, "user-feature", oid_a);
                export_all(&mut bridge).unwrap();
                assert!(
                    !matrix_in_managed_frontier(&bridge, "user-feature", RefNamespace::Branch),
                    "a foreign branch at a heddle OID must be EXCLUDED from the managed push frontier"
                );
                HeadOutcome {
                    observed: matrix_mirror_head(&bridge, "user-feature"),
                    expected: Some(oid_a),
                    forbidden: None,
                }
            }),
        },
    ];

    for cell in &cells {
        let out = (cell.run)();
        assert_eq!(out.observed, out.expected, "head cell `{}`", cell.label);
        if let Some(forbidden) = out.forbidden {
            assert_ne!(
                out.observed,
                Some(forbidden),
                "head cell `{}`: the head must NOT be left at the embargoed tip",
                cell.label
            );
        }
    }
}

/// #316 / PR #528 — the mirror's name-keyed managed-refs record is the ownership
/// boundary: every ref the reconcile WRITES is CLAIMED, every ref it DELETES is
/// DROPPED, and a foreign ref heddle never wrote NEVER enters — even one pointing
/// at a heddle-minted OID (the r20c bug the OID-based record produced).
#[test]
fn mirror_managed_record_claims_written_drops_deleted_excludes_foreign() {
    let temp = TempDir::new().unwrap();
    let repo = Repository::init(temp.path()).unwrap();
    let a = matrix_put_state(&repo, b"A\n", Vec::new());
    repo.refs()
        .set_thread(&ThreadName::new("main"), &a.change_id)
        .unwrap();
    repo.refs()
        .create_marker(&MarkerName::new("v"), &a.change_id)
        .unwrap();
    let mut bridge = GitBridge::new(&repo);
    export_all(&mut bridge).unwrap();

    // CLAIM: the written head and tag are recorded.
    let record = matrix_managed_record(&bridge);
    assert!(
        record.contains_key("refs/heads/main"),
        "written head claimed: {record:?}"
    );
    assert!(
        record.contains_key("refs/tags/v"),
        "written tag claimed: {record:?}"
    );

    // EXCLUDE FOREIGN: a foreign tag at a heddle OID never enters the record.
    let oid_a = test_support::mapping(&bridge)
        .get_git(&a.change_id)
        .expect("A minted");
    matrix_plant_foreign_tag(&bridge, "user-v1", oid_a);
    export_all(&mut bridge).unwrap();
    let record = matrix_managed_record(&bridge);
    assert!(
        !record.contains_key("refs/tags/user-v1"),
        "a foreign tag (even at a heddle OID) must never enter the record: {record:?}"
    );
    assert!(record.contains_key("refs/heads/main"), "{record:?}");

    // DROP: deleting the marker drops its tag from the record.
    repo.refs().delete_marker(&MarkerName::new("v")).unwrap();
    export_all(&mut bridge).unwrap();
    let record = matrix_managed_record(&bridge);
    assert!(
        !record.contains_key("refs/tags/v"),
        "a deleted marker's tag must drop from the record: {record:?}"
    );
}

/// #316 / PR #528 — the managed-refs record round-trips through its atomic
/// temp+rename write and the shared exported-refs parse contract.
#[test]
fn mirror_managed_record_survives_round_trip() {
    let temp = TempDir::new().unwrap();
    let mirror = SleyRepository::init_bare(temp.path()).unwrap();
    let main_tip = commit_with_tree(&mirror, None, empty_tree_oid(&mirror), "main", &[]);
    let tag_tip = commit_with_tree(&mirror, None, empty_tree_oid(&mirror), "tag", &[]);

    let mut record = std::collections::HashMap::new();
    record.insert("refs/heads/main".to_string(), main_tip);
    record.insert("refs/tags/v1.0".to_string(), tag_tip);
    write_mirror_managed_refs(&mirror, &record).expect("write record");

    let read_back = read_mirror_managed_refs(&mirror).expect("read record");
    assert_eq!(
        read_back, record,
        "managed record must round-trip byte-for-byte"
    );
}

/// #316 / PR #528 — the #1 first-run risk: the FIRST export after this code lands
/// finds NO managed record. If an absent record made every pre-existing ref look
/// foreign, embargo retraction would silently stop. Seeding the record from the
/// current mirror ref set keeps pre-existing heddle refs managed, so a stale tag
/// whose marker was already deleted IS still retracted on that first run. Without
/// seeding, the tag (not a current marker, not in an empty record) would never be
/// iterated and would survive — the leak this guards.
#[test]
fn first_export_after_upgrade_seeds_record_and_still_retracts() {
    let temp = TempDir::new().unwrap();
    let repo = Repository::init(temp.path()).unwrap();
    let a = matrix_put_state(&repo, b"A\n", Vec::new());
    let p = matrix_put_state(&repo, b"P\n", Vec::new());
    repo.refs()
        .set_thread(&ThreadName::new("main"), &a.change_id)
        .unwrap();
    repo.refs()
        .create_marker(&MarkerName::new("v"), &p.change_id)
        .unwrap();
    let mut bridge = GitBridge::new(&repo);
    export_all(&mut bridge).unwrap();
    assert!(
        matrix_mirror_tag(&bridge, "v").is_some(),
        "run 1 must publish the tag"
    );

    // Simulate the PRE-record state: delete the on-disk record so the next export
    // sees an absent record (as it would on the first run after this lands).
    let record_path = {
        let mirror = test_support::open_git_repo(&bridge).unwrap();
        mirror.git_dir().join("heddle-mirror-managed-refs")
    };
    assert!(record_path.exists(), "run 1 must have written the record");
    std::fs::remove_file(&record_path).unwrap();

    // Delete the marker so `v` is no longer a current marker. Only the SEED (from
    // the current mirror ref set) makes `refs/tags/v` reachable by the reconcile.
    repo.refs().delete_marker(&MarkerName::new("v")).unwrap();
    export_all(&mut bridge).unwrap();

    assert_eq!(
        matrix_mirror_tag(&bridge, "v"),
        None,
        "the first post-upgrade export must retract the stale tag via record seeding"
    );
    assert!(
        record_path.exists(),
        "the export must (re)write the managed record"
    );
}

/// #316 / PR #528 r7 CLASS 2 (the leak): a branch exported to a real
/// DESTINATION while public, then retracted (whole line embargoed), must be
/// DELETED at the destination — not left pointing at now-private commits. The
/// mirror-side retraction already deletes the branch from the internal mirror;
/// the destination-sync step only ever WROTE the surviving refs and never
/// computed deletions, so the destination kept the stale branch. The
/// delete-set reconciliation closes that leak.
#[test]
fn export_propagates_branch_deletion_to_destination() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    std::fs::write(heddle_temp.path().join("a.txt"), b"only\n").unwrap();
    repo.snapshot(Some("only".into()), None).unwrap();

    // Export to a real destination while public — the destination gets main.
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    let mut bridge = GitBridge::new(&repo);
    bridge.export_to_path(&dest_path).expect("first export");
    let dest = open_git(&dest_path).expect("open dest");
    assert!(
        find_reference(&dest, "refs/heads/main").is_ok(),
        "destination must advertise main while the line is public"
    );

    // Embargo the WHOLE line — including the seeded root — so no served frontier
    // remains and the mirror deletes refs/heads/main.
    for state in repo.store().list_states().unwrap() {
        repo.put_state_visibility(StateVisibility {
            state,
            tier: VisibilityTier::Private {
                scope_label: "sec-embargo".into(),
            },
            embargo_until: None,
            declarer: Principal {
                name: "Grace Hopper".into(),
                email: "grace@example.com".into(),
            },
            declared_at: Utc::now(),
            signature: None,
            supersedes: None,
        })
        .unwrap();
    }

    // Re-export to the SAME destination: the stale branch must be DELETED there.
    bridge.export_to_path(&dest_path).expect("second export");
    let dest = open_git(&dest_path).expect("reopen dest");
    assert!(
        find_reference(&dest, "refs/heads/main").is_err(),
        "retracting the line must DELETE refs/heads/main at the destination, not leave it serving now-private commits"
    );
}

/// #316 / PR #528 r7 CLASS 2: the delete-set covers TAGS and the NOTES
/// namespace too, so it is not a heads-only fix. A marker tag retracted from
/// the mirror must be deleted at the destination; a stale heddle-managed notes
/// ref absent from the served mirror must be deleted; and the embargoed
/// commit's note ENTRY must no longer be readable at the destination.
#[test]
fn export_propagates_tag_and_note_deletion() {
    use chrono::Utc;
    use objects::object::{Attribution, Principal, State, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    // A public state on main that stays public throughout — so main never
    // rewinds (a rewind would trip the export's fast-forward guard, a separate
    // concern from this test).
    std::fs::write(heddle_temp.path().join("main.txt"), b"trunk\n").unwrap();
    repo.snapshot(Some("trunk".into()), None).unwrap();

    // A SEPARATE public state R, pinned by marker v1.0 and independent of main,
    // so embargoing it later deletes the tag and retracts its note without
    // touching main's tip.
    let r = {
        let store = repo.store();
        let blob = store
            .put_blob(&Blob::from_slice(b"release\n"))
            .expect("blob");
        let tree = store
            .put_tree(&Tree::from_entries(vec![
                TreeEntry::file("release.txt".to_string(), blob, false).expect("entry"),
            ]))
            .expect("tree");
        let state = State::new(
            tree,
            Vec::new(),
            Attribution::human(Principal::new("Grace Hopper", "grace@example.com")),
        );
        store.put_state(&state).expect("put R");
        state
    };
    repo.refs()
        .create_marker(&MarkerName::new("v1.0"), &r.change_id)
        .expect("create marker at R");

    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    let mut bridge = GitBridge::new(&repo);
    bridge.export_to_path(&dest_path).expect("first export");
    let oid_r = test_support::mapping(&bridge)
        .get_git(&r.change_id)
        .expect("R minted");

    {
        let dest = open_git(&dest_path).expect("open dest");
        assert!(
            find_reference(&dest, "refs/tags/v1.0").is_ok(),
            "destination must have the tag while public"
        );
        assert!(
            cli::bridge::git_notes::read_note(&dest, oid_r)
                .unwrap()
                .is_some(),
            "destination must carry R's note while public"
        );
        // Plant a stale notes ref the served mirror will never have, to exercise
        // the NOTES namespace of the delete-set directly. r8 HOLE 2: the
        // delete-set is now scoped to refs heddle PREVIOUSLY EXPORTED here (not
        // the raw destination namespace), so record this ref as exported —
        // mirroring a real "heddle exported it, mirror later stopped serving it"
        // retraction. Without the record it would (correctly) be treated as a
        // foreign ref and survive.
        set_reference(
            &dest,
            "refs/notes/legacy",
            oid_r,
            RefPrecondition::Any,
            "test: stale heddle-exported notes ref",
        )
        .expect("plant stale notes ref");
        let mut exported = read_exported_refs(&dest).expect("read exported-refs record");
        exported.insert("refs/notes/legacy".to_string(), oid_r);
        write_exported_refs(&dest, &exported).expect("record legacy as heddle-exported");
    }

    // Embargo R → the mirror deletes the tag and retracts R's note entry. main
    // is independent of R, so it is untouched (no rewind).
    repo.put_state_visibility(StateVisibility {
        state: r.change_id,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Grace Hopper".into(),
            email: "grace@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();

    bridge.export_to_path(&dest_path).expect("second export");

    let dest = open_git(&dest_path).expect("reopen dest");
    assert!(
        find_reference(&dest, "refs/tags/v1.0").is_err(),
        "retracting the marker must DELETE refs/tags/v1.0 at the destination"
    );
    assert!(
        find_reference(&dest, "refs/notes/legacy").is_err(),
        "a stale heddle-managed notes ref absent from the served mirror must be DELETED at the destination"
    );
    assert!(
        cli::bridge::git_notes::read_note(&dest, oid_r)
            .unwrap()
            .is_none(),
        "the embargoed commit's note must no longer be readable at the destination"
    );
    assert!(
        find_reference(&dest, "refs/heads/main").is_ok(),
        "the still-public main branch must survive the reconciliation"
    );
}

/// #316 / PR #528 r7 CLASS 2: the delete-set is scoped strictly to the
/// heddle-managed namespaces (`refs/heads/*`, `refs/tags/*`, `refs/notes/*`).
/// A ref the destination holds OUTSIDE those namespaces is foreign — heddle
/// does not own it — and must be left untouched by the reconciliation. Refs
/// that ARE still served must also survive.
#[test]
fn export_does_not_delete_foreign_refs() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    std::fs::write(heddle_temp.path().join("a.txt"), b"only\n").unwrap();
    repo.snapshot(Some("only".into()), None).unwrap();
    let state_a = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();

    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    let mut bridge = GitBridge::new(&repo);
    bridge.export_to_path(&dest_path).expect("first export");
    let oid_a = test_support::mapping(&bridge)
        .get_git(&state_a)
        .expect("A minted");

    // Plant a foreign ref in a namespace heddle does not manage.
    {
        let dest = open_git(&dest_path).expect("open dest");
        set_reference(
            &dest,
            "refs/keep/backup",
            oid_a,
            RefPrecondition::Any,
            "test: foreign ref heddle does not own",
        )
        .expect("plant foreign ref");
    }

    // Re-export with nothing retracted (main still public).
    bridge.export_to_path(&dest_path).expect("second export");

    let dest = open_git(&dest_path).expect("reopen dest");
    assert!(
        find_reference(&dest, "refs/keep/backup").is_ok(),
        "a foreign ref outside heddle-managed namespaces must be left untouched"
    );
    assert!(
        find_reference(&dest, "refs/heads/main").is_ok(),
        "a still-served heddle branch must survive the reconciliation"
    );
}

/// #316 / PR #528 r8 HOLE 2 (the data-loss): a destination ref INSIDE the
/// heddle-managed namespaces (`refs/heads/*`) that heddle NEVER exported — e.g.
/// a branch another user or tool created on a shared local bare remote — must
/// survive a normal export/push. r7 diffed the whole destination namespace and so
/// DELETED such a foreign branch; scoping the delete-set to refs heddle actually
/// exported (recorded per destination) leaves it intact. The r7 foreign-ref test
/// only escaped this bug by planting OUTSIDE heads/tags/notes.
#[test]
fn export_does_not_delete_foreign_managed_ref() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    std::fs::write(heddle_temp.path().join("a.txt"), b"only\n").unwrap();
    repo.snapshot(Some("only".into()), None).unwrap();
    let state_a = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();

    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    let mut bridge = GitBridge::new(&repo);
    bridge.export_to_path(&dest_path).expect("first export");
    let oid_a = test_support::mapping(&bridge)
        .get_git(&state_a)
        .expect("A minted");

    // Plant a branch heddle never exported, INSIDE the heddle-managed
    // `refs/heads/*` namespace — the namespace r7 over-deleted from.
    {
        let dest = open_git(&dest_path).expect("open dest");
        set_reference(
            &dest,
            "refs/heads/other-user-branch",
            oid_a,
            RefPrecondition::Any,
            "test: foreign branch heddle never exported",
        )
        .expect("plant foreign managed ref");
    }

    // Re-export with nothing retracted (main still public).
    bridge.export_to_path(&dest_path).expect("second export");

    let dest = open_git(&dest_path).expect("reopen dest");
    assert!(
        find_reference(&dest, "refs/heads/other-user-branch").is_ok(),
        "a foreign branch heddle never exported must NOT be deleted by a normal push"
    );
    assert!(
        find_reference(&dest, "refs/heads/main").is_ok(),
        "a still-served heddle branch must survive the reconciliation"
    );
}

/// #316 / PR #528 r8 HOLE 2 (regression guard): scoping the delete-set to
/// heddle-exported refs must NOT break the genuine retraction path. A branch
/// heddle exported while public, then retracted (whole line embargoed so the
/// served mirror drops it), must STILL be DELETED at the destination — it is in
/// the per-destination exported-refs record and absent from the served mirror,
/// so it lands in the delete-set. Preserves the r7 behavior the HOLE 2 fix must
/// not regress.
#[test]
fn export_still_deletes_previously_exported_then_retracted_ref() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    std::fs::write(heddle_temp.path().join("a.txt"), b"only\n").unwrap();
    repo.snapshot(Some("only".into()), None).unwrap();

    // Export to a real destination while public — heddle records main as exported.
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    let mut bridge = GitBridge::new(&repo);
    bridge.export_to_path(&dest_path).expect("first export");
    let dest = open_git(&dest_path).expect("open dest");
    assert!(
        find_reference(&dest, "refs/heads/main").is_ok(),
        "destination must advertise main while the line is public"
    );

    // Embargo the WHOLE line so the mirror stops serving refs/heads/main.
    for state in repo.store().list_states().unwrap() {
        repo.put_state_visibility(StateVisibility {
            state,
            tier: VisibilityTier::Private {
                scope_label: "sec-embargo".into(),
            },
            embargo_until: None,
            declarer: Principal {
                name: "Grace Hopper".into(),
                email: "grace@example.com".into(),
            },
            declared_at: Utc::now(),
            signature: None,
            supersedes: None,
        })
        .unwrap();
    }

    // Re-export: main was heddle-exported AND is no longer served → DELETED.
    bridge.export_to_path(&dest_path).expect("second export");
    let dest = open_git(&dest_path).expect("reopen dest");
    assert!(
        find_reference(&dest, "refs/heads/main").is_err(),
        "a previously-exported, now-retracted branch must be DELETED at the destination"
    );
}

/// #316 / PR #528 r11 Finding HcDQU: the retraction delete-set must propagate to
/// URL/NETWORK remotes too, not only local-path destinations. A branch exported
/// public over the `git://` push path and then retracted (whole line embargoed)
/// must be DELETED on the wire remote — pre-r11 the URL push only sent additive
/// updates, so a retracted ref lingered on the remote after vanishing locally.
/// Uses the real network receive-pack path (`push_network_remote_with_updates`),
/// NOT `copy_mirror_to_path_with_updates`.
#[test]
fn retraction_delete_propagates_to_url_remote() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    std::fs::write(heddle_temp.path().join("a.txt"), b"only\n").unwrap();
    repo.snapshot(Some("only".into()), None).unwrap();

    // A real wire (git://) remote that also serves receive-pack.
    let remote_root = TempDir::new().expect("remote root");
    let _remote_repo = init_named_bare_git_repo(&remote_root, "remote.git");
    // Point the bare remote's HEAD at a placeholder branch so receive-pack does
    // not refuse to delete refs/heads/main later as "the current branch".
    std::fs::write(
        remote_root.path().join("remote.git").join("HEAD"),
        b"ref: refs/heads/__heddle_placeholder\n",
    )
    .unwrap();
    let Some(daemon) = GitDaemon::spawn_push(remote_root.path()) else {
        return;
    };
    let url = daemon.url("remote.git");

    // Export public over the NETWORK push path — main lands on the remote.
    let mut bridge = GitBridge::new(&repo);
    bridge.push(&url).expect("first network push");
    {
        let remote = open_git(remote_root.path().join("remote.git")).expect("open remote");
        assert!(
            find_reference(&remote, "refs/heads/main").is_ok(),
            "the remote must advertise main while the line is public"
        );
    }

    // Embargo the WHOLE line so the served mirror stops serving refs/heads/main.
    for state in repo.store().list_states().unwrap() {
        repo.put_state_visibility(StateVisibility {
            state,
            tier: VisibilityTier::Private {
                scope_label: "sec-embargo".into(),
            },
            embargo_until: None,
            declarer: Principal {
                name: "Grace Hopper".into(),
                email: "grace@example.com".into(),
            },
            declared_at: Utc::now(),
            signature: None,
            supersedes: None,
        })
        .unwrap();
    }

    // Re-push: main was heddle-exported AND is no longer served → DELETED on the
    // wire remote, not just locally.
    bridge.push(&url).expect("second network push");
    let remote = open_git(remote_root.path().join("remote.git")).expect("reopen remote");
    assert!(
        find_reference(&remote, "refs/heads/main").is_err(),
        "a previously-exported, now-retracted branch must be DELETED on the URL/network remote"
    );
}

/// #316 / PR #528 r11 Finding HcDQO: a destination push must FORCE a deliberate
/// embargo rewind. When a previously-exported tip B is embargoed but parent A
/// stays served, the served frontier lags the branch back to A — a non-fast-
/// forward rewind. Pre-r11 the local-path push ran a blanket FF guard that
/// REJECTED it, so the destination kept advertising the embargoed B. The unified
/// reconciliation distinguishes a backward rewind from a fork and forces the
/// former through.
#[test]
fn embargo_rewind_forced_through_destination_push() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    // Linear thread: public base A, then public tip B.
    std::fs::write(heddle_temp.path().join("a.txt"), b"base\n").unwrap();
    repo.snapshot(Some("base".into()), None).unwrap();
    let state_a = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();
    std::fs::write(heddle_temp.path().join("b.txt"), b"fix\n").unwrap();
    repo.snapshot(Some("fix".into()), None).unwrap();
    let state_b = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();

    // First export to a real bare destination — main advertises the public tip B.
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    let mut bridge = GitBridge::new(&repo);
    bridge.export_to_path(&dest_path).expect("first export");
    let oid_a = test_support::mapping(&bridge)
        .get_git(&state_a)
        .expect("A minted");
    let oid_b = test_support::mapping(&bridge)
        .get_git(&state_b)
        .expect("B minted");
    {
        let dest = open_git(&dest_path).expect("open dest");
        let tip = find_reference(&dest, "refs/heads/main")
            .unwrap()
            .peel_to_id()
            .unwrap();
        assert_eq!(tip, oid_b, "destination advertises the public tip B");
    }

    // Embargo only B; parent A stays served.
    repo.put_state_visibility(StateVisibility {
        state: state_b,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Grace Hopper".into(),
            email: "grace@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();

    // Re-export: the served frontier lags to A — a deliberate NON-fast-forward
    // rewind the destination push must FORCE through, not reject with the FF
    // guard. Pre-r11 this errored.
    bridge
        .export_to_path(&dest_path)
        .expect("second export must force the embargo rewind through the destination");
    let dest = open_git(&dest_path).expect("reopen dest");
    let tip = find_reference(&dest, "refs/heads/main")
        .unwrap()
        .peel_to_id()
        .unwrap();
    assert_eq!(
        tip, oid_a,
        "the destination branch must be rewound to the served ancestor A"
    );
    assert_ne!(
        tip, oid_b,
        "the destination must not keep advertising the embargoed tip B"
    );
}

/// #316 / PR #528 r11: the r8 foreign-ref scoping must hold on the UNIFIED
/// URL/network path. A branch INSIDE `refs/heads/*` that heddle never exported —
/// planted directly on the wire remote by another user/tool — must survive a
/// normal push: it is not in heddle's per-remote exported-refs record, so it can
/// never join the delete-set.
#[test]
fn foreign_ref_on_url_remote_survives() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    std::fs::write(heddle_temp.path().join("a.txt"), b"only\n").unwrap();
    repo.snapshot(Some("only".into()), None).unwrap();

    let remote_root = TempDir::new().expect("remote root");
    let _remote_repo = init_named_bare_git_repo(&remote_root, "remote.git");
    let Some(daemon) = GitDaemon::spawn_push(remote_root.path()) else {
        return;
    };
    let url = daemon.url("remote.git");

    // First public push — records main as heddle-exported to THIS url remote.
    let mut bridge = GitBridge::new(&repo);
    bridge.push(&url).expect("first network push");

    // Plant a branch heddle never exported, INSIDE the heddle-managed
    // refs/heads/* namespace, directly on the remote.
    {
        let remote = open_git(remote_root.path().join("remote.git")).expect("open remote");
        let main_oid = find_reference(&remote, "refs/heads/main")
            .unwrap()
            .peel_to_id()
            .unwrap();
        set_reference(
            &remote,
            "refs/heads/other-user-branch",
            main_oid,
            RefPrecondition::Any,
            "test: foreign branch heddle never exported",
        )
        .expect("plant foreign managed ref");
    }

    // Re-push with nothing retracted — the foreign branch must survive (the r8
    // delete-set scoping holds on the unified URL/network path).
    bridge.push(&url).expect("second network push");

    let remote = open_git(remote_root.path().join("remote.git")).expect("reopen remote");
    assert!(
        find_reference(&remote, "refs/heads/other-user-branch").is_ok(),
        "a foreign branch heddle never exported must NOT be deleted on the URL/network remote"
    );
    assert!(
        find_reference(&remote, "refs/heads/main").is_ok(),
        "a still-served heddle branch must survive the reconciliation"
    );
}

/// #316 / PR #528 r12: a destination tip advanced OUT OF BAND past heddle's
/// last-published tip — a descendant of the served frontier that heddle never
/// published, then fetched into the mirror — must NOT be force-overwritten. r11
/// treated ANY `old`-descends-from-`new` topology as a heddle-owned embargo
/// rewind and forced it, clobbering the remote's newer linear commit (data
/// loss). The force is now gated on heddle-OWNERSHIP (the exported-refs record):
/// an out-of-band descendant is `Diverged` — FF-rejected unless `--force` — so
/// the destination's newer commit survives. Covers local-path AND URL/network.
#[test]
fn out_of_band_destination_descendant_not_force_overwritten() {
    use cli::bridge::git_core::GitBridgeError;

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    // A single public tip B heddle publishes to its destinations.
    std::fs::write(heddle_temp.path().join("a.txt"), b"base\n").unwrap();
    repo.snapshot(Some("base".into()), None).unwrap();
    std::fs::write(heddle_temp.path().join("b.txt"), b"fix\n").unwrap();
    repo.snapshot(Some("fix".into()), None).unwrap();
    let state_b = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();

    let mut bridge = GitBridge::new(&repo);

    // ---- local-path destination ----
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    bridge
        .export_to_path(&dest_path)
        .expect("first export publishes B (local)");
    let oid_b = test_support::mapping(&bridge)
        .get_git(&state_b)
        .expect("B minted");

    // Out-of-band advance: a NEW commit C on top of B, written to BOTH the mirror
    // (the user fetched it, so it is a resolvable descendant of the served
    // frontier — the exact topology that fooled r11) AND the destination (its
    // branch moves to C). Identical inputs ⇒ identical oid in both repos.
    let oid_c = {
        let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
        let in_mirror = commit_with_tree(
            &mirror,
            None,
            empty_tree_oid(&mirror),
            "out-of-band",
            &[oid_b],
        );
        let dest = open_git(&dest_path).expect("open dest");
        let in_dest = commit_with_tree(
            &dest,
            Some("refs/heads/main"),
            empty_tree_oid(&dest),
            "out-of-band",
            &[oid_b],
        );
        assert_eq!(
            in_mirror, in_dest,
            "C must be the same commit in mirror and destination"
        );
        in_mirror
    };

    // A plain export must NOT clobber C: heddle never published it, so the move is
    // Diverged (FF-rejected), not a heddle-owned rewind.
    let err = bridge.export_to_path(&dest_path).expect_err(
        "out-of-band descendant must be FF-rejected at the local destination, not force-overwritten",
    );
    assert!(
        matches!(err, GitBridgeError::NonFastForwardRef { .. }),
        "expected a non-fast-forward rejection, got: {err:?}"
    );
    {
        let dest = open_git(&dest_path).expect("reopen dest");
        let tip = find_reference(&dest, "refs/heads/main")
            .unwrap()
            .peel_to_id()
            .unwrap();
        assert_eq!(
            tip, oid_c,
            "the out-of-band commit must survive — heddle must not force-overwrite it"
        );
    }

    // `--force` is the explicit escape hatch: it DOES overwrite C back to B.
    bridge
        .push_with_scope_force(
            dest_path.to_str().expect("dest path"),
            GitPushScope::AllThreads,
            true,
        )
        .expect("--force overrides the FF guard at the local destination");
    {
        let dest = open_git(&dest_path).expect("reopen dest");
        let tip = find_reference(&dest, "refs/heads/main")
            .unwrap()
            .peel_to_id()
            .unwrap();
        assert_eq!(
            tip, oid_b,
            "--force rewinds the local destination to the served frontier B"
        );
    }

    // ---- URL/network destination ----
    let remote_root = TempDir::new().expect("remote root");
    let _remote_repo = init_named_bare_git_repo(&remote_root, "remote.git");
    let Some(daemon) = GitDaemon::spawn_push(remote_root.path()) else {
        return;
    };
    let url = daemon.url("remote.git");

    bridge.push(&url).expect("first network push publishes B");
    {
        let remote = open_git(remote_root.path().join("remote.git")).expect("open remote");
        let tip = find_reference(&remote, "refs/heads/main")
            .unwrap()
            .peel_to_id()
            .unwrap();
        assert_eq!(tip, oid_b, "remote advertises the published tip B");
    }

    // Out-of-band advance on the wire remote to the SAME C (already in the mirror).
    {
        let remote = open_git(remote_root.path().join("remote.git")).expect("open remote");
        let in_remote = commit_with_tree(
            &remote,
            Some("refs/heads/main"),
            empty_tree_oid(&remote),
            "out-of-band",
            &[oid_b],
        );
        assert_eq!(
            in_remote, oid_c,
            "C must be the same commit on the wire remote"
        );
    }

    // Plain network push must likewise refuse to clobber C.
    let err = bridge
        .push(&url)
        .expect_err("out-of-band descendant must be FF-rejected on the URL/network remote too");
    assert!(
        matches!(err, GitBridgeError::NonFastForwardRef { .. }),
        "expected a non-fast-forward rejection on the wire, got: {err:?}"
    );
    {
        let remote = open_git(remote_root.path().join("remote.git")).expect("reopen remote");
        let tip = find_reference(&remote, "refs/heads/main")
            .unwrap()
            .peel_to_id()
            .unwrap();
        assert_eq!(
            tip, oid_c,
            "the out-of-band commit must survive on the URL/network remote"
        );
    }
}

/// #316 / PR #528 r12: the r11 behavior is PRESERVED — a tip heddle ITSELF
/// published, then embargoed, IS force-rewound to the served frontier at every
/// destination. The r12 ownership gate authorizes the force precisely because the
/// destination tip equals heddle's recorded published tip; only out-of-band tips
/// heddle never published are spared (see
/// [`out_of_band_destination_descendant_not_force_overwritten`]). Covers
/// local-path AND URL/network.
#[test]
fn heddle_published_tip_embargo_rewind_still_forced() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    // Linear thread: public base A, then public tip B — both heddle-published.
    std::fs::write(heddle_temp.path().join("a.txt"), b"base\n").unwrap();
    repo.snapshot(Some("base".into()), None).unwrap();
    let state_a = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();
    std::fs::write(heddle_temp.path().join("b.txt"), b"fix\n").unwrap();
    repo.snapshot(Some("fix".into()), None).unwrap();
    let state_b = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();

    let mut bridge = GitBridge::new(&repo);

    // Publish B to BOTH a local-path destination and a URL/network remote.
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    bridge
        .export_to_path(&dest_path)
        .expect("first export publishes B (local)");

    let remote_root = TempDir::new().expect("remote root");
    let _remote_repo = init_named_bare_git_repo(&remote_root, "remote.git");
    let Some(daemon) = GitDaemon::spawn_push(remote_root.path()) else {
        return;
    };
    let url = daemon.url("remote.git");
    bridge.push(&url).expect("first network push publishes B");

    let oid_a = test_support::mapping(&bridge)
        .get_git(&state_a)
        .expect("A minted");
    let oid_b = test_support::mapping(&bridge)
        .get_git(&state_b)
        .expect("B minted");
    {
        let dest = open_git(&dest_path).expect("open dest");
        assert_eq!(
            find_reference(&dest, "refs/heads/main")
                .unwrap()
                .peel_to_id()
                .unwrap(),
            oid_b,
            "local destination advertises the published tip B"
        );
        let remote = open_git(remote_root.path().join("remote.git")).expect("open remote");
        assert_eq!(
            find_reference(&remote, "refs/heads/main")
                .unwrap()
                .peel_to_id()
                .unwrap(),
            oid_b,
            "remote advertises the published tip B"
        );
    }

    // Embargo only B; parent A stays served. The served frontier lags to A — a
    // deliberate heddle-OWNED rewind: the destination tip (B) equals heddle's
    // recorded published tip, so the force is authorized at every destination.
    repo.put_state_visibility(StateVisibility {
        state: state_b,
        tier: VisibilityTier::Private {
            scope_label: "sec-embargo".into(),
        },
        embargo_until: None,
        declarer: Principal {
            name: "Grace Hopper".into(),
            email: "grace@example.com".into(),
        },
        declared_at: Utc::now(),
        signature: None,
        supersedes: None,
    })
    .unwrap();

    bridge
        .export_to_path(&dest_path)
        .expect("second export must FORCE the heddle-owned embargo rewind (local)");
    bridge
        .push(&url)
        .expect("second network push must FORCE the heddle-owned embargo rewind (network)");

    let dest = open_git(&dest_path).expect("reopen dest");
    let tip = find_reference(&dest, "refs/heads/main")
        .unwrap()
        .peel_to_id()
        .unwrap();
    assert_eq!(
        tip, oid_a,
        "local destination must be force-rewound to the served ancestor A"
    );
    assert_ne!(
        tip, oid_b,
        "local destination must not keep advertising the embargoed tip B"
    );

    let remote = open_git(remote_root.path().join("remote.git")).expect("reopen remote");
    let rtip = find_reference(&remote, "refs/heads/main")
        .unwrap()
        .peel_to_id()
        .unwrap();
    assert_eq!(
        rtip, oid_a,
        "URL/network remote must be force-rewound to the served ancestor A"
    );
    assert_ne!(
        rtip, oid_b,
        "URL/network remote must not keep advertising the embargoed tip B"
    );
}

/// #316 / PR #528 r13 (the r12-review delete finding): the retraction DELETE must
/// honor the SAME heddle-ownership gate as the forced rewind. A destination tip
/// advanced OUT OF BAND past heddle's last-published tip — and then the whole
/// line embargoed so the branch has no served frontier — must NOT be deleted by a
/// plain export/push. heddle never published that tip, so it is not heddle's to
/// retract; deleting it would clobber the user's commit (data loss). r11/r12 gated
/// FORCE on ownership but the delete-set still fired on ANY previously-exported-
/// now-unserved ref — the sibling-class miss. The unified desired-vs-actual+
/// ownership diff now derives delete from the same token (`recorded == old`): the
/// out-of-band tip survives; `--force` is the explicit escape. Covers local-path
/// AND URL/network.
#[test]
fn out_of_band_advance_after_embargo_not_deleted() {
    use chrono::Utc;
    use objects::object::{Principal, StateVisibility, VisibilityTier};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    // A single public tip B heddle publishes to its destinations.
    std::fs::write(heddle_temp.path().join("a.txt"), b"base\n").unwrap();
    repo.snapshot(Some("base".into()), None).unwrap();
    let state_b = repo
        .refs()
        .get_thread(&ThreadName::new("main"))
        .unwrap()
        .unwrap();

    let mut bridge = GitBridge::new(&repo);

    // Publish B to BOTH a local-path destination and a URL/network remote BEFORE
    // the embargo — both must record main as heddle-exported at B.
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    bridge
        .export_to_path(&dest_path)
        .expect("first export publishes B (local)");
    let oid_b = test_support::mapping(&bridge)
        .get_git(&state_b)
        .expect("B minted");

    let remote_root = TempDir::new().expect("remote root");
    let _remote_repo = init_named_bare_git_repo(&remote_root, "remote.git");
    // Park the bare remote's HEAD off main so receive-pack never treats main as
    // the checked-out branch (matches the retraction-delete URL test).
    std::fs::write(
        remote_root.path().join("remote.git").join("HEAD"),
        b"ref: refs/heads/__heddle_placeholder\n",
    )
    .unwrap();
    let Some(daemon) = GitDaemon::spawn_push(remote_root.path()) else {
        return;
    };
    let url = daemon.url("remote.git");
    bridge.push(&url).expect("first network push publishes B");

    // Out-of-band advance: a NEW commit C on top of B, written to the mirror (a
    // resolvable descendant of the served frontier), the local destination, AND
    // the wire remote. Identical inputs ⇒ identical oid in all three.
    let oid_c = {
        let mirror = test_support::open_git_repo(&bridge).expect("open mirror");
        let in_mirror = commit_with_tree(
            &mirror,
            None,
            empty_tree_oid(&mirror),
            "out-of-band",
            &[oid_b],
        );
        let dest = open_git(&dest_path).expect("open dest");
        let in_dest = commit_with_tree(
            &dest,
            Some("refs/heads/main"),
            empty_tree_oid(&dest),
            "out-of-band",
            &[oid_b],
        );
        let remote = open_git(remote_root.path().join("remote.git")).expect("open remote");
        let in_remote = commit_with_tree(
            &remote,
            Some("refs/heads/main"),
            empty_tree_oid(&remote),
            "out-of-band",
            &[oid_b],
        );
        assert_eq!(
            in_mirror, in_dest,
            "C identical in mirror and local destination"
        );
        assert_eq!(
            in_mirror, in_remote,
            "C identical in mirror and wire remote"
        );
        in_mirror
    };

    // Embargo the WHOLE line so refs/heads/main has no served frontier — the exact
    // retraction-delete trigger.
    for state in repo.store().list_states().unwrap() {
        repo.put_state_visibility(StateVisibility {
            state,
            tier: VisibilityTier::Private {
                scope_label: "sec-embargo".into(),
            },
            embargo_until: None,
            declarer: Principal {
                name: "Grace Hopper".into(),
                email: "grace@example.com".into(),
            },
            declared_at: Utc::now(),
            signature: None,
            supersedes: None,
        })
        .unwrap();
    }

    // A plain export must NOT delete C at the local destination: the destination's
    // current tip (C) is not heddle's recorded published tip (B), so the ownership
    // gate spares it from retraction. Pre-r13 this DELETED C.
    bridge
        .export_to_path(&dest_path)
        .expect("plain export must not error on the out-of-band retraction (local)");
    {
        let dest = open_git(&dest_path).expect("reopen dest");
        let tip = find_reference(&dest, "refs/heads/main")
            .unwrap()
            .peel_to_id()
            .unwrap();
        assert_eq!(
            tip, oid_c,
            "the out-of-band commit must survive — heddle must not delete a tip it never published (local)"
        );
    }

    // Same on the URL/network remote: a plain push must not delete the out-of-band
    // branch on the wire.
    bridge
        .push(&url)
        .expect("plain network push must not error on the out-of-band retraction");
    {
        let remote = open_git(remote_root.path().join("remote.git")).expect("reopen remote");
        let tip = find_reference(&remote, "refs/heads/main")
            .unwrap()
            .peel_to_id()
            .unwrap();
        assert_eq!(
            tip, oid_c,
            "the out-of-band commit must survive on the URL/network remote too"
        );
    }

    // `--force` is the explicit escape: it DOES retract the out-of-band branch.
    bridge
        .push_with_scope_force(
            dest_path.to_str().expect("dest path"),
            GitPushScope::AllThreads,
            true,
        )
        .expect("--force retracts the out-of-band branch at the local destination");
    {
        let dest = open_git(&dest_path).expect("reopen dest");
        assert!(
            find_reference(&dest, "refs/heads/main").is_err(),
            "--force deletes the retracted branch even when the destination tip was advanced out of band"
        );
    }
}

/// #316 / PR #528 r17 — the conformance matrix that turns the per-cell fix into a
/// REDESIGN. It drives [`plan_destination_reconcile`] directly across every
/// {namespace} × {operation} × {ownership} × {force} cell and asserts the
/// reconcile outcome. The structural guarantee it locks: ownership (`recorded ==
/// old`, a safe forward move, or `--force`) gates EVERY namespace's overwrite AND
/// delete; move-classification (fast-forward for branch/note, free for tag) is
/// the ONLY per-namespace axis. A future namespace that wires an overwrite
/// without funnelling through the uniform ownership gate — the exact asymmetry
/// that let an out-of-band tag be clobbered before r17 — would fail a row here.
/// The annotated-tag-object sub-cases additionally prove a tag never resolves
/// `find_commit` (which would error on a tag object).
#[test]
fn reconcile_ownership_conformance_matrix() {
    use std::collections::{HashMap, HashSet};

    let (_mirror_temp, mirror) = init_git_repo();
    // Linear topology a <- b so classify_ref_move resolves fast-forward (a->b),
    // rewind (b->a, owned), and divergence for the branch/note rows.
    let a = commit_with_tree(&mirror, None, empty_tree_oid(&mirror), "A", &[]);
    let b = commit_with_tree(&mirror, None, empty_tree_oid(&mirror), "B", &[a]);
    // An annotated-tag OBJECT (kind == Tag, NOT a commit): used as a tag tip to
    // prove classify_tag_move never calls find_commit on it.
    let tag_obj = create_annotated_tag(&mirror, "annot", b, "annotated tag object");

    // Expected reconcile outcome for a single-ref call.
    enum Outcome {
        /// In `writes` with this `new`, and `deletes` empty.
        Write(ObjectId),
        /// In `deletes`, and `writes` empty.
        Delete,
        /// Neither written nor deleted (no-op skip, or out-of-band spared).
        Absent,
        /// `Err(NonFastForwardRef)` — an unowned overwrite without `--force`.
        NonFastForward,
    }

    struct Cell {
        label: &'static str,
        ns: RefNamespace,
        old: Option<ObjectId>,
        target: ObjectId,
        recorded: Option<ObjectId>,
        /// In the served frontier (an overwrite/create) vs. only previously
        /// exported (a retraction).
        desired: bool,
        force: bool,
        expect: Outcome,
    }

    fn is_ancestor_commit(repo: &SleyRepository, ancestor: ObjectId, descendant: ObjectId) -> bool {
        let mut pending = vec![descendant];
        let mut seen = HashSet::new();
        while let Some(oid) = pending.pop() {
            if oid == ancestor {
                return true;
            }
            if !seen.insert(oid) {
                continue;
            }
            if let Ok(commit) = repo.read_commit(&oid) {
                pending.extend(commit.parents);
            }
        }
        false
    }

    fn expected_write_force(repo: &SleyRepository, cell: &Cell) -> bool {
        if cell.force {
            return true;
        }
        let Some(old) = cell.old else {
            return false;
        };
        if old == cell.target {
            return false;
        }
        match cell.ns {
            RefNamespace::Tag => true,
            RefNamespace::Branch | RefNamespace::Note => {
                !is_ancestor_commit(repo, old, cell.target)
            }
        }
    }

    let cells = vec![
        // ---- branch: fast-forward move-classification + uniform ownership ----
        Cell {
            label: "branch/create",
            ns: RefNamespace::Branch,
            old: None,
            target: b,
            recorded: None,
            desired: true,
            force: false,
            expect: Outcome::Write(b),
        },
        Cell {
            label: "branch/no-op",
            ns: RefNamespace::Branch,
            old: Some(b),
            target: b,
            recorded: Some(b),
            desired: true,
            force: false,
            expect: Outcome::Absent,
        },
        Cell {
            label: "branch/fast-forward/owned",
            ns: RefNamespace::Branch,
            old: Some(a),
            target: b,
            recorded: Some(a),
            desired: true,
            force: false,
            expect: Outcome::Write(b),
        },
        Cell {
            label: "branch/fast-forward/out-of-band",
            ns: RefNamespace::Branch,
            old: Some(a),
            target: b,
            recorded: None,
            desired: true,
            force: false,
            expect: Outcome::Write(b),
        },
        Cell {
            label: "branch/rewind/owned",
            ns: RefNamespace::Branch,
            old: Some(b),
            target: a,
            recorded: Some(b),
            desired: true,
            force: false,
            expect: Outcome::Write(a),
        },
        Cell {
            label: "branch/rewind/out-of-band/force-off",
            ns: RefNamespace::Branch,
            old: Some(b),
            target: a,
            recorded: None,
            desired: true,
            force: false,
            expect: Outcome::NonFastForward,
        },
        Cell {
            label: "branch/rewind/out-of-band/force-on",
            ns: RefNamespace::Branch,
            old: Some(b),
            target: a,
            recorded: None,
            desired: true,
            force: true,
            expect: Outcome::Write(a),
        },
        Cell {
            label: "branch/retract/owned",
            ns: RefNamespace::Branch,
            old: Some(b),
            target: b,
            recorded: Some(b),
            desired: false,
            force: false,
            expect: Outcome::Delete,
        },
        // Out-of-band retract: heddle published `a`, the destination drifted to `b`
        // (recorded != old) — spared unless forced.
        Cell {
            label: "branch/retract/out-of-band/force-off",
            ns: RefNamespace::Branch,
            old: Some(b),
            target: b,
            recorded: Some(a),
            desired: false,
            force: false,
            expect: Outcome::Absent,
        },
        Cell {
            label: "branch/retract/out-of-band/force-on",
            ns: RefNamespace::Branch,
            old: Some(b),
            target: b,
            recorded: Some(a),
            desired: false,
            force: true,
            expect: Outcome::Delete,
        },
        // ---- tag: free move-classification + the SAME uniform ownership gate ----
        Cell {
            label: "tag/create",
            ns: RefNamespace::Tag,
            old: None,
            target: b,
            recorded: None,
            desired: true,
            force: false,
            expect: Outcome::Write(b),
        },
        Cell {
            label: "tag/no-op",
            ns: RefNamespace::Tag,
            old: Some(b),
            target: b,
            recorded: Some(b),
            desired: true,
            force: false,
            expect: Outcome::Absent,
        },
        Cell {
            label: "tag/owned-overwrite",
            ns: RefNamespace::Tag,
            old: Some(a),
            target: b,
            recorded: Some(a),
            desired: true,
            force: false,
            expect: Outcome::Write(b),
        },
        // THE r17 fix: an out-of-band tag (recorded != old) is no longer clobbered.
        Cell {
            label: "tag/out-of-band-overwrite/unrecorded/force-off",
            ns: RefNamespace::Tag,
            old: Some(a),
            target: b,
            recorded: None,
            desired: true,
            force: false,
            expect: Outcome::NonFastForward,
        },
        Cell {
            label: "tag/out-of-band-overwrite/mismatched-record/force-off",
            ns: RefNamespace::Tag,
            old: Some(a),
            target: b,
            recorded: Some(b),
            desired: true,
            force: false,
            expect: Outcome::NonFastForward,
        },
        Cell {
            label: "tag/out-of-band-overwrite/force-on",
            ns: RefNamespace::Tag,
            old: Some(a),
            target: b,
            recorded: None,
            desired: true,
            force: true,
            expect: Outcome::Write(b),
        },
        // annotated-tag-object as the NEW target: proves no find_commit on a tag obj.
        Cell {
            label: "tag/owned-overwrite/annotated-object-target",
            ns: RefNamespace::Tag,
            old: Some(a),
            target: tag_obj,
            recorded: Some(a),
            desired: true,
            force: false,
            expect: Outcome::Write(tag_obj),
        },
        // annotated-tag-object as the OLD tip: still gated by OID compare only.
        Cell {
            label: "tag/out-of-band-overwrite/annotated-object-old/force-off",
            ns: RefNamespace::Tag,
            old: Some(tag_obj),
            target: b,
            recorded: None,
            desired: true,
            force: false,
            expect: Outcome::NonFastForward,
        },
        Cell {
            label: "tag/retract/owned",
            ns: RefNamespace::Tag,
            old: Some(b),
            target: b,
            recorded: Some(b),
            desired: false,
            force: false,
            expect: Outcome::Delete,
        },
        Cell {
            label: "tag/retract/out-of-band/force-off",
            ns: RefNamespace::Tag,
            old: Some(b),
            target: b,
            recorded: Some(a),
            desired: false,
            force: false,
            expect: Outcome::Absent,
        },
        Cell {
            label: "tag/retract/out-of-band/force-on",
            ns: RefNamespace::Tag,
            old: Some(b),
            target: b,
            recorded: Some(a),
            desired: false,
            force: true,
            expect: Outcome::Delete,
        },
        // ---- note: classified exactly like a branch (uniform ownership) ----
        Cell {
            label: "note/create",
            ns: RefNamespace::Note,
            old: None,
            target: b,
            recorded: None,
            desired: true,
            force: false,
            expect: Outcome::Write(b),
        },
        Cell {
            label: "note/no-op",
            ns: RefNamespace::Note,
            old: Some(b),
            target: b,
            recorded: Some(b),
            desired: true,
            force: false,
            expect: Outcome::Absent,
        },
        Cell {
            label: "note/fast-forward/owned",
            ns: RefNamespace::Note,
            old: Some(a),
            target: b,
            recorded: Some(a),
            desired: true,
            force: false,
            expect: Outcome::Write(b),
        },
        Cell {
            label: "note/rewind/owned",
            ns: RefNamespace::Note,
            old: Some(b),
            target: a,
            recorded: Some(b),
            desired: true,
            force: false,
            expect: Outcome::Write(a),
        },
        Cell {
            label: "note/rewind/out-of-band/force-off",
            ns: RefNamespace::Note,
            old: Some(b),
            target: a,
            recorded: None,
            desired: true,
            force: false,
            expect: Outcome::NonFastForward,
        },
        Cell {
            label: "note/rewind/out-of-band/force-on",
            ns: RefNamespace::Note,
            old: Some(b),
            target: a,
            recorded: None,
            desired: true,
            force: true,
            expect: Outcome::Write(a),
        },
        Cell {
            label: "note/retract/owned",
            ns: RefNamespace::Note,
            old: Some(b),
            target: b,
            recorded: Some(b),
            desired: false,
            force: false,
            expect: Outcome::Delete,
        },
    ];

    for cell in &cells {
        let short = "v1";
        let full = match cell.ns {
            RefNamespace::Branch => format!("refs/heads/{short}"),
            RefNamespace::Tag => format!("refs/tags/{short}"),
            RefNamespace::Note => format!("refs/notes/{short}"),
        };
        let served: Vec<RefUpdate> = if cell.desired {
            vec![RefUpdate {
                name: short.to_string(),
                target: cell.target,
                namespace: cell.ns,
            }]
        } else {
            Vec::new()
        };
        let mut old_map: HashMap<String, ObjectId> = HashMap::new();
        if let Some(o) = cell.old {
            old_map.insert(full.clone(), o);
        }
        let mut recorded_map: HashMap<String, ObjectId> = HashMap::new();
        if let Some(r) = cell.recorded {
            recorded_map.insert(full.clone(), r);
        }

        let result =
            plan_destination_reconcile(&mirror, &served, None, &old_map, &recorded_map, cell.force);

        if let Outcome::NonFastForward = cell.expect {
            let err = result.expect_err(&format!(
                "cell `{}`: expected Err(NonFastForwardRef)",
                cell.label
            ));
            assert!(
                matches!(err, GitBridgeError::NonFastForwardRef { .. }),
                "cell `{}`: expected NonFastForwardRef, got {err:?}",
                cell.label
            );
            continue;
        }

        let plan =
            result.unwrap_or_else(|e| panic!("cell `{}`: expected Ok, got {e:?}", cell.label));
        match cell.expect {
            Outcome::Write(exp_new) => {
                assert!(
                    plan.deletes.is_empty(),
                    "cell `{}`: expected no deletes",
                    cell.label
                );
                assert_eq!(
                    plan.writes.len(),
                    1,
                    "cell `{}`: expected exactly one write",
                    cell.label
                );
                let w = &plan.writes[0];
                assert_eq!(w.full_name, full, "cell `{}`: write name", cell.label);
                assert_eq!(w.new, exp_new, "cell `{}`: write new", cell.label);
                assert_eq!(
                    w.force,
                    expected_write_force(&mirror, cell),
                    "cell `{}`: write force",
                    cell.label
                );
            }
            Outcome::Delete => {
                assert!(
                    plan.writes.is_empty(),
                    "cell `{}`: expected no writes",
                    cell.label
                );
                assert_eq!(
                    plan.deletes.len(),
                    1,
                    "cell `{}`: expected exactly one delete",
                    cell.label
                );
                let d = &plan.deletes[0];
                assert_eq!(d.full_name, full, "cell `{}`: delete name", cell.label);
            }
            Outcome::Absent => {
                assert!(
                    plan.writes.is_empty(),
                    "cell `{}`: expected no writes",
                    cell.label
                );
                assert!(
                    plan.deletes.is_empty(),
                    "cell `{}`: expected no deletes",
                    cell.label
                );
            }
            Outcome::NonFastForward => unreachable!("handled above"),
        }
    }
}

/// #316 / PR #528 — destination foreign-ref over-claim: a pre-existing destination
/// ref already AT the served target that heddle never recorded (no exported-refs
/// entry) must NOT be claimed into the manifest. The verdict is Skip (no write, no
/// delete), but the prior code still recorded it — which would let a LATER export,
/// once it no longer serves that ref, DELETE a ref heddle never created. The
/// reconcile now leaves it out of the new manifest, so the foreign ref survives a
/// later retraction.
#[test]
fn foreign_destination_ref_spared() {
    use std::collections::HashMap;

    let (_mirror_temp, mirror) = init_git_repo();
    let a = commit_with_tree(&mirror, None, empty_tree_oid(&mirror), "A", &[]);
    let full = "refs/tags/user-v1".to_string();

    // The served frontier WANTS refs/tags/user-v1 at A, and the destination already
    // happens to be at A — but heddle never recorded it (recorded None): FOREIGN.
    let served = vec![RefUpdate {
        name: "user-v1".to_string(),
        target: a,
        namespace: RefNamespace::Tag,
    }];
    let mut old_map: HashMap<String, ObjectId> = HashMap::new();
    old_map.insert(full.clone(), a);
    let recorded_map: HashMap<String, ObjectId> = HashMap::new();

    let plan =
        plan_destination_reconcile(&mirror, &served, None, &old_map, &recorded_map, false).unwrap();
    assert!(
        plan.writes.is_empty(),
        "a coincidental match must not be written"
    );
    assert!(
        plan.deletes.is_empty(),
        "a coincidental match must not be deleted"
    );
    assert!(
        !plan.new_manifest.contains_key(&full),
        "heddle must NOT claim ownership of a foreign destination ref it never recorded"
    );

    // The consequence: a LATER export that no longer serves user-v1 must NOT delete
    // it, because it was never claimed (the manifest carries no record for it).
    let plan2 = plan_destination_reconcile(&mirror, &[], None, &old_map, &plan.new_manifest, false)
        .unwrap();
    assert!(
        plan2.deletes.is_empty(),
        "the foreign ref must survive a later retraction — it was never heddle's to delete"
    );
}

/// #316 / PR #528 r17 (the behavioral gap): an out-of-band destination TAG heddle
/// never recorded must NOT be clobbered by a plain export/push — the precise
/// asymmetry r1-r16 left open (tag DELETES were ownership-gated, tag WRITES were
/// not). A destination `refs/tags/v1.0` advanced out of band past heddle's
/// recorded published tip is FF-rejected (`NonFastForwardRef`) and survives; only
/// `--force` overwrites it back to the served target. Covers BOTH call sites —
/// local-path AND URL/network.
#[test]
fn out_of_band_destination_tag_not_overwritten() {
    use cli::bridge::git_core::GitBridgeError;
    use objects::object::{Attribution, Principal, State};

    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init_default(heddle_temp.path()).expect("init heddle");
    let mut cfg = repo.config().clone();
    cfg.set_principal("Grace Hopper", "grace@example.com");
    cfg.save(&repo.heddle_dir().join("config.toml"))
        .expect("save principal");
    let repo = Repository::open(heddle_temp.path()).expect("reopen heddle");

    // A public main that stays put, plus a SEPARATE state R pinned by marker v1.0
    // — so heddle serves refs/tags/v1.0 throughout (it never rewinds/retracts).
    std::fs::write(heddle_temp.path().join("main.txt"), b"trunk\n").unwrap();
    repo.snapshot(Some("trunk".into()), None).unwrap();
    let r = {
        let store = repo.store();
        let blob = store
            .put_blob(&Blob::from_slice(b"release\n"))
            .expect("blob");
        let tree = store
            .put_tree(&Tree::from_entries(vec![
                TreeEntry::file("release.txt".to_string(), blob, false).expect("entry"),
            ]))
            .expect("tree");
        let state = State::new(
            tree,
            Vec::new(),
            Attribution::human(Principal::new("Grace Hopper", "grace@example.com")),
        );
        store.put_state(&state).expect("put R");
        state
    };
    repo.refs()
        .create_marker(&MarkerName::new("v1.0"), &r.change_id)
        .expect("create marker at R");

    let mut bridge = GitBridge::new(&repo);

    // ---- local-path destination ----
    let dest_root = TempDir::new().expect("dest temp");
    let dest_path = dest_root.path().join("export-target");
    bridge
        .export_to_path(&dest_path)
        .expect("first export publishes the tag (local)");

    // The served tag tip heddle recorded for this destination.
    let served_tag = {
        let dest = open_git(&dest_path).expect("open dest");
        read_exported_refs(&dest).expect("read record")["refs/tags/v1.0"]
    };

    // Out-of-band advance: move the destination tag to a fresh commit X heddle
    // never published (and never recorded).
    let oid_x = {
        let dest = open_git(&dest_path).expect("open dest");
        let x = commit_with_tree(&dest, None, empty_tree_oid(&dest), "out-of-band-tag", &[]);
        set_reference(
            &dest,
            "refs/tags/v1.0",
            x,
            RefPrecondition::Any,
            "test: out-of-band tag",
        )
        .expect("move tag out of band");
        x
    };
    assert_ne!(
        oid_x, served_tag,
        "the out-of-band tag tip must differ from the served tip"
    );

    // A plain export must NOT clobber X: heddle does not own that tip.
    let err = bridge.export_to_path(&dest_path).expect_err(
        "out-of-band tag must be FF-rejected at the local destination, not overwritten",
    );
    assert!(
        matches!(err, GitBridgeError::NonFastForwardRef { .. }),
        "expected a non-fast-forward rejection, got: {err:?}"
    );
    {
        let dest = open_git(&dest_path).expect("reopen dest");
        let tip = find_reference(&dest, "refs/tags/v1.0")
            .unwrap()
            .try_id()
            .expect("tag id");
        assert_eq!(
            tip, oid_x,
            "the out-of-band tag must survive — heddle must not overwrite it"
        );
    }

    // `--force` is the explicit escape hatch: it DOES overwrite back to the tip.
    bridge
        .push_with_scope_force(
            dest_path.to_str().expect("dest path"),
            GitPushScope::AllThreads,
            true,
        )
        .expect("--force overrides the tag ownership gate at the local destination");
    {
        let dest = open_git(&dest_path).expect("reopen dest");
        let tip = find_reference(&dest, "refs/tags/v1.0")
            .unwrap()
            .try_id()
            .expect("tag id");
        assert_eq!(
            tip, served_tag,
            "--force rewinds the local destination tag to the served tip"
        );
    }

    // ---- URL/network destination ----
    let remote_root = TempDir::new().expect("remote root");
    let _remote_repo = init_named_bare_git_repo(&remote_root, "remote.git");
    std::fs::write(
        remote_root.path().join("remote.git").join("HEAD"),
        b"ref: refs/heads/__heddle_placeholder\n",
    )
    .unwrap();
    let Some(daemon) = GitDaemon::spawn_push(remote_root.path()) else {
        return;
    };
    let url = daemon.url("remote.git");

    bridge
        .push(&url)
        .expect("first network push publishes the tag");
    let remote_served_tag = {
        let remote = open_git(remote_root.path().join("remote.git")).expect("open remote");
        find_reference(&remote, "refs/tags/v1.0")
            .unwrap()
            .try_id()
            .expect("tag id")
    };

    let remote_oid_x = {
        let remote = open_git(remote_root.path().join("remote.git")).expect("open remote");
        let x = commit_with_tree(
            &remote,
            None,
            empty_tree_oid(&remote),
            "out-of-band-tag",
            &[],
        );
        set_reference(
            &remote,
            "refs/tags/v1.0",
            x,
            RefPrecondition::Any,
            "test: out-of-band tag",
        )
        .expect("move remote tag out of band");
        x
    };
    assert_ne!(
        remote_oid_x, remote_served_tag,
        "the out-of-band remote tag tip must differ"
    );

    let err = bridge
        .push(&url)
        .expect_err("out-of-band tag must be FF-rejected on the URL/network remote too");
    assert!(
        matches!(err, GitBridgeError::NonFastForwardRef { .. }),
        "expected a non-fast-forward rejection on the wire, got: {err:?}"
    );
    {
        let remote = open_git(remote_root.path().join("remote.git")).expect("reopen remote");
        let tip = find_reference(&remote, "refs/tags/v1.0")
            .unwrap()
            .try_id()
            .expect("tag id");
        assert_eq!(
            tip, remote_oid_x,
            "the out-of-band tag must survive on the URL/network remote"
        );
    }

    bridge
        .push_with_scope_force(&url, GitPushScope::AllThreads, true)
        .expect("--force overrides the tag ownership gate on the URL/network remote");
    {
        let remote = open_git(remote_root.path().join("remote.git")).expect("reopen remote");
        let tip = find_reference(&remote, "refs/tags/v1.0")
            .unwrap()
            .try_id()
            .expect("tag id");
        assert_eq!(
            tip, remote_served_tag,
            "--force rewinds the remote tag to the served tip"
        );
    }
}

/// #316 / PR #528 r17: the ownership gate must NOT over-block a LEGITIMATE tag
/// move. A destination tag whose tip heddle still OWNS (`recorded == old`) is
/// overwritten to the served target on a plain reconcile — `classify_tag_move`'s
/// gate spares ONLY out-of-band tips heddle never recorded, never heddle's own
/// published moves. Driven directly against [`plan_destination_reconcile`]
/// (the mirror now FORCE-retargets a marker re-point, heddle#316 S1, so the
/// source-move path cannot stage an out-of-band DESTINATION tip end-to-end),
/// pinning the owned-vs-unowned boundary in one focused regression: identical
/// inputs land a write when owned, and demand `--force` when not.
#[test]
fn heddle_owned_tag_overwrite_still_lands() {
    use std::collections::HashMap;

    let (_mirror_temp, mirror) = init_git_repo();
    let a = commit_with_tree(&mirror, None, empty_tree_oid(&mirror), "A", &[]);
    let b = commit_with_tree(&mirror, None, empty_tree_oid(&mirror), "B", &[a]);

    let full = "refs/tags/v1.0".to_string();
    let served = vec![RefUpdate {
        name: "v1.0".to_string(),
        target: b,
        namespace: RefNamespace::Tag,
    }];
    let old_at_destination: HashMap<String, ObjectId> = [(full.clone(), a)].into_iter().collect();

    // Owned: heddle recorded the destination tip `a` it is overwriting → the move
    // to `b` lands as a plain write, no `--force` needed.
    let owned: HashMap<String, ObjectId> = [(full.clone(), a)].into_iter().collect();
    let plan =
        plan_destination_reconcile(&mirror, &served, None, &old_at_destination, &owned, false)
            .expect("a heddle-owned tag move must reconcile without --force");
    assert_eq!(
        plan.writes.len(),
        1,
        "owned tag move must produce exactly one write"
    );
    assert_eq!(plan.writes[0].full_name, full);
    assert!(
        plan.writes[0].force,
        "owned tag overwrite must force the destination update"
    );
    assert_eq!(plan.writes[0].new, b, "write lands the served target");
    assert!(
        plan.deletes.is_empty(),
        "an owned overwrite is a write, not a delete"
    );

    // Contrast: the SAME move with no ownership record (out-of-band tip) is the r17
    // gate — FF-rejected unless `--force`.
    let unrecorded: HashMap<String, ObjectId> = HashMap::new();
    let err = plan_destination_reconcile(
        &mirror,
        &served,
        None,
        &old_at_destination,
        &unrecorded,
        false,
    )
    .expect_err("an unowned tag overwrite must be FF-rejected without --force");
    assert!(
        matches!(err, GitBridgeError::NonFastForwardRef { .. }),
        "expected NonFastForwardRef, got {err:?}"
    );
}

/// Write a raw root commit with explicit, distinct author and committer
/// signatures and arbitrary extra headers. Unlike `commit_with_tree`, which
/// reuses one zero-offset signature for both roles, this surfaces committer,
/// timezone, gpgsig, and extra-header fidelity (#564 step 1).
fn commit_with_signatures(
    repo: &SleyRepository,
    reference: Option<&str>,
    tree_oid: ObjectId,
    message: &str,
    author: Signature,
    committer: Signature,
    extra_headers: Vec<(Vec<u8>, Vec<u8>)>,
) -> ObjectId {
    let body = raw_commit_body(
        tree_oid,
        &[],
        &author,
        &committer,
        extra_headers,
        message.as_bytes(),
    );
    let id = repo
        .write_object(EncodedObject::new(GitObjectType::Commit, body))
        .expect("write commit");
    if let Some(reference) = reference {
        set_reference(
            repo,
            reference,
            id,
            RefPrecondition::Any,
            "test: update ref",
        )
        .expect("update ref");
    }
    id
}

fn raw_commit_body(
    tree_oid: ObjectId,
    parents: &[ObjectId],
    author: &Signature,
    committer: &Signature,
    extra_headers: Vec<(Vec<u8>, Vec<u8>)>,
    message: &[u8],
) -> Vec<u8> {
    let mut out = Vec::new();
    out.extend_from_slice(format!("tree {tree_oid}\n").as_bytes());
    for parent in parents {
        out.extend_from_slice(format!("parent {parent}\n").as_bytes());
    }
    out.extend_from_slice(b"author ");
    out.extend_from_slice(&author.to_ident_bytes());
    out.push(b'\n');
    out.extend_from_slice(b"committer ");
    out.extend_from_slice(&committer.to_ident_bytes());
    out.push(b'\n');
    for (name, value) in extra_headers {
        write_raw_commit_header(&mut out, &name, &value);
    }
    out.push(b'\n');
    out.extend_from_slice(message);
    out
}

fn write_raw_commit_header(out: &mut Vec<u8>, name: &[u8], value: &[u8]) {
    out.extend_from_slice(name);
    out.push(b' ');
    let mut lines = value.split(|byte| *byte == b'\n');
    if let Some(first) = lines.next() {
        out.extend_from_slice(first);
    }
    for line in lines {
        out.push(b'\n');
        out.push(b' ');
        out.extend_from_slice(line);
    }
    out.push(b'\n');
}

/// #564 step 1: a commit imported through the bridge must round-trip every
/// git-fidelity field — distinct committer identity, both timezone offsets,
/// the verbatim message, the gpgsig (pulled out of the extra headers), and
/// the remaining extra headers in order.
#[test]
fn import_preserves_commit_git_fidelity_fields() {
    let heddle_temp = TempDir::new().expect("heddle temp");
    let repo = Repository::init(heddle_temp.path()).expect("init heddle");
    let (_git_temp, git_repo) = init_git_repo();

    let tree_oid = empty_tree_oid(&git_repo);
    let author = test_signature_at("Author", "author@example.com", 1_000_000, -7 * 60);
    let committer = test_signature_at("Committer", "committer@example.com", 2_000_000, 2 * 60);
    let gpgsig = "-----BEGIN PGP SIGNATURE-----\nABCD\n-----END PGP SIGNATURE-----";
    let extra_headers = vec![
        (b"gpgsig".to_vec(), gpgsig.as_bytes().to_vec()),
        (b"mergetag".to_vec(), b"object deadbeef".to_vec()),
    ];
    let commit_oid = commit_with_signatures(
        &git_repo,
        Some("refs/heads/main"),
        tree_oid,
        "feat: thing\n\nBody.\n",
        author,
        committer,
        extra_headers,
    );

    let mut bridge = GitBridge::new(&repo);
    import_all(
        &mut bridge,
        Some(git_repo.workdir().expect("workdir").as_path()),
    )
    .expect("import");

    let change_id = test_support::mapping(&bridge)
        .get_heddle(commit_oid)
        .expect("commit mapped");
    let state = repo
        .store()
        .get_state(&change_id)
        .expect("load state")
        .expect("state written");

    let stored_committer = state.committer.expect("committer preserved");
    assert_eq!(stored_committer.name, "Committer");
    assert_eq!(stored_committer.email, "committer@example.com");
    assert_eq!(state.authored_tz_offset, -7 * 3600);
    assert_eq!(state.committer_tz_offset, 2 * 3600);
    assert_eq!(
        state.raw_message.as_deref(),
        Some("feat: thing\n\nBody.\n".as_bytes())
    );
    // Git config folds multi-line extra-header values and round-trips them with a
    // trailing newline; byte-exact State round-tripping is covered by the
    // ingest unit test. Here we verify gpgsig stays INLINE in extra_headers at
    // its captured position (not split into a separate field) and the headers
    // keep their original order.
    assert_eq!(
        state.extra_headers.len(),
        2,
        "gpgsig + mergetag, both inline"
    );
    assert_eq!(state.extra_headers[0].0, b"gpgsig".to_vec());
    assert_eq!(
        String::from_utf8_lossy(&state.extra_headers[0].1).trim_end(),
        gpgsig,
        "gpgsig preserved inline at its captured position"
    );
    assert_eq!(state.extra_headers[1].0, b"mergetag".to_vec());
    assert_eq!(
        String::from_utf8_lossy(&state.extra_headers[1].1).trim_end(),
        "object deadbeef"
    );
}

/// #564 de-lossy step 1, close-the-class proof (#565 r3). Every
/// fidelity-bearing git byte-string of a COMMIT must survive byte-identically
/// through BOTH import paths — the bridge (`import_all`) and the ingest engine
/// (`ingest::import_git_into`). A single fixture exercises non-UTF8 bytes in
/// ALL of: the commit message, a `gpgsig` header (kept inline in
/// `extra_headers`), a custom extra-header value, and a `mergetag` payload.
/// `0xe9` (latin-1 `é`) is invalid standalone UTF-8, so any lingering
/// `String`/`to_string()` hop on any of these would replace it with U+FFFD and
/// fail an assertion below. This one test fails if ANY sibling of the
/// byte-vs-String class regresses. (Annotated-tag-object fidelity is out of
/// scope here — see #575.)
#[test]
fn non_utf8_git_fidelity_is_byte_identical_across_bridge_and_ingest() {
    use ingest::import_git_into;

    let (_git_temp, git_repo) = init_git_repo();
    let tree_oid = empty_tree_oid(&git_repo);

    // The message keeps its own internal blank line (`\n\n`) to prove the
    // header/body split isn't fooled by a `\n\n` inside the body.
    let commit_message = b"caf\xe9 subject\n\nbody with a \xe9 byte\n".to_vec();
    let gpgsig_value =
        b"-----BEGIN PGP SIGNATURE-----\n\xe9 not-real-armor\n-----END PGP SIGNATURE-----".to_vec();
    let custom_value = b"x-note caf\xe9 value".to_vec();
    // A mergetag value is a whole tag object — multi-line, with its own blank
    // line and a non-UTF8 byte in the tag name and message lines.
    let mergetag_value = {
        let mut v = Vec::new();
        v.extend_from_slice(b"object 0123456789012345678901234567890123456789\n");
        v.extend_from_slice(b"type commit\n");
        v.extend_from_slice(b"tag merged-\xe9\n");
        v.extend_from_slice(b"tagger Heddle Test <heddle@test> 0 +0000\n");
        v.extend_from_slice(b"\n");
        v.extend_from_slice(b"merge note caf\xe9\n");
        v
    };

    let sig = test_signature();
    let commit = raw_commit_body(
        tree_oid,
        &[],
        &sig,
        &sig,
        vec![
            (b"gpgsig".to_vec(), gpgsig_value.clone()),
            (b"x-custom".to_vec(), custom_value.clone()),
            (b"mergetag".to_vec(), mergetag_value.clone()),
        ],
        &commit_message,
    );
    let commit_oid = git_repo
        .write_object(EncodedObject::new(GitObjectType::Commit, commit))
        .expect("write commit");
    set_reference(
        &git_repo,
        "refs/heads/main",
        commit_oid,
        RefPrecondition::Any,
        "test: main",
    )
    .expect("set main");

    let git_workdir = git_repo.workdir().expect("workdir");

    // ── path 1: bridge import ──
    let bridge_heddle = TempDir::new().expect("bridge heddle temp");
    let bridge_repo = Repository::init(bridge_heddle.path()).expect("init bridge heddle");
    let mut bridge = GitBridge::new(&bridge_repo);
    import_all(&mut bridge, Some(git_workdir.as_path())).expect("bridge import");
    let bridge_cid = test_support::mapping(&bridge)
        .get_heddle(commit_oid)
        .expect("bridge mapped commit");
    let bridge_state = bridge_repo
        .store()
        .get_state(&bridge_cid)
        .expect("load bridge state")
        .expect("bridge state written");

    // ── path 2: ingest import ──
    let ingest_heddle = TempDir::new().expect("ingest heddle temp");
    let (_stats, ingest_map) =
        import_git_into(git_workdir, ingest_heddle.path()).expect("ingest import");
    let ingest_cid = ingest_map
        .get_commit(&commit_oid.to_string())
        .expect("ingest mapped commit");
    let ingest_repo = Repository::open(ingest_heddle.path()).expect("open ingest heddle");
    let ingest_state = ingest_repo
        .store()
        .get_state(&ingest_cid)
        .expect("load ingest state")
        .expect("ingest state written");

    // The fixture really is non-UTF8 — otherwise the test proves nothing.
    assert!(String::from_utf8(commit_message.clone()).is_err());

    // (1) commit message: byte-exact to the original, AND byte-identical
    // across paths — this pins `message_raw_sloppy` (bridge) and
    // `message_raw` (ingest) to the same bytes.
    assert_eq!(
        bridge_state.raw_message.as_deref(),
        Some(commit_message.as_slice()),
        "bridge must preserve the raw commit message verbatim"
    );
    assert_eq!(
        ingest_state.raw_message, bridge_state.raw_message,
        "raw_message must be byte-identical across bridge and ingest"
    );

    // (2) extra headers (gpgsig + custom + mergetag): identical across paths,
    // ordered, non-UTF8 survived. gpgsig is kept INLINE here at its captured
    // position (not split into a separate field), so its byte-identity is
    // proved by this same comparison.
    assert_eq!(
        bridge_state.extra_headers, ingest_state.extra_headers,
        "extra_headers must be byte-identical (and same order) across paths"
    );
    let keys: Vec<&[u8]> = bridge_state
        .extra_headers
        .iter()
        .map(|(k, _)| k.as_slice())
        .collect();
    assert_eq!(
        keys,
        vec![
            b"gpgsig".as_slice(),
            b"x-custom".as_slice(),
            b"mergetag".as_slice(),
        ],
        "gpgsig stays inline at its captured position; all three remain in order"
    );
    for (key, value) in &bridge_state.extra_headers {
        assert!(
            value.contains(&0xe9u8),
            "extra-header {:?} must preserve its non-UTF8 byte",
            String::from_utf8_lossy(key)
        );
        assert!(String::from_utf8(value.clone()).is_err());
    }
}