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
use anyhow::{Context, Result};
use serde::{Deserialize, Deserializer, Serialize};
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::process::Command as StdCommand;
use std::sync::Mutex;
use tokio::process::Command as TokioCommand;
pub(crate) static GIT_COMMAND_LOCK: Mutex<()> = Mutex::new(());
pub(crate) struct GitCommand {
inner: StdCommand,
}
impl GitCommand {
pub(crate) fn new() -> Self {
// Poisoned means a previous git-command thread panicked while holding
// the lock; continuing would risk overlapping git operations.
let _command_guard = GIT_COMMAND_LOCK.lock().expect("git command lock poisoned");
Self {
inner: StdCommand::new(git_binary()),
}
}
}
impl Deref for GitCommand {
type Target = StdCommand;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for GitCommand {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
pub(crate) struct TokioGitCommand {
inner: TokioCommand,
}
impl TokioGitCommand {
pub(crate) fn new() -> Self {
// Poisoned means a previous git-command thread panicked while holding
// the lock; continuing would risk overlapping git operations.
let _command_guard = GIT_COMMAND_LOCK.lock().expect("git command lock poisoned");
Self {
inner: TokioCommand::new(git_binary()),
}
}
}
impl Deref for TokioGitCommand {
type Target = TokioCommand;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for TokioGitCommand {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
pub(crate) const DEFAULT_GIT_HOST_BLOB_LIMIT_BYTES: u64 = 100 * 1024 * 1024;
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
pub(crate) struct StandardFileConfig {
pub(crate) source: String,
pub(crate) target: String,
#[serde(default)]
pub(crate) overwrite: bool,
}
impl StandardFileConfig {
pub(crate) fn source_path(&self, base_dir: &Path) -> PathBuf {
let expanded = expand_tilde(&self.source);
if expanded.is_absolute() {
expanded
} else {
base_dir.join(&expanded)
}
}
}
/// ADDED 2026-07-26 (v0.113.4, audit SYNC-H5): shared safety check
/// for `standard_files` source/target path STRINGS, enforced both by
/// `validate_config` AND at the point of use in
/// `ensure_standard_files` (the daemon's execution path never calls
/// `validate_config` — a config typo or a write to the policy file
/// was a read-anywhere → publish-everywhere primitive: `source =
/// "~/.ssh/id_rsa"` passed validation because raw `~/...` is not
/// `Path::is_absolute`, then `expand_tilde` resolved it outside the
/// sync base, and the copied file was auto-committed + auto-pushed
/// to public forges). Rule: no raw-absolute paths (tilde `~/` is
/// fine — `expand_tilde` anchors it under $HOME) and no `..`
/// components anywhere.
pub(crate) fn is_safe_standard_file_path(raw: &str) -> bool {
let p = std::path::Path::new(raw);
if p.is_absolute() {
return false;
}
!p.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
}
fn expand_tilde(path: &str) -> PathBuf {
if let Some(rest) = path.strip_prefix('~') {
// FIXED 2026-07-21 (v0.112.33, audit M22/F3.4):
// `strip_prefix('~')` on `"~/templates/LICENSE"` yields
// `"/templates/LICENSE"` (leading slash retained), and
// `Path::join` with an ABSOLUTE argument REPLACES the base —
// so `expand_tilde("~/x")` resolved to `/x` (filesystem
// root), not `$HOME/x` (verified by compiling the function
// during the audit). Strip the optional `/` after `~`.
let rest = rest.strip_prefix('/').unwrap_or(rest);
dirs::home_dir()
.map(|h| h.join(rest))
.unwrap_or_else(|| PathBuf::from(path))
} else {
PathBuf::from(path)
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub(crate) enum StandardFilesEntry {
Short(String),
Full(StandardFileConfig),
}
impl From<String> for StandardFileConfig {
fn from(name: String) -> Self {
StandardFileConfig {
source: format!("templates/{}", name),
target: name,
overwrite: false,
}
}
}
fn deserialize_standard_files<'de, D>(deserializer: D) -> Result<Vec<StandardFileConfig>, D::Error>
where
D: Deserializer<'de>,
{
let raw: Vec<StandardFilesEntry> = Deserialize::deserialize(deserializer)?;
Ok(raw.into_iter().map(|e| e.into_config()).collect())
}
impl StandardFilesEntry {
fn into_config(self) -> StandardFileConfig {
match self {
StandardFilesEntry::Short(name) => name.into(),
StandardFilesEntry::Full(cfg) => cfg,
}
}
}
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
pub(crate) struct RemoteConfig {
pub(crate) name: String,
pub(crate) push_url: String,
#[serde(default)]
pub(crate) auto_create: bool,
#[serde(default)]
pub(crate) auto_create_account: String,
#[serde(default = "default_auth_type")]
pub(crate) auth_type: AuthType,
#[serde(default = "default_priority")]
pub(crate) priority: u32,
#[serde(default)]
pub(crate) api_endpoint: Option<String>,
#[serde(default)]
pub(crate) auto_create_token_var: Option<String>,
/// Optional per-remote name mapping for repos that need sanitization.
/// Key = local repo basename, Value = remote project name.
/// Example: { ".dracon" = "dracon-home" } maps .dracon → dracon-home on this remote.
#[serde(default)]
pub(crate) repo_name_map: std::collections::HashMap<String, String>,
/// If true, when a push to this remote fails with non-fast-forward, the daemon
/// will diagnose divergence. If the remote is purely behind (0 commits ahead
/// of local), it force-pushes with --force-with-lease. If the remote has
/// commits local lacks (divergent), the repo is marked CONCERN instead.
#[serde(default)]
pub(crate) force_push_when_behind: bool,
}
impl RemoteConfig {
pub(crate) fn resolve_push_url(&self, repo_name: &str) -> String {
let resolved_name = self
.repo_name_map
.get(repo_name)
.map(|s| s.as_str())
.unwrap_or(repo_name);
let url = self.push_url.replace("{repo}", resolved_name);
url.replace("{account}", &self.auto_create_account)
}
pub(crate) fn resolve_repo_name(&self, repo_name: &str) -> String {
self.repo_name_map
.get(repo_name)
.cloned()
.unwrap_or_else(|| repo_name.to_string())
}
}
fn default_auth_type() -> AuthType {
AuthType::GitHub
}
fn default_priority() -> u32 {
50
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum AuthType {
#[default]
GitHub,
GitLab,
Codeberg,
Generic,
}
impl AuthType {
/// Auto-detect auth type from a push URL.
/// Returns the detected type, or `GitHub` (default) if no match.
pub(crate) fn from_push_url(url: &str) -> Self {
let lower = url.to_ascii_lowercase();
if lower.contains("gitlab") {
Self::GitLab
} else if lower.contains("codeberg") {
Self::Codeberg
} else if lower.contains("github") {
Self::GitHub
} else {
Self::Generic
}
}
}
impl RemoteConfig {
/// Returns the effective auth type: explicitly set if non-default,
/// otherwise auto-detected from the push_url.
pub(crate) fn effective_auth_type(&self) -> AuthType {
if self.auth_type != AuthType::GitHub {
return self.auth_type;
}
AuthType::from_push_url(&self.push_url)
}
/// Returns the account name: explicitly set if non-empty,
/// otherwise extracted from the push_url.
pub(crate) fn resolve_account(&self) -> String {
if !self.auto_create_account.is_empty() {
return self.auto_create_account.clone();
}
// Extract account from push_url patterns:
// SSH: git@host:account/repo.git
// HTTPS: https://host/account/repo.git
let url = &self.push_url;
if url.contains('@') {
// SSH: git@host:account/{repo}.git → extract account before {repo}
if let Some(colon) = url.rfind(':') {
let after_colon = &url[colon + 1..];
if let Some(slash) = after_colon.find('/') {
return after_colon[..slash].to_string();
}
}
} else if url.starts_with("http://") || url.starts_with("https://") {
// HTTPS: https://host/account/{repo}.git
if let Some(double_slash) = url.find("://") {
let after_proto = &url[double_slash + 3..];
if let Some(slash) = after_proto.find('/') {
let after_host = &after_proto[slash + 1..];
if let Some(slash) = after_host.find('/') {
return after_host[..slash].to_string();
}
}
}
}
self.auto_create_account.clone()
}
}
fn deserialize_remotes_or_extra<'de, D>(deserializer: D) -> Result<Vec<RemoteConfig>, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum RemotesOrExtra {
New(Vec<RemoteConfig>),
Legacy(Vec<String>),
}
let raw = RemotesOrExtra::deserialize(deserializer)?;
match raw {
RemotesOrExtra::New(configs) => Ok(configs),
RemotesOrExtra::Legacy(names) => {
let defaults = vec![
RemoteConfig {
name: "github".to_string(),
push_url: "https://github.com/{account}/{repo}.git".to_string(),
auto_create: false,
auto_create_account: "DraconDev".to_string(),
auth_type: AuthType::GitHub,
priority: 50,
api_endpoint: None,
auto_create_token_var: None,
repo_name_map: Default::default(),
force_push_when_behind: false,
},
RemoteConfig {
name: "gitlab".to_string(),
push_url: "git@gitlab.com:{account}/{repo}.git".to_string(),
auto_create: false,
auto_create_account: "DraconDev".to_string(),
auth_type: AuthType::GitLab,
priority: 50,
api_endpoint: None,
auto_create_token_var: None,
repo_name_map: Default::default(),
force_push_when_behind: false,
},
RemoteConfig {
name: "codeberg".to_string(),
push_url: "git@codeberg.org:{account}/{repo}.git".to_string(),
auto_create: false,
auto_create_account: "dracondev".to_string(),
auth_type: AuthType::Codeberg,
priority: 50,
api_endpoint: Some("https://codeberg.org/api/v1/repos".to_string()),
auto_create_token_var: None,
repo_name_map: Default::default(),
force_push_when_behind: false,
},
];
let filtered: Vec<RemoteConfig> = defaults
.into_iter()
.filter(|d| names.contains(&d.name))
.map(|mut d| {
d.auto_create = true;
d
})
.collect();
Ok(filtered)
}
}
}
pub(crate) fn git_binary() -> PathBuf {
if let Ok(custom) = std::env::var("DRACON_SYNC_GIT_BIN") {
let trimmed = custom.trim();
if !trimmed.is_empty() {
return PathBuf::from(trimmed);
}
}
for candidate in ["/run/current-system/sw/bin/git", "/usr/bin/git", "/bin/git"] {
let path = PathBuf::from(candidate);
if path.exists() {
return path;
}
}
PathBuf::from("git")
}
pub(crate) fn std_git_command() -> GitCommand {
GitCommand::new()
}
pub(crate) fn tokio_git_command() -> TokioGitCommand {
TokioGitCommand::new()
}
pub(crate) fn timestamp_secs() -> u64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
#[derive(Debug, Default, Deserialize, serde::Serialize, Clone)]
pub(crate) struct SyncPolicy {
#[serde(default)]
pub(crate) system_repo: String,
#[serde(default = "default_pulse_interval")]
pub(crate) pulse_interval_secs: u64,
/// Maximum seconds to wait for dispatched sync tasks to complete during
/// the trailing-drain phase before clearing them from `in_flight` so the
/// next cycle can re-dispatch.
///
/// The trailing-drain phase runs after the apply-phase deadline
/// (`pulse_interval_secs * 2`) to clean up slow pushes that didn't
/// finish in time. If this deadline is too short, pushes that take
/// longer (e.g. github first-push with a cold pack cache) get killed
/// and the next cycle spawns a duplicate push, causing a traffic jam
/// that delays smaller pushes.
///
/// The default (120s) gives most pushes enough time to complete while
/// still bounding the daemon's cycle time. Set higher for repos with
/// very large histories (e.g. 2+ GiB packs).
///
/// ADDED 2026-07-09 (goal fb8ddd6b — repo-discovery audit): the
/// previous code reused `pulse_interval_secs * 2` (default 2s) which
/// was way too short for github pushes, causing the 9-submodule
/// github lag that the audit surfaced.
#[serde(default = "default_trailing_drain_deadline_secs")]
pub(crate) trailing_drain_deadline_secs: u64,
#[serde(default = "default_inactivity_push_delay_secs")]
pub(crate) inactivity_push_delay_secs: u64,
#[serde(default = "default_true")]
pub(crate) auto_commit: bool,
/// If true, bump patch versions before an auto-commit (best-effort).
/// Applies to common files when present at repo root:
/// - Rust: `Cargo.toml` (and keep `Cargo.lock` aligned for root package)
/// - Node/TS: `package.json` (and align `package-lock.json` root `version` when applicable)
/// - Generic: `VERSION`
#[serde(default = "default_true")]
pub(crate) auto_bump_versions: bool,
#[serde(default = "default_true")]
pub(crate) auto_pull: bool,
#[serde(default = "default_true")]
pub(crate) auto_push: bool,
#[serde(default)]
pub(crate) backup_policy: String,
#[serde(default)]
pub(crate) backup_dir: String,
#[serde(default)]
pub(crate) exclude_repos: Vec<String>,
#[serde(default)]
pub(crate) exclude_dir_names: Vec<String>,
#[serde(default = "default_exclude_file_patterns")]
pub(crate) exclude_file_patterns: Vec<String>,
/// If true, the daemon will stage newly-created untracked working
/// files on the next sync cycle. Defaults to `true` so brand-new
/// working files (research docs, source files, etc.) get
/// committed promptly. Excluded by `untracked_exclude_patterns`.
#[serde(default = "default_true")]
pub(crate) auto_stage_untracked: bool,
/// Glob patterns for untracked files that should NOT be
/// auto-staged by `auto_stage_untracked`. Defaults to common
/// safe patterns: user notes, scratch files, audit/research
/// evidence, and dotfile/scratch dirs. Edit in
/// `dracon-sync.toml` to extend.
#[serde(default = "default_untracked_exclude_patterns")]
pub(crate) untracked_exclude_patterns: Vec<String>,
/// Glob patterns for TRACKED files that should NOT be auto-
/// staged by the daemon. Unlike `untracked_exclude_patterns`
/// (which only applies to newly-added files), this list applies
/// to ANY file the daemon considers staging — including
/// modifications to already-tracked files.
///
/// Use case: a repo's `web/test-results/` directory has 372
/// Playwright screenshots that are force-tracked by the
/// `.gitignore` allowlist (`!*.png`). Playwright regenerates
/// these on every test run, and the daemon auto-commits them
/// — creating a moving target the daemon can never push.
/// Setting `auto_commit_exclude_patterns = ["**/test-results/**"]`
/// in the repo's `.dracon/dracon-sync.toml` tells the daemon
/// to skip those files entirely (manual `git add` still works).
///
/// Defaults to empty: this is an opt-in per-repo mechanism. The
/// global `untracked_exclude_patterns` still applies to new
/// files; this only filters modifications to tracked files.
#[serde(default)]
pub(crate) auto_commit_exclude_patterns: Vec<String>,
#[serde(default = "default_true")]
pub(crate) auto_repair_concerns: bool,
/// Untrack tracked files living inside hard-coded build-artifact
/// dir names (output/, dist-new/, gen/, …) and add the dir to
/// .gitignore. Set false per-repo when such a dir is CONTENT,
/// not residue — e.g. ai-auto-writer's `output/` holds the
/// generated books, the project's actual deliverable
/// (2026-07-31 operator decision: the daemon's untrack fought the
/// loop's deliberate chapter commits in a 30-commit/hour
/// ping-pong that starved pushes).
#[serde(default = "default_true")]
pub(crate) build_artifact_cleanup: bool,
#[serde(default = "default_true")]
pub(crate) auto_repair_warns: bool,
#[serde(default = "default_true")]
pub(crate) auto_rewrite_large_blobs: bool,
#[serde(default)]
pub(crate) watch_roots: Vec<String>,
#[serde(default, deserialize_with = "deserialize_remotes_or_extra")]
pub(crate) remotes: Vec<RemoteConfig>,
#[serde(default)]
pub(crate) auto_github_private: bool,
#[serde(default = "default_github_account")]
pub(crate) auto_github_private_account: String,
#[serde(default = "default_max_stage_file_bytes")]
pub(crate) max_stage_file_bytes: u64,
/// Maximum number of files to stage in a single commit batch.
/// When a repo has more untracked files than this limit, the daemon
/// commits them in multiple smaller batches (each ≤ this size) to
/// avoid lock contention and large commit overhead.
/// Default: 100000. The large default keeps high-volume test/audit
/// batches in one commit; operators can lower it when smaller batches
/// are preferable.
#[serde(default = "default_max_stage_batch_files")]
pub(crate) max_stage_batch_files: usize,
/// Auto-resolve unmerged index entries when the working tree
/// matches HEAD (the "ours" side of the merge). When true, the
/// daemon runs `git reset HEAD -- <unmerged-paths>` to clear
/// the unmerge and proceeds with the commit. This is safe
/// because the working tree content has already been verified
/// to match HEAD byte-for-byte. Default: true (commit-all
/// policy — never block on stale unmerged entries).
/// ADDED 2026-06-21, goal 55db3bfc-4fc0-4650-8349-38da9e62bd44.
#[serde(default = "default_auto_resolve_unmerged")]
pub(crate) auto_resolve_unmerged: bool,
/// Minimum seconds between push attempts to all remotes of a
/// single repo. When the daemon makes multiple commits within
/// this window, it accumulates them and pushes once at the end
/// of the window. This eliminates per-commit push churn.
/// Default: 30s.
/// ADDED 2026-06-21, goal 55db3bfc-4fc0-4650-8349-38da9e62bd44.
#[serde(default = "default_push_debounce_secs")]
#[allow(dead_code)]
// intentional future-policy config; not yet wired into runtime. Audit AUDIT-3-UTILITIES-2026-07-10.md CONCERN #6.
pub(crate) push_debounce_secs: u64,
/// When the untracked-file count exceeds this threshold, the
/// daemon emits a warning to the operator. Set to 0 to disable.
/// Default: 500.
/// ADDED 2026-06-21, goal 55db3bfc-4fc0-4650-8349-38da9e62bd44.
#[serde(default = "default_untracked_warn_threshold")]
pub(crate) untracked_warn_threshold: usize,
#[serde(default = "default_pull_op_timeout_secs")]
pub(crate) pull_op_timeout_secs: u64,
#[serde(default = "default_push_op_timeout_secs")]
pub(crate) push_op_timeout_secs: u64,
/// ADDED 2026-07-25 (v0.113.0): when a repo's dangling-object
/// garbage (`count-objects` `size-garbage`, the tmp_pack_* debris
/// of interrupted pushes) exceeds this many bytes, the daemon
/// runs `git gc --prune=now` automatically. Root-cause fix for
/// the recurring `.git` bloat incidents (hegemon 4.9 GiB,
/// dracon-platform 37 GiB) that previously needed manual gc.
/// Default: 2 GiB. Set to 0 to disable.
#[serde(default = "default_auto_gc_garbage_threshold_bytes")]
pub(crate) auto_gc_garbage_threshold_bytes: u64,
/// ADDED 2026-07-29 (v0.113.10): opt-in janitor for stale
/// daemon-created branches (`backup/pre-sync-largeblob-fix-*`,
/// `daemon-standalone`) plus orphaned remote-tracking refs
/// (`refs/remotes/<removed-remote>/*`). When true, a daily per-repo
/// pass bundles the candidate branches into
/// `<backup_dir>/auto-prune/`, verifies the bundle, deletes them
/// locally, and deletes the remote copy on any remote whose tip
/// matches the recorded local tip (injecting
/// `DRACON_ALLOW_REWRITE=1` into that one push command's env — the
/// sanctioned narrow exception to the no-auto-rewrite policy,
/// scoped to branches the daemon itself created). Every deletion
/// is `log_warn!`'d with repo, branch, tip, and bundle path so the
/// journal remains the operator-review trail AGENTS.md assigns to
/// new `backup/*` branches. Requires `backup_dir` to be set.
/// Default: false (destructive-class actions are opt-in).
#[serde(default)]
pub(crate) auto_prune_stale_backup_branches: bool,
#[serde(default = "default_repo_sync_timeout_secs")]
pub(crate) repo_sync_timeout_secs: u64,
/// Timeout for `git add` staging operations during a sync cycle.
/// Repos with very large working trees (thousands of dirty paths) may
/// need a higher value than the legacy 30s hardcoded default.
/// Default: 60s.
#[serde(default = "default_stage_op_timeout_secs")]
pub(crate) stage_op_timeout_secs: u64,
/// When `git add` times out for a repo, the daemon applies a per-repo
/// cooldown of this many seconds before retrying. This prevents the
/// incident ledger from being spammed every ~70s with the same timeout
/// for repos whose working tree is too large to stage automatically.
/// Default: 3600s (1 hour).
#[serde(default = "default_stage_cooldown_secs")]
pub(crate) stage_cooldown_secs: u64,
#[serde(default = "default_push_retries")]
pub(crate) push_retries: u32,
#[serde(default = "default_repair_cooldown_secs")]
pub(crate) repair_cooldown_secs: u64,
#[serde(default = "default_max_push_blob_bytes")]
pub(crate) max_push_blob_bytes: u64,
#[serde(default = "default_sem_max_concurrent_sync")]
#[allow(dead_code)] // removed semaphore gate; field retained for config compatibility
pub(crate) sem_max_concurrent_sync: usize,
#[serde(default = "default_incident_ledger_max_lines")]
pub(crate) incident_ledger_max_lines: usize,
#[serde(default = "default_incident_ledger_max_age_days")]
pub(crate) incident_ledger_max_age_days: u64,
#[serde(default)]
pub(crate) webhook_url: Option<String>,
#[serde(default = "default_alert_unpushed_threshold")]
pub(crate) alert_unpushed_threshold: usize,
/// When a repo has more than this many unpushed commits AND the push
/// has been pending (ahead_since) for more than
/// `auto_commit_backstop_min_age_secs`, the daemon stops auto-
/// committing and logs the backstop. This prevents the daemon from
/// creating a moving target while a push is failing. Set to 0 to
/// disable the backstop entirely. The ACTIVITY column shows
/// `⏸ backstop` for repos in this state so the operator can see
/// the daemon is intentionally pausing.
#[serde(default = "default_auto_commit_backstop_threshold")]
pub(crate) auto_commit_backstop_threshold: usize,
#[serde(default = "default_auto_commit_backstop_min_age_secs")]
pub(crate) auto_commit_backstop_min_age_secs: u64,
/// Number of consecutive push failures before the daemon
/// stops auto-pushing a repo and surfaces a `🛑 push-stuck`
/// state in the ACTIVITY column with the actual error
/// message in the HINT. Default 5. Set to 0 to disable the
/// retry budget (never give up; the existing
/// `push_retries` still applies per-attempt).
#[serde(default = "default_push_max_retries")]
pub(crate) push_max_retries: u32,
/// Safety guard rail: when true (default), the daemon skips
/// auto-commit AND auto-push for repos classified as
/// `Unowned` or `Unknown` outside configured watch roots.
/// Repositories beneath a configured watch root are path-owned by
/// default; their identity/origin mismatches are warnings instead.
/// `owned = false` remains a hard per-repo opt-out. Set this false
/// to re-enable heuristic handling for explicitly unowned paths.
/// Per-repo override: `RepoPolicyOverride.auto_skip_unowned`.
#[serde(default = "default_true")]
pub(crate) auto_skip_unowned: bool,
/// Trusted git `user.email` values. Outside configured watch roots,
/// a repo is classified as Owned when its local `git config user.email`
/// matches one of these. For path-owned repos this remains a warning
/// signal. Default: `["dracsharp@gmail.com"]`.
#[serde(default = "default_trusted_emails")]
pub(crate) trusted_emails: Vec<String>,
/// Trusted git author name values. Outside configured watch roots, a
/// repo is classified as Owned when its HEAD commit author name matches
/// one of these (e.g. when the operator's commit name was changed in the
/// global git config but historical commits still have the old name).
/// For path-owned repos this remains a warning signal. Default:
/// `["DraconDev"]`.
#[serde(default = "default_trusted_authors")]
pub(crate) trusted_authors: Vec<String>,
/// Trusted `origin` remote URL substrings. Outside configured watch roots,
/// a repo is classified as Owned when its `origin` URL matches one of
/// these host/account pairs. For path-owned repos a foreign origin is
/// fetch-only and remains a warning. Default: the three DraconDev hosts
/// on GitHub, GitLab, and Codeberg.
#[serde(default = "default_trusted_remote_hosts")]
pub(crate) trusted_remote_hosts: Vec<String>,
/// When a repo has been dirty continuously for longer than
/// this many seconds, the daemon commits REGARDLESS of
/// whether the fingerprint is still changing. Prevents the
/// "⏸ stalled Xm" pileup the operator sees when many repos
/// have stale dirty state from previous sessions. Default
/// 60s. Set to 0 to disable (back to 5s fingerprint wait).
#[serde(default = "default_settling_max_delay_secs")]
#[allow(dead_code)]
// intentional future-policy config; not yet wired into runtime. Audit AUDIT-3-UTILITIES-2026-07-10.md CONCERN #6.
pub(crate) settling_max_delay_secs: u64,
/// Action to take when a dirty repo exceeds
/// `settling_max_delay_secs`. `Commit` (default) force-
/// commits the current state; `Warn` logs a warning but
/// does not commit; `Ignore` does nothing.
#[serde(default = "default_dirty_max_age_action")]
#[allow(dead_code)]
// intentional future-policy config; not yet wired into runtime. Audit AUDIT-3-UTILITIES-2026-07-10.md CONCERN #6.
pub(crate) dirty_max_age_action: DirtyMaxAgeAction,
/// Minimum time between consecutive auto-commits for the
/// same repo. Prevents thrashing when the operator is
/// actively editing. Default 5s. Setting this too high will
/// make the daemon appear to "stall" on dirty repos.
#[serde(default = "default_min_commit_interval_secs")]
#[allow(dead_code)]
// intentional future-policy config; not yet wired into runtime. Audit AUDIT-3-UTILITIES-2026-07-10.md CONCERN #6.
pub(crate) min_commit_interval_secs: u64,
/// When a watched repo has committable changes whose OLDEST file
/// mtime is older than this many seconds, the daemon emits a
/// "Changes Piling Up" alert (journal + alerts ledger, throttled
/// to once per 30 min per repo). The age is mtime-based, so a
/// frozen daemon or a wedged cycle is surfaced on the first
/// cycle after the daemon resumes — even when it then commits
/// immediately. Default 600s (10 min). Set to 0 to disable.
/// Per-repo override via `stale_dirty_alert_secs` in
/// `<repo>/.dracon/dracon-sync.toml`. ADDED 2026-08-05
/// (v0.113.42).
#[serde(default = "default_stale_dirty_alert_secs")]
pub(crate) stale_dirty_alert_secs: u64,
#[serde(default)]
pub(crate) sync_visibility: bool,
#[serde(default = "default_sync_visibility_interval_hours")]
pub(crate) sync_visibility_interval_hours: u64,
/// When true, sync repo description and topics from GitHub to mirror remotes.
/// Uses the same interval as visibility sync.
#[serde(default)]
pub(crate) sync_metadata: bool,
/// When true (default), the daemon AUTOMATICALLY skips the
/// `codeberg` remote when pushing to a private repo. Codeberg's
/// 85 GiB global quota makes it unsuitable as a private-repo
/// backup target — the quota fills up fast with game art /
/// source. By keeping codeberg out of the private-repo push
/// path, we preserve the 85 GiB for the small handful of
/// public repos where codeberg is genuinely useful as a
/// non-corporate marketing surface.
///
/// Per-repo override via `codeberg_public_only = false` in
/// `<repo>/.dracon/dracon-sync.toml` (forces codeberg push
/// regardless of repo visibility). Per-repo override
/// `codeberg_public_only = true` is a no-op since the global
/// default is already true.
///
/// The visibility check reads the cached state written by
/// `sync_visibility` / `sync_mirror_visibility` in
/// `visibility.rs`. If no cache exists yet, the daemon
/// falls back to "private" (safe default: skip codeberg)
/// until the next visibility sync refreshes it.
///
/// Set to false to restore the pre-policy behavior of
/// pushing every repo to every remote.
///
/// ADDED 2026-07-17 (goal `codeberg-public-only`):
/// see `docs/design/codeberg-public-only-policy-2026-07-17.md`.
#[serde(default = "default_codeberg_public_only")]
pub(crate) codeberg_public_only: bool,
/// When true, version bumps automatically create a git tag (e.g. v0.2.0).
/// Tags are cheap and reversible — default is true.
/// Per-repo override via `auto_tag` in .dracon/dracon-sync.toml.
#[serde(default = "default_true")]
pub(crate) auto_tag: bool,
/// When true, major version bumps create a GitHub Release.
/// Releases are public-facing milestones — default is false.
/// Per-repo override via `auto_release` in .dracon/dracon-sync.toml.
#[serde(default)]
pub(crate) auto_release: bool,
/// Master toggle for auto-publishing to package registries after version bumps.
/// Requires per-repo opt-in via `auto_publish` in `.dracon/dracon-sync.toml`.
#[serde(default)]
pub(crate) auto_publish: bool,
/// Configured package registry publish targets.
#[serde(default)]
pub(crate) publish_targets: Vec<PublishTarget>,
/// When true, version bumps in repos with a `flake.nix` create a PR updating
/// the flake's version field (in addition to tagging and publishing).
/// Default is false.
#[serde(default)]
pub(crate) nix_auto_update: bool,
/// Standard files to ensure exist in every synced repository.
/// Short form (filename string) resolves to `templates/{name}` in the sync config dir.
/// Long form allows specifying explicit source/target paths and overwrite behavior.
#[serde(default, deserialize_with = "deserialize_standard_files")]
pub(crate) standard_files: Vec<StandardFileConfig>,
/// Automatically copy standard files during the sync cycle.
/// When true (default), standard files are auto-copied to repos during sync.
/// When false, use `dracon-sync scaffold` to apply on demand.
#[serde(default = "default_true")]
pub(crate) standard_files_auto: bool,
/// `dracon-sync repos` "active" threshold (in minutes). A repo is
/// labelled `active` only when it is clean, in sync, and both commit
/// and push are within this window. Default: 5 minutes.
#[serde(default = "default_active_commit_minutes")]
pub(crate) active_commit_minutes: u64,
/// `dracon-sync repos` "committing" threshold (in minutes). A repo
/// with unpushed commits, or whose last commit is between
/// `active_commit_minutes` and this value, is labelled `committing`.
/// Default: 60 minutes.
#[serde(default = "default_committing_commit_minutes")]
pub(crate) committing_commit_minutes: u64,
/// `dracon-sync repos` "cold" threshold (in minutes). A repo whose
/// last commit is older than this is labelled `cold`. Default:
/// 1440 minutes (24 hours).
#[serde(default = "default_cold_commit_minutes")]
pub(crate) cold_commit_minutes: u64,
}
/// Package registry type for auto-publish.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum PublishRegistry {
#[default]
CratesIo,
Npm,
Pypi,
}
impl PublishRegistry {
pub(crate) fn as_str(&self) -> &'static str {
match self {
PublishRegistry::CratesIo => "crates-io",
PublishRegistry::Npm => "npm",
PublishRegistry::Pypi => "pypi",
}
}
}
/// A configured package registry publish target.
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
pub(crate) struct PublishTarget {
/// Human-readable name for this target (used in per-repo opt-in lists).
pub(crate) name: String,
/// Registry type (crates-io, npm, pypi).
pub(crate) registry: PublishRegistry,
/// Environment variable name or secret file key for the auth token.
/// Loaded via `load_secret()` from env or `~/.dracon/utilities/sync/secrets/`.
pub(crate) token_secret: String,
/// Timeout for the publish command in seconds.
#[serde(default = "default_publish_timeout_secs")]
pub(crate) publish_timeout_secs: u64,
}
fn default_publish_timeout_secs() -> u64 {
300
}
fn default_active_commit_minutes() -> u64 {
5
}
fn default_committing_commit_minutes() -> u64 {
60
}
fn default_cold_commit_minutes() -> u64 {
1440
}
#[derive(Debug, Deserialize, serde::Serialize, Default, Clone)]
pub(crate) struct RepoPolicyOverride {
/// Optional per-repo override for `auto_bump_versions`.
pub(crate) auto_bump_versions: Option<bool>,
/// Optional per-repo override for `build_artifact_cleanup`
/// (v0.113.33 — v0.113.29 added the SyncPolicy field but forgot
/// this override-struct half, so the per-repo
/// `.dracon/dracon-sync.toml` opt-out parsed into thin air and
/// the ai-auto-writer output/ ping-pong kept running in
/// production despite `build_artifact_cleanup = false` being set).
#[serde(default)]
pub(crate) build_artifact_cleanup: Option<bool>,
/// Per-repo override for auto-tagging. Defaults to true (inherited from global).
/// Set to false to disable version tags for this repo.
#[serde(default)]
pub(crate) auto_tag: Option<bool>,
/// Per-repo override for GitHub Releases on major bumps.
/// Defaults to false (inherited from global auto_release).
#[serde(default)]
pub(crate) auto_release: Option<bool>,
/// Per-repo list of publish target names to auto-publish to.
/// Only used when global `auto_publish = true`.
#[serde(default)]
pub(crate) auto_publish: Vec<String>,
/// Per-repo override for nix flake auto-update. Defaults to false (inherited from global).
/// Set to true to enable auto-creating PRs for flake version updates.
#[serde(default)]
pub(crate) nix_auto_update: Option<bool>,
/// Per-repo list of standard file targets to skip.
/// Use the target filename (e.g., "LICENSE") not the source path.
#[serde(default)]
pub(crate) skip_standard_files: Vec<String>,
/// When true, the daemon recognizes this repo as intentionally
/// untracked by any remote (for example, a local working tree that
/// mirrors a different public clone, or a legacy-isolated repo).
/// With this flag set:
///
/// - `NO_UPSTREAM` is replaced by the explicit `INTENTIONAL_NO_UPSTREAM`
/// flag in `repos` output, so the row is not classified as a
/// hidden concern.
/// - `repair concerns` skips the repo entirely.
/// - The auto-repair path never runs `git push -u origin HEAD`, so the
/// daemon will not attempt to wire the local branch to a remote the
/// operator has explicitly chosen to leave unconnected.
/// - The hint for the row says
/// `"intentional legacy isolation, no upstream configured"`.
///
/// Default: false. Set in `<repo>/.dracon/dracon-sync.toml`.
#[serde(default)]
pub(crate) intentional_no_upstream: bool,
/// Per-repo override for `active_commit_minutes`. None means inherit
/// the global value. See [`SyncPolicy::active_commit_minutes`].
#[serde(default)]
pub(crate) active_commit_minutes: Option<u64>,
/// Per-repo override for `committing_commit_minutes`. None means
/// inherit the global value.
#[serde(default)]
pub(crate) committing_commit_minutes: Option<u64>,
/// Per-repo override for `cold_commit_minutes`. None means inherit
/// the global value.
#[serde(default)]
pub(crate) cold_commit_minutes: Option<u64>,
/// Per-repo list of glob patterns for TRACKED files the daemon
/// should NOT auto-commit. See
/// [`SyncPolicy::auto_commit_exclude_patterns`]. None means
/// inherit the global value. Each entry is a glob
/// (e.g. `"**/test-results/**"` or `"*.log"`).
#[serde(default)]
pub(crate) auto_commit_exclude_patterns: Option<Vec<String>>,
/// ADDED 2026-07-22 (v0.112.34, audit F1.16): opt-in for the
/// DESTRUCTIVE excluded-path semantics. When `Some(true)`,
/// files matching `auto_commit_exclude_patterns` are reverted to
/// HEAD after each commit (`git restore --staged --worktree` —
/// the pre-v0.112.34 behavior), i.e. "these files must always
/// equal HEAD". When `Some(false)` or absent (the default),
/// excluded files are only UNSTAGED (operator edits preserved):
/// the exclusion means "don't auto-commit these", never
/// "delete the operator's work".
#[serde(default)]
pub(crate) revert_excluded_to_head: Option<bool>,
/// Per-repo ownership override. Some(false) is the explicit hard
/// opt-out, even beneath an owned watch root. Some(true) is retained
/// for backwards compatibility and forces Owned. None follows path
/// ownership beneath configured watch roots and the legacy heuristic
/// outside them.
#[serde(default)]
pub(crate) owned: Option<bool>,
/// Per-repo override for `auto_skip_unowned`. Some(false)
/// re-enables the daemon for a specific unowned repo (the
/// operator has confirmed they want to push into it). Some
/// (true) overrides to skip. None inherits the global
/// policy.
#[serde(default)]
pub(crate) auto_skip_unowned: Option<bool>,
/// Per-repo override for `settling_max_delay_secs`. None
/// inherits the global value. See
/// [`SyncPolicy::settling_max_delay_secs`].
#[serde(default)]
#[allow(dead_code)]
// intentional future-policy config; not yet wired into runtime. Audit AUDIT-3-UTILITIES-2026-07-10.md CONCERN #6.
pub(crate) settling_max_delay_secs: Option<u64>,
/// Per-repo override for `dirty_max_age_action`. None
/// inherits the global value.
#[serde(default)]
#[allow(dead_code)]
// intentional future-policy config; not yet wired into runtime. Audit AUDIT-3-UTILITIES-2026-07-10.md CONCERN #6.
pub(crate) dirty_max_age_action: Option<DirtyMaxAgeAction>,
/// Optional per-repo override for `stale_dirty_alert_secs`.
/// None inherits the global value. See
/// [`SyncPolicy::stale_dirty_alert_secs`].
#[serde(default)]
pub(crate) stale_dirty_alert_secs: Option<u64>,
/// Per-repo list of remote names to skip when configuring
/// and pushing mirrors. Each entry is a remote name as
/// defined in the global `[[remotes]]` config (e.g. "gitlab").
/// When a remote is in this list, the daemon will not
/// add the remote to `.git/config` and will not attempt to
/// push to it. Default: empty (no exclusion). Set in
/// `<repo>/.dracon/dracon-sync.toml`.
///
/// Added 2026-06-23 (goal mqqsyzyd-qkvna5) so a repo whose
/// mirror is permanently unavailable (e.g. over a free-tier
/// storage quota) can opt out of that mirror without
/// affecting other repos that use it.
#[serde(default)]
pub(crate) exclude_remotes: Vec<String>,
/// Per-repo override for `codeberg_public_only`. Some(false)
/// forces the daemon to push this PRIVATE repo to codeberg
/// (opt-in override of the global public-only default).
/// Some(true) is a no-op (already the global default).
/// None inherits the global `policy.codeberg_public_only`.
///
/// Use case: a repo that's currently private but the operator
/// has decided needs a codeberg backup regardless (e.g. a
/// critical config repo that's small enough to not threaten
/// the 85 GiB quota). Setting this to `false` is the explicit
/// operator authorization for codeberg push on a private repo.
///
/// ADDED 2026-07-17 (goal `codeberg-public-only`):
/// see `docs/design/codeberg-public-only-policy-2026-07-17.md`.
#[serde(default)]
pub(crate) codeberg_public_only: Option<bool>,
/// Per-repo opt-in to codeberg auto-create when the global
/// `[[remotes]]` config has `auto_create = false` for codeberg
/// (the v0.112.28 default, to protect the 85 GiB grace quota).
/// Some(true) re-enables codeberg auto-create for this specific
/// repo. Some(false) is a no-op (already the global default).
/// None inherits the global `auto_create` per remote.
///
/// Use case: a repo the operator explicitly wants on codeberg
/// (e.g. for archival or because the operator has verified it
/// is small + non-bloat-prone). Set in
/// `<repo>/.dracon/dracon-sync.toml`.
///
/// ADDED 2026-07-20 (goal v0.112.28):
/// see `docs/design/codeberg-quota-leak-fix-2026-07-13.md` for
/// the 85 GiB context.
#[serde(default)]
pub(crate) auto_create_on_codeberg: Option<bool>,
}
pub(crate) fn default_true() -> bool {
true
}
pub(crate) fn default_pulse_interval() -> u64 {
1
}
pub(crate) fn default_trailing_drain_deadline_secs() -> u64 {
120
}
pub(crate) fn default_inactivity_push_delay_secs() -> u64 {
2
}
pub(crate) fn load_repo_override(repo: &Path) -> RepoPolicyOverride {
let path = repo.join(".dracon").join("dracon-sync.toml");
let Ok(content) = std::fs::read_to_string(&path) else {
return RepoPolicyOverride::default();
};
toml::from_str(&content).unwrap_or_else(|e| {
eprintln!("⚠️ failed to parse repo override {}: {}", path.display(), e);
RepoPolicyOverride::default()
})
}
pub(crate) fn default_exclude_dir_names() -> Vec<String> {
[
"target",
"node_modules",
".cache",
".direnv",
".venv",
"dist",
"build",
"archives",
".tmp-*",
]
.into_iter()
.map(String::from)
.collect()
}
/// Default exclude patterns for `exclude_file_patterns` (TRACKED file
/// modifications). Operator policy change 2026-06-15 (goal `9aaf0b08`):
/// "commit all unless we have a super good reason to leave it out like
/// over 100 megs". Logs and DB files are now committed (operator can
/// `git rm` them later if desired). Per-repo `auto_commit_exclude_patterns`
/// still applies for operator-defined per-repo exclusions.
pub(crate) fn default_exclude_file_patterns() -> Vec<String> {
Vec::new()
}
/// Default exclude patterns for `untracked_exclude_patterns`. The daemon
/// will NOT auto-stage untracked files matching any of these patterns.
///
/// Policy evolution:
/// - 2026-06-15 (goal `9aaf0b08`): operator switched to "commit all
/// unless we have a super good reason to leave it out". The list was
/// reduced to scratch-only patterns. Patterns REMOVED in that change
/// (now committed by default): user notes (`**/note.md`,
/// `**/notes.md`, `**/scratch.md`), audit/evidence dirs, and image/
/// video extensions — see `AUDIT-3-UTILITIES-2026-07-10.md`.
/// - 2026-07-13 (codeberg quota leak fix): added 9 DIR-level patterns
/// for unambiguous collection directories that appeared as untracked
/// noise on every game/heavy repo. These are NAME-BASED, not
/// extension-based, so they do not collide with intentional shipping
/// art (PNGs/MP3s in `static/`, `assets/`, `screenshots/<game>/`).
/// See `docs/design/codeberg-quota-leak-fix-2026-07-13.md`.
///
/// The 9 added patterns (verified empirically against 17 watched repos,
/// no false positives on intentional content like 1mg marketing shots
/// or audit REPORTS in `docs/audit-*.md` / `scripts/audit-*.mjs`):
/// - `**/.pi/**` universal agent dir (.pi/, .pi-tmp/,
/// .pi-goals/, .pi-tasks/, .pi/mmx-out/)
/// - `**/test-results/**` Playwright outputs (named with git SHA)
/// - `**/verify-screenshots/**` verification harness output
/// - `**/__screenshots__/**` Python e2e framework convention
/// - `**/.state-recon/**` agent probe dirs
/// - `**/chrome-screenshots/**` chrome agent output
/// - `**/chrome-*/**` chrome-fixes, chrome-consistency, etc.
/// - `**/sign-in-flash-audit/**` one-off verification dir
/// - `**/~/**` home-dir leak (e.g. browser-extensions-
/// shared had a stray `~/` from a misrouted
/// extraction; this catches it globally)
///
/// Forward-compatibility: any future agent tool that drops a
/// screenshot into one of these names is automatically excluded from
/// auto-stage. New tools using different names will be flagged by
/// `dracon-sync scan-bloat` for the operator's manual review (see
/// `docs/design/codeberg-quota-leak-fix-2026-07-13.md`).
///
/// Per-repo `auto_commit_exclude_patterns` is still the operator's
/// opt-in mechanism to extend this list per-repo.
pub(crate) fn default_untracked_exclude_patterns() -> Vec<String> {
[
// Session / agent scratch dirs — keep local
"**/scratch/**",
"**/scratch-*",
"**/scratch_*",
"**/tmp/**",
"**/tmp-*",
"**/pi-tmp/**",
"**/.pi-tmp/**",
"**/research/scratch/**",
// Agent session state — never auto-stage
".demon/**",
".sisyphus/**",
".ralph/**",
// Codeberg quota leak fix (2026-07-13): unambiguous DIR-level
// collections emitted by agents, harnesses, and verification
// tools. See rustdoc above.
"**/.pi/**",
"**/test-results/**",
"**/verify-screenshots/**",
"**/__screenshots__/**",
"**/.state-recon/**",
"**/chrome-screenshots/**",
"**/chrome-*/**",
"**/sign-in-flash-audit/**",
"**/~/**",
]
.into_iter()
.map(String::from)
.collect()
}
pub(crate) fn default_max_stage_file_bytes() -> u64 {
100 * 1024 * 1024
}
fn default_max_stage_batch_files() -> usize {
// CHANGED 2026-06-20: 100 -> 100000. The batch limit was splitting
// large Playwright test runs into multiple commits, slowing sync.
// With 100000, the daemon commits everything it can in one cycle.
100000
}
pub(crate) fn default_auto_resolve_unmerged() -> bool {
// Default: true. The daemon's commit-all policy should never
// be blocked by a stale unmerged index. When the working tree
// matches HEAD (verified byte-by-byte), the unmerge is safe to
// reset.
true
}
pub(crate) fn default_push_debounce_secs() -> u64 {
// Default: 30s. Eliminates per-commit push churn while still
// keeping the remotes up-to-date within a reasonable window.
30
}
pub(crate) fn default_untracked_warn_threshold() -> usize {
// Default: 500. Emits a warning when the untracked count
// exceeds this. Set to 0 to disable.
500
}
pub(crate) fn default_pull_op_timeout_secs() -> u64 {
30
}
pub(crate) fn default_push_op_timeout_secs() -> u64 {
300
}
pub(crate) fn default_auto_gc_garbage_threshold_bytes() -> u64 {
// 2 GiB — below GitHub's per-push pack limit, large enough that
// normal loose-object churn never triggers it.
2 * 1024 * 1024 * 1024
}
pub(crate) fn default_repo_sync_timeout_secs() -> u64 {
420
}
pub(crate) fn default_stage_op_timeout_secs() -> u64 {
60
}
pub(crate) fn default_stage_cooldown_secs() -> u64 {
3600
}
pub(crate) fn default_push_retries() -> u32 {
3
}
pub(crate) fn default_repair_cooldown_secs() -> u64 {
60
}
pub(crate) fn default_max_push_blob_bytes() -> u64 {
DEFAULT_GIT_HOST_BLOB_LIMIT_BYTES
}
pub(crate) fn default_sem_max_concurrent_sync() -> usize {
4
}
pub(crate) fn default_incident_ledger_max_lines() -> usize {
10_000
}
pub(crate) fn default_incident_ledger_max_age_days() -> u64 {
30
}
fn default_github_account() -> String {
"DraconDev".to_string()
}
fn default_alert_unpushed_threshold() -> usize {
10
}
fn default_auto_commit_backstop_threshold() -> usize {
20
}
fn default_auto_commit_backstop_min_age_secs() -> u64 {
300
}
fn default_push_max_retries() -> u32 {
5
}
pub(crate) fn default_trusted_emails() -> Vec<String> {
vec!["dracsharp@gmail.com".to_string()]
}
pub(crate) fn default_trusted_authors() -> Vec<String> {
vec!["DraconDev".to_string()]
}
pub(crate) fn default_trusted_remote_hosts() -> Vec<String> {
// CHANGED 2026-07-02 (goal `354fe3cb`):
// Added case-insensitive entries for `DraconDev` (uppercase D)
// because the SSH remote URL convention in this monorepo is
// `git@gitlab.com:DraconDev/<repo>.git` (capital D), but the
// legacy trusted list used `dracondev` (lowercase). The case
// mismatch caused the daemon's ownership detector to flag
// every DraconDev-owned repo on gitlab as `untrusted_origin`
// and skip auto-push.
//
// Case-insensitive matching is left to the caller so the
// existing list can be tightened later. The lowercase forms
// are retained for backwards compatibility with any policy
// file overrides.
vec![
"github.com/DraconDev".to_string(),
"github.com/dracondev".to_string(),
"gitlab.com/DraconDev".to_string(),
"gitlab.com/dracondev".to_string(),
"codeberg.org/DraconDev".to_string(),
"codeberg.org/dracondev".to_string(),
]
}
pub(crate) fn default_settling_max_delay_secs() -> u64 {
60
}
pub(crate) fn default_min_commit_interval_secs() -> u64 {
5
}
pub(crate) fn default_stale_dirty_alert_secs() -> u64 {
600
}
pub(crate) fn default_dirty_max_age_action() -> DirtyMaxAgeAction {
DirtyMaxAgeAction::Commit
}
/// What the daemon should do when a dirty repo has been dirty
/// continuously for longer than `settling_max_delay_secs`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
#[derive(Default)]
pub(crate) enum DirtyMaxAgeAction {
/// Force-commit the current working tree state, regardless of
/// fingerprint stability. Default.
#[default]
Commit,
/// Log a warning to stderr but do NOT commit. The operator
/// must intervene.
Warn,
/// Do nothing. Same as `Warn` but with no log line.
Ignore,
}
fn default_sync_visibility_interval_hours() -> u64 {
24
}
fn default_codeberg_public_only() -> bool {
// Default true: codeberg has an 85 GiB global quota, so it's only
// safe as a public-repo marketing mirror. See SyncPolicy field
// docstring for rationale. ADDED 2026-07-17.
true
}
impl SyncPolicy {
pub(crate) fn load(path: &Path) -> Result<Self> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("failed to read policy {}", path.display()))?;
let mut policy: Self = toml::from_str(&content)
.with_context(|| format!("failed to parse policy {}", path.display()))?;
if policy.exclude_dir_names.is_empty() {
policy.exclude_dir_names = default_exclude_dir_names();
}
if policy.max_stage_file_bytes == 0 {
policy.max_stage_file_bytes = default_max_stage_file_bytes();
}
if policy.pull_op_timeout_secs == 0 {
policy.pull_op_timeout_secs = default_pull_op_timeout_secs();
}
if policy.push_op_timeout_secs == 0 {
policy.push_op_timeout_secs = default_push_op_timeout_secs();
}
if policy.repo_sync_timeout_secs == 0 {
policy.repo_sync_timeout_secs = default_repo_sync_timeout_secs();
}
if policy.stage_op_timeout_secs == 0 {
policy.stage_op_timeout_secs = default_stage_op_timeout_secs();
}
if policy.push_retries == 0 {
policy.push_retries = default_push_retries();
}
if policy.inactivity_push_delay_secs == 0 {
policy.inactivity_push_delay_secs = default_inactivity_push_delay_secs();
}
if policy.repair_cooldown_secs == 0 {
policy.repair_cooldown_secs = default_repair_cooldown_secs();
}
if policy.max_push_blob_bytes == 0 {
policy.max_push_blob_bytes = default_max_push_blob_bytes();
}
if policy.incident_ledger_max_lines == 0 {
policy.incident_ledger_max_lines = default_incident_ledger_max_lines();
}
if policy.incident_ledger_max_age_days == 0 {
policy.incident_ledger_max_age_days = default_incident_ledger_max_age_days();
}
if policy.pull_op_timeout_secs < 5 {
eprintln!(
"⚠️ pull_op_timeout_secs {} below minimum 5s, adjusting",
policy.pull_op_timeout_secs
);
policy.pull_op_timeout_secs = 5;
}
if policy.push_op_timeout_secs < 10 {
eprintln!(
"⚠️ push_op_timeout_secs {} below minimum 10s, adjusting",
policy.push_op_timeout_secs
);
policy.push_op_timeout_secs = 10;
}
if policy.stage_op_timeout_secs < 10 {
eprintln!(
"⚠️ stage_op_timeout_secs {} below minimum 10s, adjusting",
policy.stage_op_timeout_secs
);
policy.stage_op_timeout_secs = 10;
}
if policy.stage_cooldown_secs == 0 {
policy.stage_cooldown_secs = default_stage_cooldown_secs();
}
policy.max_push_blob_bytes = policy
.max_push_blob_bytes
.clamp(1, DEFAULT_GIT_HOST_BLOB_LIMIT_BYTES);
policy.repo_sync_timeout_secs = policy.repo_sync_timeout_secs.max(
policy
.push_op_timeout_secs
.saturating_add(30)
.max(policy.pull_op_timeout_secs.saturating_add(30)),
);
Ok(policy)
}
pub(crate) fn watch_root_paths(&self) -> Vec<PathBuf> {
self.watch_roots
.iter()
.map(PathBuf::from)
.filter(|p| {
if !p.exists() {
eprintln!("⚠️ watch root {} does not exist, skipping", p.display());
false
} else {
true
}
})
.collect()
}
/// Return true when `repo` is beneath one of the explicitly configured
/// watch roots. Configured path membership is the daemon's ownership
/// signal; per-repo `owned = false` remains the explicit opt-out.
pub(crate) fn path_is_owned(&self, repo: &Path) -> bool {
let repo = std::fs::canonicalize(repo).unwrap_or_else(|_| repo.to_path_buf());
self.watch_roots.iter().any(|root| {
let root = PathBuf::from(root);
let root = std::fs::canonicalize(&root).unwrap_or(root);
repo == root || repo.starts_with(&root)
})
}
}
pub(crate) fn resolve_policy_path() -> Result<PathBuf> {
let home = dirs::home_dir().context("home not found")?;
if let Ok(val) = std::env::var("DRACON_SYNC_POLICY") {
return Ok(PathBuf::from(val));
}
let paths = [
home.join(".dracon/utilities/sync/dracon-sync.toml"),
home.join(".dracon/utilities/sync/config.toml"),
home.join(".dracon/git/dracon-git.toml"),
];
for path in &paths {
if path.exists() {
return Ok(path.clone());
}
}
anyhow::bail!("sync policy not found")
}
#[derive(Debug, Default)]
pub(crate) struct ValidateResult {
pub errors: Vec<String>,
pub warnings: Vec<String>,
}
impl ValidateResult {
fn error(&mut self, msg: String) {
self.errors.push(msg);
}
fn warn(&mut self, msg: String) {
self.warnings.push(msg);
}
pub(crate) fn is_valid(&self) -> bool {
self.errors.is_empty()
}
}
pub(crate) fn validate_config(policy_path: &Path) -> ValidateResult {
let mut result = ValidateResult::default();
let content = match std::fs::read_to_string(policy_path) {
Ok(c) => c,
Err(e) => {
result.error(format!(
"cannot read policy {}: {}",
policy_path.display(),
e
));
return result;
}
};
let policy: SyncPolicy = match toml::from_str(&content) {
Ok(p) => p,
Err(e) => {
result.error(format!("TOML parse error: {}", e));
return result;
}
};
for root in &policy.watch_roots {
let path = Path::new(root);
if !path.exists() {
result.error(format!("watch root does not exist: {}", root));
} else if !path.is_dir() {
result.error(format!("watch root is not a directory: {}", root));
}
}
if policy.watch_roots.is_empty() {
result.error("no watch_roots defined (no directories will be synced)".to_string());
}
for (idx, remote) in policy.remotes.iter().enumerate() {
if remote.push_url.is_empty() {
result.error(format!(
"remote[{}] '{}': push_url is empty",
idx, remote.name
));
}
if remote.auto_create {
// Empty auto_create_account is intentionally silent: resolve_account()
// extracts the account from the push_url (e.g. git@host:account/{repo}.git
// → account). This is a working default that has shipped for years.
if let Some(token_var) = &remote.auto_create_token_var {
if token_var.is_empty() {
result.error(format!(
"remote[{}] '{}': auto_create_token_var is set but empty",
idx, remote.name
));
} else if std::env::var(token_var).is_err() {
let secrets_dir = crate::secrets::sync_secrets_dir();
let secrets_path =
secrets_dir.join(format!("{}.env", token_var.to_lowercase()));
if !secrets_path.exists() {
result.warn(format!(
"remote[{}] '{}': auto_create_token_var '{}' not in env and no secret file at {}",
idx, remote.name, token_var, secrets_path.display()
));
}
}
}
if remote.effective_auth_type() == crate::policy::AuthType::Codeberg {
if let Some(api_endpoint) = &remote.api_endpoint {
if api_endpoint.is_empty() {
result.error(format!(
"remote[{}] '{}': auth_type=codeberg but api_endpoint is empty",
idx, remote.name
));
} else if !api_endpoint.starts_with("http://")
&& !api_endpoint.starts_with("https://")
{
result.error(format!(
"remote[{}] '{}': api_endpoint '{}' is not a valid URL",
idx, remote.name, api_endpoint
));
}
} else {
// No api_endpoint set → fall back to the Codeberg default
// (https://codeberg.org). Working default, intentionally silent.
}
}
} else if !remote.push_url.contains("{repo}") && !remote.push_url.contains("{account}") {
result.warn(format!(
"remote[{}] '{}': push_url '{}' has no {{repo}} or {{account}} placeholder — repo names will not be substituted",
idx, remote.name, remote.push_url
));
}
for (local_name, remote_name) in &remote.repo_name_map {
if local_name.is_empty() {
result.error(format!(
"remote[{}] '{}': repo_name_map has empty local name (maps to '{}')",
idx, remote.name, remote_name
));
}
if remote_name.is_empty() {
result.error(format!(
"remote[{}] '{}': repo_name_map local '{}' maps to empty remote name",
idx, remote.name, local_name
));
}
if local_name.contains('/') || local_name.contains('\\') {
result.error(format!(
"remote[{}] '{}': repo_name_map local name '{}' is not a valid directory name",
idx, remote.name, local_name
));
}
}
}
if policy.remotes.is_empty() {
result.warn("no remotes defined (push operations will have no destination)".to_string());
}
for (idx, pattern) in policy.exclude_dir_names.iter().enumerate() {
if pattern.is_empty() {
result.warn(format!("exclude_dir_names[{}] is empty string", idx));
}
}
for (idx, pattern) in policy.exclude_file_patterns.iter().enumerate() {
if pattern.is_empty() {
result.warn(format!("exclude_file_patterns[{}] is empty string", idx));
}
}
// F40 (2026-07-18): standard_files[].target must be a relative
// path with no `..` segments. Otherwise `repo.join(target)` either
// replaces the base entirely (absolute path) or escapes the repo
// (parent traversal). A config typo would be a write-anywhere
// primitive under the daemon's UID.
for (idx, sf) in policy.standard_files.iter().enumerate() {
let target_str = sf.target.as_str();
if target_str.is_empty() {
result.error(format!("standard_files[{}].target is empty", idx));
continue;
}
let target_path = std::path::Path::new(target_str);
let abs = target_path.is_absolute();
let has_parent = target_path
.components()
.any(|c| matches!(c, std::path::Component::ParentDir));
let has_root = target_path
.components()
.any(|c| matches!(c, std::path::Component::RootDir));
let has_prefix = target_path
.components()
.any(|c| matches!(c, std::path::Component::Prefix(_)));
if abs || has_parent || has_root || has_prefix {
result.error(format!(
"standard_files[{}].target '{}' is not a relative path inside the repo \
(must not be absolute, contain '..', or contain a Windows drive prefix)",
idx, target_str
));
}
// CHANGED 2026-07-26 (v0.113.4, audit SYNC-H5): source
// validation was absolute-only — `..` escapes (and the
// tilde-expansion bypass of the absolute check) were missed,
// and the daemon path never ran validation at all. The same
// rule is now ALSO enforced at the point of use in
// `ensure_standard_files`.
let source_str = sf.source.as_str();
if !is_safe_standard_file_path(source_str) {
result.error(format!(
"standard_files[{}].source '{}' is not a safe relative path \
(must not be absolute or contain '..'; '~/...' is allowed and \
resolves under the operator's home)",
idx, source_str
));
}
}
if policy.auto_github_private && policy.auto_github_private_account.is_empty() {
result
.error("auto_github_private=true but auto_github_private_account is empty".to_string());
}
if policy.pulse_interval_secs == 0 {
result.error("pulse_interval_secs must be > 0".to_string());
}
if policy.push_retries == 0 {
result.error("push_retries must be > 0".to_string());
}
if policy.max_stage_file_bytes == 0 {
result.error("max_stage_file_bytes must be > 0".to_string());
}
if policy.stage_op_timeout_secs < 10 {
result.warn(format!(
"stage_op_timeout_secs {} below recommended minimum 10s",
policy.stage_op_timeout_secs
));
}
if policy.stage_cooldown_secs < 60 {
result.warn(format!(
"stage_cooldown_secs {} below recommended minimum 60s; very short cooldowns can flood the incident ledger",
policy.stage_cooldown_secs
));
}
if policy.pull_op_timeout_secs < 5 {
result.warn(format!(
"pull_op_timeout_secs {} below recommended minimum 5s",
policy.pull_op_timeout_secs
));
}
if policy.push_op_timeout_secs < 10 {
result.warn(format!(
"push_op_timeout_secs {} below recommended minimum 10s",
policy.push_op_timeout_secs
));
}
let min_repo_sync_timeout = policy
.push_op_timeout_secs
.saturating_add(30)
.max(policy.pull_op_timeout_secs.saturating_add(30));
if policy.repo_sync_timeout_secs < min_repo_sync_timeout {
result.warn(format!(
"repo_sync_timeout_secs {} below recommended minimum {}s (push/pull timeout + 30s safety margin)",
policy.repo_sync_timeout_secs, min_repo_sync_timeout
));
}
if policy.inactivity_push_delay_secs == 0 {
result.warn("inactivity_push_delay_secs = 0 means the daemon may commit partial changes before quiet time elapses".to_string());
}
if policy.repair_cooldown_secs < 10 {
result.warn(format!(
"repair_cooldown_secs {} below recommended minimum 10s; very short cooldowns can flood the incident ledger",
policy.repair_cooldown_secs
));
}
if policy.incident_ledger_max_lines < 100 {
result.warn(format!(
"incident_ledger_max_lines {} below recommended minimum 100; recent-push-failure classification may lose context",
policy.incident_ledger_max_lines
));
}
if policy.incident_ledger_max_age_days == 0 {
result.warn(
"incident_ledger_max_age_days = 0 disables age-based ledger retention".to_string(),
);
}
if let Some(ref url) = policy.webhook_url {
if !url.starts_with("http://") && !url.starts_with("https://") {
result.error(format!(
"webhook_url '{}' is not a valid http/https URL",
url
));
}
}
check_toml_field_ordering(&content, &mut result);
result
}
fn check_toml_field_ordering(content: &str, result: &mut ValidateResult) {
let mut first_section_pos: Option<usize> = None;
let mut pos = 0;
let bytes = content.as_bytes();
let mut in_table = false; // inside a [[remotes]] or [[...]] table entry
// ADDED 2026-07-21 (v0.112.33, audit M20/F3.2): which [[table]]
// we're inside (for the absorbed-key check below).
let mut current_table: Option<String> = None;
// ADDED 2026-07-21 (v0.112.33, audit M20/F3.2): known field
// names per table. TOML absorbs trailing bare keys into the LAST
// [[table]] entry — a misplaced top-level field after any
// [[remotes]]/[[standard_files]] block is (a) silently ignored
// by serde (no deny_unknown_fields on the table structs) and (b)
// NOT warned about by the pre-fix checker (which skipped ALL
// keys inside [[tables]]). Verified live during the audit: the
// operator's own config has `standard_files_auto = true`
// absorbed into the last [[standard_files]] entry TODAY.
const REMOTE_KEYS: &[&str] = &[
"name",
"push_url",
"auto_create",
"auto_create_account",
"auth_type",
"priority",
"api_endpoint",
"auto_create_token_var",
"repo_name_map",
"force_push_when_behind",
];
const STANDARD_FILE_KEYS: &[&str] = &["source", "target", "overwrite"];
while pos < bytes.len() {
let line_start = pos;
while pos < bytes.len() && bytes[pos] != b'\n' {
pos += 1;
}
let line = &content[line_start..pos];
let stripped = line.trim();
if stripped.starts_with("[[") {
// Enters a new table entry — fields inside are table-scoped, not top-level
in_table = true;
current_table = stripped
.trim_start_matches('[')
.trim_end_matches(']')
.split('.')
.next()
.map(|s| s.trim().to_string());
if first_section_pos.is_none() {
first_section_pos = Some(line_start);
}
} else if stripped.starts_with('[') && !stripped.starts_with("[[") {
// Single-bracket section like [repo_name_map], [extra_remotes]
in_table = false;
current_table = None;
if first_section_pos.is_none() {
first_section_pos = Some(line_start);
}
} else if !stripped.is_empty() && !stripped.starts_with('#') && stripped.contains('=') {
let (key, _) = stripped.split_once('=').unwrap_or((stripped, ""));
let key = key.trim();
// ADDED 2026-07-21 (v0.112.33, audit M20/F3.2): inside a
// [[table]], warn when a bare key is NOT a known field of
// that table — the signature of a misplaced top-level
// field being silently absorbed (or a typo'd table key).
if in_table && !key.is_empty() && !key.starts_with('"') && !key.starts_with('\'') {
let known = match current_table.as_deref() {
Some("remotes") => Some(REMOTE_KEYS),
Some("standard_files") => Some(STANDARD_FILE_KEYS),
_ => None,
};
if let Some(known_keys) = known {
if !key.contains('.') && !known_keys.contains(&key) {
result.warn(format!(
"field '{}' inside [[{}]] is not a known {} field -- if you meant it \
as a TOP-LEVEL field (e.g. standard_files_auto), it is being silently \
absorbed into the last table entry by the TOML parser; move it above \
the first [section] block",
key,
current_table.as_deref().unwrap_or("?"),
current_table.as_deref().unwrap_or("?")
));
}
}
}
if let Some(first_sec) = first_section_pos {
// Only warn for top-level fields after a section header.
// Fields inside [[remotes]] table entries are correctly placed.
if line_start > first_sec
&& !in_table
&& !key.starts_with('"')
&& !key.starts_with('\'')
&& !key.is_empty()
&& !key.contains('{')
&& !key.contains('.')
{
result.warn(format!(
"field '{}' appears after a section header -- top-level fields \
must be defined before any [section] or [[remotes]] block or \
they will be silently ignored by the TOML parser (they become \
table fields instead)",
key
));
}
}
}
pos += 1;
}
}
pub(crate) fn env_freeze_enabled() -> bool {
matches!(
std::env::var("DRACON_SYNC_FREEZE")
.unwrap_or_default()
.to_ascii_lowercase()
.as_str(),
"1" | "true" | "yes" | "on"
)
}
pub(crate) fn debug_enabled() -> bool {
matches!(
std::env::var("DRACON_SYNC_DEBUG")
.unwrap_or_default()
.to_ascii_lowercase()
.as_str(),
"1" | "true" | "yes" | "on"
)
}
pub(crate) fn freeze_marker_paths(_policy_path: &Path) -> Vec<PathBuf> {
let mut paths = Vec::new();
// Freeze markers are intentionally kept out of git-tracked repos to avoid accidental
// perpetual DIRTY states and surprise "sync frozen" incidents.
//
// Canonical locations:
// - ~/.dracon/dracon-sync.freeze
// - ~/.dracon/freeze/dracon-sync
if let Some(home) = dirs::home_dir() {
paths.push(home.join(".dracon").join("dracon-sync.freeze"));
paths.push(home.join(".dracon").join("freeze").join("dracon-sync"));
}
paths
}
/// Default freeze-marker TTL: 24 hours. Markers older than this are auto-cleared
/// and a warning is logged to prevent indefinite pause from a forgotten `pause`.
///
/// The 2026-06-04 incident (1h23m of stale freeze, 3 CONCERN repos) is the
/// motivating example. See `.dracon/project-state.md` for details.
pub(crate) const FREEZE_MARKER_TTL_SECS: u64 = 24 * 60 * 60;
/// If a freeze marker exists but is older than `FREEZE_MARKER_TTL_SECS`,
/// auto-clear it and log a warning. Returns `Some(reason)` if sync should
/// still be frozen (marker is fresh or no marker).
pub(crate) fn freeze_reason(policy_path: &Path) -> Option<String> {
if env_freeze_enabled() {
return Some("env DRACON_SYNC_FREEZE".to_string());
}
for marker in freeze_marker_paths(policy_path) {
if marker.exists() {
// Check TTL — auto-expire stale markers
if let Ok(meta) = std::fs::metadata(&marker) {
if let Ok(modified) = meta.modified() {
if let Ok(age) = modified.elapsed() {
if age.as_secs() > FREEZE_MARKER_TTL_SECS {
eprintln!(
"⚠️ freeze marker at {} is stale ({:.0}h old, TTL {}s); auto-clearing to prevent indefinite pause",
marker.display(),
age.as_secs() as f64 / 3600.0,
FREEZE_MARKER_TTL_SECS
);
let _ = std::fs::remove_file(&marker);
continue;
}
}
}
}
return Some(format!("marker {}", marker.display()));
}
}
None
}
pub(crate) fn open_policy_in_editor(policy_path: &Path) -> Result<()> {
let mut editors = Vec::new();
if let Ok(visual) = std::env::var("VISUAL") {
if !visual.trim().is_empty() {
editors.push(visual);
}
}
if let Ok(editor) = std::env::var("EDITOR") {
if !editor.trim().is_empty() {
editors.push(editor);
}
}
for fallback in ["nvim", "vim", "nano", "vi"] {
editors.push(fallback.to_string());
}
for editor in editors {
match StdCommand::new(editor.trim()).arg(policy_path).status() {
Ok(status) if status.success() => return Ok(()),
Ok(status) => {
return Err(anyhow::anyhow!(
"editor exited non-zero ({}). policy: {}",
status,
policy_path.display()
));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => {
return Err(anyhow::anyhow!(
"failed to launch editor '{}' for {}: {}",
editor,
policy_path.display(),
e
));
}
}
}
Err(anyhow::anyhow!(
"no editor available. set VISUAL or EDITOR to open {}",
policy_path.display()
))
}
#[cfg(test)]
pub(crate) fn test_sync_policy() -> SyncPolicy {
SyncPolicy {
auto_prune_stale_backup_branches: false,
system_repo: String::new(),
pulse_interval_secs: 1,
trailing_drain_deadline_secs: 120,
inactivity_push_delay_secs: 5,
auto_commit: true,
auto_bump_versions: true,
auto_pull: true,
auto_push: true,
backup_policy: String::new(),
backup_dir: String::new(),
exclude_repos: vec![],
exclude_dir_names: vec![],
exclude_file_patterns: vec![],
auto_repair_concerns: true,
build_artifact_cleanup: true,
auto_repair_warns: true,
auto_rewrite_large_blobs: true,
auto_stage_untracked: true,
untracked_exclude_patterns: default_untracked_exclude_patterns(),
auto_commit_exclude_patterns: Vec::new(),
watch_roots: vec![],
remotes: vec![],
auto_github_private: false,
auto_github_private_account: "DraconDev".to_string(),
max_stage_file_bytes: 100 * 1024 * 1024,
max_stage_batch_files: 100000,
auto_resolve_unmerged: default_auto_resolve_unmerged(),
push_debounce_secs: default_push_debounce_secs(),
untracked_warn_threshold: default_untracked_warn_threshold(),
pull_op_timeout_secs: 30,
push_op_timeout_secs: 300,
auto_gc_garbage_threshold_bytes: default_auto_gc_garbage_threshold_bytes(),
repo_sync_timeout_secs: 420,
stage_op_timeout_secs: 60,
stage_cooldown_secs: 3600,
push_retries: 3,
repair_cooldown_secs: 60,
max_push_blob_bytes: 100 * 1024 * 1024,
sem_max_concurrent_sync: default_sem_max_concurrent_sync(),
incident_ledger_max_lines: 10_000,
incident_ledger_max_age_days: 30,
webhook_url: None,
alert_unpushed_threshold: 10,
auto_commit_backstop_threshold: 20,
auto_commit_backstop_min_age_secs: 300,
push_max_retries: 5,
auto_skip_unowned: true,
trusted_emails: default_trusted_emails(),
trusted_authors: default_trusted_authors(),
trusted_remote_hosts: default_trusted_remote_hosts(),
settling_max_delay_secs: 60,
dirty_max_age_action: DirtyMaxAgeAction::Commit,
min_commit_interval_secs: 5,
stale_dirty_alert_secs: 600,
sync_visibility: false,
sync_visibility_interval_hours: 24,
sync_metadata: false,
codeberg_public_only: true, // default; tests that need override set explicitly
auto_tag: true,
auto_release: false,
auto_publish: false,
publish_targets: vec![],
nix_auto_update: false,
standard_files: vec![],
standard_files_auto: true,
active_commit_minutes: 5,
committing_commit_minutes: 60,
cold_commit_minutes: 1440,
}
}
#[cfg(test)]
mod tests {
use super::*;
/// v0.113.29: the build-artifact tracked-path cleanup defaults ON
/// for TOML-loaded configs (serde default) and is deserializable
/// as a per-repo opt-out. NOTE: `SyncPolicy::default()` (derived)
/// gives `false` for every bool — the documented derive-Default
/// footgun shared with `auto_repair_concerns` & siblings; the
/// serde default is what governs real configs.
#[test]
fn test_build_artifact_cleanup_default_true_and_opt_out() {
let p: SyncPolicy = toml::from_str("").expect("parse empty");
assert!(p.build_artifact_cleanup, "missing field must default true");
let p: SyncPolicy = toml::from_str("build_artifact_cleanup = false").expect("parse");
assert!(!p.build_artifact_cleanup, "per-repo opt-out must parse");
// Derived Default matches its auto_* siblings (false).
assert!(!SyncPolicy::default().build_artifact_cleanup);
}
// ====================================================================
// Per-repo override COVERAGE tripwire (v0.113.34, operator:
// "prevent such things automatically, not hack every case").
//
// The v0.113.29/v0.113.33 incident class: a knob was added to
// SyncPolicy and consumed in sync.rs, but its RepoPolicyOverride
// half was forgotten — per-repo `.dracon/dracon-sync.toml`
// settings parsed into thin air (serde ignores unknown fields),
// and the bug only surfaced in production months later.
//
// This test makes that structurally impossible: every SyncPolicy
// field must EITHER have a RepoPolicyOverride counterpart OR be
// listed in GLOBAL_ONLY below; every override field must name a
// global field OR be listed in OVERRIDE_ONLY. Adding a field to
// either struct without deciding its per-repo story FAILS this
// test at `cargo test` time, not in production.
// ====================================================================
/// Global-only knobs (no per-repo override by design or pending a
/// demonstrated need — migrate an entry to RepoPolicyOverride when
/// a repo needs to tune it; the test then enforces the wiring).
const OVERRIDE_COVERAGE_GLOBAL_ONLY: &[&str] = &[
"alert_unpushed_threshold",
"auto_commit",
"auto_commit_backstop_min_age_secs",
"auto_commit_backstop_threshold",
"auto_gc_garbage_threshold_bytes",
"auto_github_private",
"auto_github_private_account",
"auto_prune_stale_backup_branches",
"auto_pull",
"auto_push",
"auto_repair_concerns",
"auto_repair_warns",
"auto_resolve_unmerged",
"auto_rewrite_large_blobs",
"auto_stage_untracked",
"backup_dir",
"backup_policy",
"exclude_dir_names",
"exclude_file_patterns",
"exclude_repos",
"inactivity_push_delay_secs",
"incident_ledger_max_age_days",
"incident_ledger_max_lines",
"max_push_blob_bytes",
"max_stage_batch_files",
"max_stage_file_bytes",
"min_commit_interval_secs",
"publish_targets",
"pull_op_timeout_secs",
"pulse_interval_secs",
"push_debounce_secs",
"push_max_retries",
"push_op_timeout_secs",
"push_retries",
"remotes",
"repair_cooldown_secs",
"repo_sync_timeout_secs",
"sem_max_concurrent_sync",
"stage_cooldown_secs",
"stage_op_timeout_secs",
"standard_files",
"standard_files_auto",
"sync_metadata",
"sync_visibility",
"sync_visibility_interval_hours",
"system_repo",
"trailing_drain_deadline_secs",
"trusted_authors",
"trusted_emails",
"trusted_remote_hosts",
"untracked_exclude_patterns",
"untracked_warn_threshold",
"watch_roots",
"webhook_url",
];
/// Override-only knobs (per-repo concepts with no meaningful
/// global counterpart).
const OVERRIDE_COVERAGE_OVERRIDE_ONLY: &[&str] = &[
"auto_create_on_codeberg",
"exclude_remotes",
"intentional_no_upstream",
"owned",
"revert_excluded_to_head",
"skip_standard_files",
];
fn serde_field_names<T: serde::Serialize>(v: &T) -> std::collections::BTreeSet<String> {
serde_json::to_value(v)
.expect("serialize")
.as_object()
.expect("struct serializes to object")
.keys()
.cloned()
.collect()
}
#[test]
fn test_repo_override_field_coverage_tripwire() {
let global = serde_field_names(&SyncPolicy::default());
let over = serde_field_names(&RepoPolicyOverride::default());
let mut failures = Vec::new();
for name in &global {
if OVERRIDE_COVERAGE_GLOBAL_ONLY.contains(&name.as_str()) {
continue;
}
if !over.contains(name) {
failures.push(format!(
"SyncPolicy field `{name}` has no RepoPolicyOverride counterpart — \
add it (with merge resolution at the point of use, see \
auto_bump_versions) or list it in OVERRIDE_COVERAGE_GLOBAL_ONLY"
));
}
}
for name in &over {
if OVERRIDE_COVERAGE_OVERRIDE_ONLY.contains(&name.as_str()) {
continue;
}
if !global.contains(name) {
failures.push(format!(
"RepoPolicyOverride field `{name}` names no SyncPolicy field — \
per-repo files would set a knob nothing consumes; add the global \
field or list it in OVERRIDE_COVERAGE_OVERRIDE_ONLY"
));
}
}
// The allow-lists must not rot: every entry must still name a
// real field on its side.
for name in OVERRIDE_COVERAGE_GLOBAL_ONLY {
if !global.contains(*name) {
failures.push(format!(
"GLOBAL_ONLY entry `{name}` is not a SyncPolicy field — stale list entry"
));
}
}
for name in OVERRIDE_COVERAGE_OVERRIDE_ONLY {
if !over.contains(*name) {
failures.push(format!("OVERRIDE_ONLY entry `{name}` is not a RepoPolicyOverride field — stale list entry"));
}
}
assert!(
failures.is_empty(),
"override coverage tripwire:\n - {}",
failures.join("\n - ")
);
}
#[test]
fn test_repo_override_build_artifact_cleanup_round_trip() {
// v0.113.33: the per-repo opt-out must round-trip through
// `load_repo_override` — v0.113.29 only tested SyncPolicy
// parsing, missing that `RepoPolicyOverride` lacked the field
// entirely, so ai-auto-writer's `.dracon/dracon-sync.toml`
// `build_artifact_cleanup = false` parsed into thin air and
// the output/ ping-pong kept running in production.
let dir = tempfile::tempdir().unwrap();
let repo = dir.path();
std::fs::create_dir_all(repo.join(".dracon")).unwrap();
std::fs::write(
repo.join(".dracon/dracon-sync.toml"),
"build_artifact_cleanup = false\n",
)
.unwrap();
let o = load_repo_override(repo);
assert_eq!(o.build_artifact_cleanup, Some(false));
// Absent file → None → global policy governs.
let dir2 = tempfile::tempdir().unwrap();
assert_eq!(load_repo_override(dir2.path()).build_artifact_cleanup, None);
}
/// ADDED 2026-07-21 (v0.112.33, audit M22/F3.4):
/// `expand_tilde("~/x")` must resolve to `$HOME/x` — the pre-fix
/// code kept the leading `/` after `~`, and `Path::join` with an
/// absolute argument replaces the base, producing `/x`
/// (filesystem root).
#[test]
fn test_expand_tilde_resolves_under_home() {
let home = dirs::home_dir().expect("home dir");
assert_eq!(
expand_tilde("~/templates/LICENSE"),
home.join("templates/LICENSE")
);
assert_eq!(expand_tilde("~"), home);
// `~x` (no slash) — not a real tilde form we support, but it
// must NOT resolve to a filesystem-root-relative path.
let tx = expand_tilde("~templates/x");
assert!(tx.starts_with(&home) || tx == std::path::Path::new("~templates/x"));
// Non-tilde paths pass through unchanged.
assert_eq!(
expand_tilde("templates/LICENSE"),
std::path::PathBuf::from("templates/LICENSE")
);
assert_eq!(
expand_tilde("/abs/path"),
std::path::PathBuf::from("/abs/path")
);
}
#[test]
fn test_default_exclude_dir_names() {
let dirs = default_exclude_dir_names();
assert!(dirs.contains(&"target".to_string()));
assert!(dirs.contains(&"node_modules".to_string()));
assert!(dirs.contains(&".cache".to_string()));
}
#[test]
fn test_default_exclude_file_patterns() {
// Goal 9aaf0b08 (2026-06-15): operator's "commit all unless
// super-good reason" policy. Default is now empty list.
// Logs/DBs are committed; operator can `git rm` them later.
let patterns = default_exclude_file_patterns();
assert!(
patterns.is_empty(),
"default_exclude_file_patterns should be empty under commit-all policy, got: {:?}",
patterns
);
}
#[test]
fn test_default_untracked_exclude_patterns_is_commit_all_unless_scratch() {
// Goal 9aaf0b08 (2026-06-15): operator's "commit all unless
// super-good reason" policy. Goal mrhvbn1s-codeberg-quota-leak-fix
// (2026-07-13): added 8 DIR-level patterns for unambiguous
// collection directories that the codeberg audit identified as
// ~10 GiB of fixable bloat. See
// `docs/design/codeberg-quota-leak-fix-2026-07-13.md`.
let patterns = default_untracked_exclude_patterns();
// Patterns that MUST be present (super-good reasons):
for required in [
// Original scratch / agent dirs from 2026-06-15
"**/scratch/**",
"**/scratch-*",
"**/scratch_*",
"**/tmp/**",
"**/tmp-*",
"**/pi-tmp/**",
"**/.pi-tmp/**",
".demon/**",
".sisyphus/**",
".ralph/**",
// Codeberg quota leak fix (2026-07-13) — dir-level patterns
"**/.pi/**",
"**/test-results/**",
"**/verify-screenshots/**",
"**/__screenshots__/**",
"**/.state-recon/**",
"**/chrome-screenshots/**",
"**/chrome-*/**",
"**/sign-in-flash-audit/**",
"**/~/**",
] {
assert!(
patterns.contains(&required.to_string()),
"default_untracked_exclude_patterns must contain `{}` (super-good reason), got: {:?}",
required,
patterns
);
}
// Patterns that MUST NOT be present (operator wants committed):
// The audit binary/text split (e.g. `**/audit-*/**/*.png`)
// cannot be expressed with the current matcher (no multi-*
// glob), and per `codeberg-quota-leak-fix-2026-07-13.md` the
// operator opted for DIR-level filtering only. Tests for the
// intentional-content preservation rules live in
// `test_default_untracked_exclude_patterns_preserves_intentional_content`
// below.
for forbidden in [
"**/audit/**", // intentional audit evidence
"**/evidence/**", // intentional evidence
"**/screenshots/**", // intentional screenshots (1mg marketing lives here)
"*.png", // media (intentional game art is committed via `git add`)
"*.jpg",
"*.jpeg",
"*.gif",
"*.webp",
"*.mp4",
"*.mov",
"**/note.md", // notes
"**/notes.md",
"**/NOTE.md",
"**/scratch.md",
] {
assert!(
!patterns.contains(&forbidden.to_string()),
"default_untracked_exclude_patterns must NOT contain `{}` (operator wants committed), got: {:?}",
forbidden,
patterns
);
}
}
/// Codeberg quota leak fix (2026-07-13): every DIR-level pattern
/// added must preserve intentional shipping content. The matcher is
/// substring-based (see `exclude::matches_untracked_exclude`), so
/// the live patterns are tested against real-world paths that the
/// codeberg quota audit identified as MUST-KEEP:
/// - `web/screenshots/one-mil-girls-screenshots/*.png` (1mg marketing)
/// - `docs/audit-event-2026-07-06.md` (audit REPORTS — text, useful in git)
/// - `scripts/audit-uiux-2026-06-26.mjs` (audit SCRIPTS — code, useful in git)
/// - `static/assets/texture.png` (intentional game art)
/// - `src/lib.rs` (source)
/// - `web/build/output.js` (build output, but committed at user's discretion)
///
/// These MUST NOT be matched by `default_untracked_exclude_patterns`.
#[test]
fn test_default_untracked_exclude_patterns_preserves_intentional_content() {
use std::path::Path;
let patterns = default_untracked_exclude_patterns();
let repo = Path::new("/repo");
for path in [
// 1mg marketing (1mi-release-art, kept in git by operator)
"web/screenshots/one-mil-girls-screenshots/01-title.png",
"web/screenshots/one-mil-girls-screenshots/02-gameplay.jpg",
// Audit REPORTS (text — operator reads them through git log)
"docs/audit-event-2026-07-06.md",
"docs/audit-a11y-v1.md",
// Audit SCRIPTS (code — committed for traceability)
"scripts/audit-uiux-2026-06-26.mjs",
"scripts/audit-html-2026-06-10.mjs",
// Intentional game art (committed via `git add art.png`)
"static/assets/texture.png",
"static/sprites/player.png",
"assets/audio/theme.mp3",
// Source code
"src/lib.rs",
"src/main.ts",
// Build output that operator occasionally commits
"web/build/output.js",
// Game-specific KEEP paths
"web/screenshots/capture-anime-girls-screenshots/promo.png",
] {
assert!(
!crate::exclude::matches_untracked_exclude(
repo,
Path::new(path),
&patterns,
),
"default_untracked_exclude_patterns MUST NOT match intentional content at `{}` (use the operator review loop via `dracon-sync scan-bloat` instead)",
path
);
}
}
#[test]
fn test_default_max_stage_file_bytes() {
let bytes = default_max_stage_file_bytes();
assert_eq!(bytes, 100 * 1024 * 1024);
}
#[test]
fn test_default_pull_op_timeout_secs() {
let secs = default_pull_op_timeout_secs();
assert_eq!(secs, 30);
}
#[test]
fn test_default_push_op_timeout_secs() {
let secs = default_push_op_timeout_secs();
assert_eq!(secs, 300);
}
#[test]
fn test_default_repo_sync_timeout_secs() {
let secs = default_repo_sync_timeout_secs();
assert_eq!(secs, 420);
}
#[test]
fn test_default_push_retries() {
let retries = default_push_retries();
assert_eq!(retries, 3);
}
#[test]
fn test_default_repair_cooldown_secs() {
let secs = default_repair_cooldown_secs();
assert_eq!(secs, 60);
}
#[test]
fn test_default_stage_op_timeout_secs() {
let secs = default_stage_op_timeout_secs();
assert_eq!(secs, 60);
assert!(secs >= 10, "stage timeout must be at least 10s");
}
#[test]
fn test_default_stage_cooldown_secs() {
let secs = default_stage_cooldown_secs();
// 1 hour default — long enough to stop the incident ledger from
// being spammed every ~70s by repos whose working tree is too
// large to stage within stage_op_timeout_secs.
assert_eq!(secs, 3600);
}
#[test]
fn test_default_max_push_blob_bytes() {
let bytes = default_max_push_blob_bytes();
assert_eq!(bytes, DEFAULT_GIT_HOST_BLOB_LIMIT_BYTES);
}
#[test]
fn test_default_incident_ledger_max_lines() {
let lines = default_incident_ledger_max_lines();
assert_eq!(lines, 10_000);
}
#[test]
fn test_default_incident_ledger_max_age_days() {
let days = default_incident_ledger_max_age_days();
assert_eq!(days, 30);
}
#[test]
fn test_debug_enabled() {
let _guard = VarGuard::set_temp("DRACON_SYNC_DEBUG", "");
assert!(!debug_enabled());
}
#[test]
fn test_default_true() {
assert!(default_true());
}
#[test]
fn test_default_pulse_interval() {
assert_eq!(default_pulse_interval(), 1);
}
#[test]
fn test_default_inactivity_push_delay_secs() {
assert_eq!(default_inactivity_push_delay_secs(), 2);
}
#[test]
fn test_default_trusted_emails() {
let emails = default_trusted_emails();
assert!(emails.contains(&"dracsharp@gmail.com".to_string()));
}
#[test]
fn test_default_trusted_authors() {
let authors = default_trusted_authors();
assert!(authors.contains(&"DraconDev".to_string()));
}
#[test]
fn test_default_trusted_remote_hosts_includes_three_platforms() {
let hosts = default_trusted_remote_hosts();
assert!(hosts.iter().any(|h| h.contains("github.com")));
assert!(hosts.iter().any(|h| h.contains("gitlab.com")));
assert!(hosts.iter().any(|h| h.contains("codeberg.org")));
}
#[test]
fn test_default_settling_max_delay_secs_is_60() {
assert_eq!(default_settling_max_delay_secs(), 60);
}
#[test]
fn test_default_min_commit_interval_secs_is_5() {
assert_eq!(default_min_commit_interval_secs(), 5);
}
#[test]
fn test_default_dirty_max_age_action_is_commit() {
assert_eq!(default_dirty_max_age_action(), DirtyMaxAgeAction::Commit);
}
#[test]
fn test_dirty_max_age_action_default_is_commit() {
assert_eq!(DirtyMaxAgeAction::default(), DirtyMaxAgeAction::Commit);
}
#[test]
fn test_dirty_max_age_action_serde_kebab_case() {
// Verify the serde rename_all = "kebab-case" works
// both ways. The TOML is "commit" (or
// "warn" or "ignore") and the Rust enum is
// `Commit` / `Warn` / `Ignore`.
#[derive(serde::Deserialize)]
struct Wrap {
action: DirtyMaxAgeAction,
}
let toml = "action = \"warn\"\n";
let w: Wrap = toml::from_str(toml).expect("parse warn");
assert_eq!(w.action, DirtyMaxAgeAction::Warn);
let toml = "action = \"commit\"\n";
let w: Wrap = toml::from_str(toml).expect("parse commit");
assert_eq!(w.action, DirtyMaxAgeAction::Commit);
let toml = "action = \"ignore\"\n";
let w: Wrap = toml::from_str(toml).expect("parse ignore");
assert_eq!(w.action, DirtyMaxAgeAction::Ignore);
}
#[test]
fn test_test_sync_policy_has_new_fields() {
// Regression: the test fixture must be kept in sync
// with the SyncPolicy struct. If a new field is
// added, the test fixture will fail to compile
// (good — forces the author to think about the
// default).
let p = test_sync_policy();
assert!(p.auto_skip_unowned);
assert!(!p.trusted_emails.is_empty());
assert!(!p.trusted_authors.is_empty());
assert!(!p.trusted_remote_hosts.is_empty());
assert_eq!(p.settling_max_delay_secs, 60);
assert_eq!(p.dirty_max_age_action, DirtyMaxAgeAction::Commit);
assert_eq!(p.min_commit_interval_secs, 5);
}
#[test]
fn test_repo_override_parses_new_fields() {
// Per-repo override TOML should parse the new
// fields. Backward compat: missing fields
// default to None / inherit global.
let toml = r#"
owned = true
auto_skip_unowned = false
settling_max_delay_secs = 30
dirty_max_age_action = "warn"
"#;
let parsed: RepoPolicyOverride = toml::from_str(toml).expect("parse override");
assert_eq!(parsed.owned, Some(true));
assert_eq!(parsed.auto_skip_unowned, Some(false));
assert_eq!(parsed.settling_max_delay_secs, Some(30));
assert_eq!(parsed.dirty_max_age_action, Some(DirtyMaxAgeAction::Warn));
}
#[test]
fn test_repo_override_missing_new_fields_defaults_none() {
// Backward compat: an old override TOML without
// the new fields should parse with all new
// fields as None.
let toml = r#"
auto_bump_versions = false
"#;
let parsed: RepoPolicyOverride = toml::from_str(toml).expect("parse old override");
assert_eq!(parsed.owned, None);
assert_eq!(parsed.auto_skip_unowned, None);
assert_eq!(parsed.settling_max_delay_secs, None);
assert_eq!(parsed.dirty_max_age_action, None);
}
#[test]
fn test_default_sem_max_concurrent_sync_is_four() {
assert_eq!(default_sem_max_concurrent_sync(), 4);
}
/// Regression test: the apply-phase deadline is derived from
/// `pulse_interval_secs` so the daemon main loop is bounded
/// against a slow push. The deadline is `pulse_interval_secs * 2`
/// with a minimum of 2s.
#[test]
fn test_apply_deadline_derived_from_pulse_interval() {
// Default pulse_interval_secs is 1; the deadline is 1*2 = 2.
let p = SyncPolicy::default();
let expected = p.pulse_interval_secs.max(1) * 2;
assert_eq!(expected, 2);
}
#[test]
fn test_git_host_blob_limit() {
assert_eq!(DEFAULT_GIT_HOST_BLOB_LIMIT_BYTES, 100 * 1024 * 1024);
}
#[test]
fn test_timestamp_secs_returns_reasonable_value() {
let ts = timestamp_secs();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
assert!(ts > 0);
assert!(ts <= now + 1);
}
#[test]
fn test_sync_policy_defaults_produce_valid_values() {
let policy = test_sync_policy();
assert!(policy.pulse_interval_secs >= 1);
assert!(policy.inactivity_push_delay_secs >= 1);
assert!(policy.max_stage_file_bytes > 0);
assert!(policy.pull_op_timeout_secs >= 5);
assert!(policy.push_op_timeout_secs >= 10);
}
fn test_sync_policy() -> SyncPolicy {
super::test_sync_policy()
}
#[test]
fn test_repo_policy_override_default() {
let override_default = crate::policy::RepoPolicyOverride::default();
assert!(override_default.auto_bump_versions.is_none());
}
#[test]
fn test_freeze_marker_paths() {
let paths = freeze_marker_paths(std::path::Path::new("/fake/path.toml"));
assert!(!paths.is_empty());
}
#[test]
fn test_load_repo_override_nonexistent() {
let repo = std::path::Path::new("/nonexistent/path/for/test");
let override_ = load_repo_override(repo);
assert!(override_.auto_bump_versions.is_none());
}
#[test]
fn test_load_repo_override_intentional_no_upstream() {
// A repo's per-repo `.dracon/dracon-sync.toml` setting
// `intentional_no_upstream = true` must round-trip through
// `load_repo_override`. Default when the file is absent must
// remain `false` so the existing concern classification path
// is unchanged for any repo that has not opted in.
let dir = tempfile::tempdir().unwrap();
let repo = dir.path();
std::fs::create_dir_all(repo.join(".dracon")).unwrap();
std::fs::write(
repo.join(".dracon/dracon-sync.toml"),
"intentional_no_upstream = true\n",
)
.unwrap();
let override_ = load_repo_override(repo);
assert!(override_.intentional_no_upstream);
}
#[test]
fn test_load_repo_override_intentional_no_upstream_default_false() {
// When the per-repo override file is absent, the field must
// default to false so the new opt-in is non-breaking.
let dir = tempfile::tempdir().unwrap();
let repo = dir.path();
let override_ = load_repo_override(repo);
assert!(!override_.intentional_no_upstream);
}
// ========================================================================
// Tests for exclude_remotes (goal mqqsyzyd-qkvna5, 2026-06-23)
//
// The `exclude_remotes` field is the per-repo opt-out for a specific
// mirror. Default is empty (no exclusion). The platform uses this
// to disable gitlab pushes (free-tier storage quota exceeded).
// ========================================================================
#[test]
fn test_load_repo_override_exclude_remotes() {
// A repo's per-repo `.dracon/dracon-sync.toml` setting
// `exclude_remotes = ["gitlab"]` must round-trip through
// `load_repo_override`.
let dir = tempfile::tempdir().unwrap();
let repo = dir.path();
std::fs::create_dir_all(repo.join(".dracon")).unwrap();
std::fs::write(
repo.join(".dracon/dracon-sync.toml"),
"exclude_remotes = [\"gitlab\"]\n",
)
.unwrap();
let override_ = load_repo_override(repo);
assert_eq!(override_.exclude_remotes, vec!["gitlab".to_string()]);
}
#[test]
fn test_load_repo_override_exclude_remotes_default_empty() {
// When the per-repo override file is absent, `exclude_remotes`
// must default to an empty vec so the new opt-in is non-breaking
// for the 12 other repos that use gitlab.
let dir = tempfile::tempdir().unwrap();
let repo = dir.path();
let override_ = load_repo_override(repo);
assert!(
override_.exclude_remotes.is_empty(),
"default exclude_remotes must be empty, got {:?}",
override_.exclude_remotes
);
}
// ---- Tests for codeberg_public_only policy (goal ----
// ---- `codeberg-public-only`, 2026-07-17) ----
#[test]
fn test_default_codeberg_public_only_is_true() {
// The global default for `codeberg_public_only` must be `true`
// so that out-of-the-box the daemon uses codeberg as a
// public-only marketing mirror. Operators can flip it off via
// `codeberg_public_only = false` in the global config, or via
// the per-repo override.
assert!(
default_codeberg_public_only(),
"global default for codeberg_public_only must be true"
);
}
#[test]
fn test_load_repo_override_codeberg_public_only_some_false() {
// Per-repo override `codeberg_public_only = false` must
// round-trip through `load_repo_override` as `Some(false)`.
// This is the explicit operator opt-in to push a private
// repo to codeberg.
let dir = tempfile::tempdir().unwrap();
let repo = dir.path();
std::fs::create_dir_all(repo.join(".dracon")).unwrap();
std::fs::write(
repo.join(".dracon/dracon-sync.toml"),
"codeberg_public_only = false\n",
)
.unwrap();
let override_ = load_repo_override(repo);
assert_eq!(override_.codeberg_public_only, Some(false));
}
#[test]
fn test_load_repo_override_codeberg_public_only_some_true() {
// Per-repo override `codeberg_public_only = true` must
// round-trip as `Some(true)`. This is a no-op when the global
// default is already true, but useful when the operator has
// flipped the global default off for most repos and wants to
// re-enable it for one specific private repo.
let dir = tempfile::tempdir().unwrap();
let repo = dir.path();
std::fs::create_dir_all(repo.join(".dracon")).unwrap();
std::fs::write(
repo.join(".dracon/dracon-sync.toml"),
"codeberg_public_only = true\n",
)
.unwrap();
let override_ = load_repo_override(repo);
assert_eq!(override_.codeberg_public_only, Some(true));
}
#[test]
fn test_load_repo_override_codeberg_public_only_default_none() {
// When the per-repo override file is absent OR the field is
// not set, `codeberg_public_only` must default to `None` so
// the per-repo override inherits the global policy. This is
// the "default" path for the ~30 watched repos that don't
// need an explicit per-repo declaration.
let dir = tempfile::tempdir().unwrap();
let repo = dir.path();
let override_ = load_repo_override(repo);
assert_eq!(
override_.codeberg_public_only, None,
"default per-repo codeberg_public_only must be None (inherit global), got {:?}",
override_.codeberg_public_only
);
}
#[test]
fn test_sync_policy_codeberg_public_only_field_default_true() {
// Loading a minimal TOML that doesn't mention
// `codeberg_public_only` must produce a `SyncPolicy` with
// `codeberg_public_only = true` (the global default).
let toml = r#"
system_repo = "/tmp/test"
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert!(
policy.codeberg_public_only,
"default SyncPolicy.codeberg_public_only must be true, got {}",
policy.codeberg_public_only
);
}
#[test]
fn test_sync_policy_codeberg_public_only_explicit_false() {
// Operator can disable the policy site-wide by setting
// `codeberg_public_only = false` in the global config.
let toml = r#"
codeberg_public_only = false
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert!(
!policy.codeberg_public_only,
"explicit codeberg_public_only = false must be honored"
);
}
static POLICY_ENV_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
struct VarGuard {
var: String,
original: Option<String>,
_lock: std::sync::MutexGuard<'static, ()>,
}
impl VarGuard {
fn set_temp(var: &str, value: &str) -> Self {
// v0.113.31: tolerate a poisoned lock — a panicking env
// test used to cascade-fail EVERY later VarGuard user at
// this unwrap (observed 2026-07-31 when a real
// ~/.dracon/dracon-sync.freeze marker failed one freeze
// test and 2 innocent tests died at line 2622). The
// guard's purpose is serialization, not integrity — a
// poisoned mutex still serializes.
let lock = POLICY_ENV_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let original = std::env::var(var).ok();
if value.is_empty() {
std::env::remove_var(var);
} else {
std::env::set_var(var, value);
}
Self {
var: var.to_string(),
original,
_lock: lock,
}
}
}
impl Drop for VarGuard {
fn drop(&mut self) {
if let Some(orig) = self.original.take() {
std::env::set_var(&self.var, orig);
} else {
std::env::remove_var(&self.var);
}
}
}
#[test]
fn test_env_freeze_enabled_ignores_case() {
let _guard = VarGuard::set_temp("DRACON_SYNC_FREEZE", "TRUE");
assert!(env_freeze_enabled());
}
#[test]
fn test_env_freeze_enabled_accepts_yes() {
let _guard = VarGuard::set_temp("DRACON_SYNC_FREEZE", "yes");
assert!(env_freeze_enabled());
}
#[test]
fn test_env_freeze_enabled_accepts_on() {
let _guard = VarGuard::set_temp("DRACON_SYNC_FREEZE", "on");
assert!(env_freeze_enabled());
}
#[test]
fn test_env_freeze_enabled_rejects_false() {
let _guard = VarGuard::set_temp("DRACON_SYNC_FREEZE", "false");
assert!(!env_freeze_enabled());
}
#[test]
fn test_env_freeze_enabled_rejects_empty() {
let _guard = VarGuard::set_temp("DRACON_SYNC_FREEZE", "");
assert!(!env_freeze_enabled());
}
#[test]
fn test_debug_enabled_accepts_1() {
let _guard = VarGuard::set_temp("DRACON_SYNC_DEBUG", "1");
assert!(debug_enabled());
}
#[test]
fn test_debug_enabled_rejects_empty() {
let _guard = VarGuard::set_temp("DRACON_SYNC_DEBUG", "");
assert!(!debug_enabled());
}
#[test]
fn test_freeze_reason_env_takes_precedence() {
let _guard = VarGuard::set_temp("DRACON_SYNC_FREEZE", "1");
let reason = freeze_reason(std::path::Path::new("/fake/policy.toml"));
assert_eq!(reason, Some("env DRACON_SYNC_FREEZE".to_string()));
}
#[test]
fn test_freeze_reason_none_when_not_frozen() {
let _guard = VarGuard::set_temp("DRACON_SYNC_FREEZE", "");
// v0.113.31: isolate HOME — freeze_marker_paths probes the
// REAL ~/.dracon/ regardless of the policy path arg, so a
// live operator pause (dracon-sync.pause marker) failed this
// test on a real machine. The VarGuard above already holds
// the env mutex, so touching HOME here is serialized.
let tmp = tempfile::TempDir::new().unwrap();
let orig_home = std::env::var("HOME").ok();
std::env::set_var("HOME", tmp.path());
let reason = freeze_reason(std::path::Path::new("/fake/policy.toml"));
match orig_home {
Some(h) => std::env::set_var("HOME", h),
None => std::env::remove_var("HOME"),
}
assert!(reason.is_none());
}
#[test]
fn test_freeze_marker_paths_includes_dracondir() {
let paths = freeze_marker_paths(std::path::Path::new("/fake.toml"));
assert!(paths
.iter()
.any(|p| p.to_string_lossy().contains(".dracon")));
assert!(paths.iter().any(|p| p.to_string_lossy().contains("freeze")));
}
#[test]
fn test_resolve_policy_path_env_override() {
let _guard = VarGuard::set_temp("DRACON_SYNC_POLICY", "/custom/policy.toml");
let path = resolve_policy_path();
assert!(path.is_ok());
assert_eq!(path.unwrap(), PathBuf::from("/custom/policy.toml"));
}
#[test]
fn test_sync_policy_watch_roots_filters_nonexistent() {
let policy = SyncPolicy {
watch_roots: vec![
"/nonexistent/path/one".to_string(),
"/nonexistent/path/two".to_string(),
],
..test_sync_policy()
};
let roots = policy.watch_root_paths();
assert!(roots.is_empty());
}
#[test]
fn test_timestamp_secs_returns_increasing_values() {
let ts1 = timestamp_secs();
std::thread::sleep(std::time::Duration::from_millis(10));
let ts2 = timestamp_secs();
assert!(ts2 >= ts1);
}
#[test]
fn test_resolve_push_url_template_substitution() {
let config = RemoteConfig {
name: "github".to_string(),
push_url: "git@github.com:{account}/{repo}.git".to_string(),
auto_create: false,
auto_create_account: "myorg".to_string(),
auth_type: AuthType::GitHub,
priority: 50,
api_endpoint: None,
auto_create_token_var: None,
repo_name_map: Default::default(),
force_push_when_behind: false,
};
assert_eq!(
config.resolve_push_url("my-repo"),
"git@github.com:myorg/my-repo.git"
);
}
#[test]
fn test_resolve_push_url_no_template() {
let config = RemoteConfig {
name: "mirror".to_string(),
push_url: "git@mirror.example.com:fixed/path.git".to_string(),
auto_create: false,
auto_create_account: "".to_string(),
auth_type: AuthType::GitHub,
priority: 50,
api_endpoint: None,
auto_create_token_var: None,
repo_name_map: Default::default(),
force_push_when_behind: false,
};
assert_eq!(
config.resolve_push_url("any-repo"),
"git@mirror.example.com:fixed/path.git"
);
}
#[test]
fn test_resolve_push_url_account_only() {
let config = RemoteConfig {
name: "gitlab".to_string(),
push_url: "git@gitlab.com:{account}/".to_string(),
auto_create: false,
auto_create_account: "testuser".to_string(),
auth_type: AuthType::GitLab,
priority: 50,
api_endpoint: None,
auto_create_token_var: None,
repo_name_map: Default::default(),
force_push_when_behind: false,
};
assert_eq!(config.resolve_push_url("repo"), "git@gitlab.com:testuser/");
}
#[test]
fn test_resolve_push_url_with_name_mapping() {
let mut config = RemoteConfig {
name: "gitlab".to_string(),
push_url: "git@gitlab.com:{account}/{repo}.git".to_string(),
auto_create: false,
auto_create_account: "myorg".to_string(),
auth_type: AuthType::GitLab,
priority: 50,
api_endpoint: None,
auto_create_token_var: None,
repo_name_map: Default::default(),
force_push_when_behind: false,
};
config
.repo_name_map
.insert(".dracon".to_string(), "dracon-home".to_string());
assert_eq!(
config.resolve_push_url(".dracon"),
"git@gitlab.com:myorg/dracon-home.git"
);
assert_eq!(
config.resolve_push_url("other-repo"),
"git@gitlab.com:myorg/other-repo.git"
);
}
#[test]
fn test_resolve_repo_name_with_mapping() {
let mut config = RemoteConfig {
name: "gitlab".to_string(),
push_url: "git@gitlab.com:{account}/{repo}.git".to_string(),
auto_create: false,
auto_create_account: "myorg".to_string(),
auth_type: AuthType::GitLab,
priority: 50,
api_endpoint: None,
auto_create_token_var: None,
repo_name_map: Default::default(),
force_push_when_behind: false,
};
config
.repo_name_map
.insert(".dracon".to_string(), "dracon-home".to_string());
assert_eq!(config.resolve_repo_name(".dracon"), "dracon-home");
assert_eq!(config.resolve_repo_name("other-repo"), "other-repo");
}
#[test]
fn test_resolve_repo_name_without_mapping() {
let config = RemoteConfig {
name: "github".to_string(),
push_url: "https://github.com/{account}/{repo}.git".to_string(),
auto_create: false,
auto_create_account: "myorg".to_string(),
auth_type: AuthType::GitHub,
priority: 50,
api_endpoint: None,
auto_create_token_var: None,
repo_name_map: Default::default(),
force_push_when_behind: false,
};
assert_eq!(config.resolve_repo_name(".dracon"), ".dracon");
assert_eq!(config.resolve_repo_name("my-repo"), "my-repo");
}
#[test]
fn test_validate_config_valid_policy() {
let tmp = tempfile::TempDir::new().unwrap();
let content = r#"
auto_github_private = false
auto_commit = true
auto_pull = true
auto_push = true
auto_bump_versions = false
watch_roots = ["/tmp"]
remotes = []
"#;
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(
result.is_valid(),
"valid policy should pass: {:?}",
result.errors
);
}
#[test]
fn test_validate_config_warns_on_short_stage_cooldown_and_timeouts() {
let tmp = tempfile::TempDir::new().unwrap();
let content = r#"
auto_github_private = false
watch_roots = ["/tmp"]
remotes = []
stage_op_timeout_secs = 5
stage_cooldown_secs = 10
pull_op_timeout_secs = 1
push_op_timeout_secs = 5
repo_sync_timeout_secs = 5
inactivity_push_delay_secs = 0
repair_cooldown_secs = 1
incident_ledger_max_lines = 10
incident_ledger_max_age_days = 0
"#;
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(result.is_valid(), "short values warn but remain valid");
for expected in [
"stage_op_timeout_secs 5",
"stage_cooldown_secs 10",
"pull_op_timeout_secs 1",
"push_op_timeout_secs 5",
"repo_sync_timeout_secs 5",
"inactivity_push_delay_secs = 0",
"repair_cooldown_secs 1",
"incident_ledger_max_lines 10",
"incident_ledger_max_age_days = 0",
] {
assert!(
result.warnings.iter().any(|w| w.contains(expected)),
"missing warning for {expected}: {:?}",
result.warnings
);
}
}
#[test]
fn test_validate_config_missing_watch_root() {
let tmp = tempfile::TempDir::new().unwrap();
let content = r#"
auto_github_private = false
watch_roots = ["/nonexistent/path/that/does/not/exist"]
remotes = []
"#;
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(!result.is_valid(), "missing watch root should fail");
assert!(
result.errors.iter().any(|e| e.contains("does not exist")),
"should mention missing path"
);
}
#[test]
fn test_validate_config_rejects_path_traversal_in_standard_files() {
// F40 (2026-07-18): standard_files target must be a relative
// path inside the repo; absolute or `..` targets escape.
for (bad_target, why) in [
(r#""/etc/cron.daily/evil""#, "absolute path"),
(r#""../escape.txt""#, "parent traversal"),
(r#""a/../../b""#, "parent traversal mid-path"),
] {
let tmp = tempfile::TempDir::new().unwrap();
let content = format!(
r#"
auto_github_private = false
watch_roots = ["/tmp"]
remotes = []
standard_files = [{{ source = "templates/LICENSE", target = {bad_target}, overwrite = false }}]
"#
);
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(
!result.is_valid(),
"target {} ({}) must be rejected, got errors = {:?}",
bad_target,
why,
result.errors
);
assert!(
result
.errors
.iter()
.any(|e| e.contains("not a relative path")),
"target {} ({}) error message missing, got {:?}",
bad_target,
why,
result.errors
);
}
}
#[test]
fn test_validate_config_rejects_absolute_source_in_standard_files() {
// F40 follow-up: source is also a config field; reject if
// absolute (we want sources to live under the policy base).
let tmp = tempfile::TempDir::new().unwrap();
let content = r#"
auto_github_private = false
watch_roots = ["/tmp"]
remotes = []
standard_files = [{ source = "/etc/passwd", target = "README.md", overwrite = false }]
"#;
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(!result.is_valid(), "absolute source must be rejected");
assert!(
result
.errors
.iter()
.any(|e| e.contains("not a safe relative path")),
"source error message missing, got {:?}",
result.errors
);
}
#[test]
fn test_validate_config_rejects_parent_dir_source_in_standard_files() {
// ADDED 2026-07-26 (v0.113.4, audit SYNC-H5): `..` escapes in
// the source were not validated before (absolute-only check),
// and tilde expansion happened AFTER validation so
// `~/../../etc/passwd`-style raw sources passed.
let tmp = tempfile::TempDir::new().unwrap();
let content = r#"
auto_github_private = false
watch_roots = ["/tmp"]
remotes = []
standard_files = [{ source = "../../etc/passwd", target = "README.md", overwrite = false }]
"#;
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(!result.is_valid(), "parent-dir source must be rejected");
assert!(
result
.errors
.iter()
.any(|e| e.contains("not a safe relative path")),
"source error message missing, got {:?}",
result.errors
);
}
#[test]
fn test_validate_config_invalid_webhook_url() {
let tmp = tempfile::TempDir::new().unwrap();
let content = r#"
auto_github_private = false
watch_roots = ["/tmp"]
remotes = []
webhook_url = "ftp://invalid.example.com/hook"
"#;
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(!result.is_valid(), "non-http webhook URL should fail");
assert!(
result.errors.iter().any(|e| e.contains("webhook_url")),
"should mention webhook_url"
);
}
#[test]
fn test_validate_config_empty_remote_push_url() {
let tmp = tempfile::TempDir::new().unwrap();
let content = r#"
auto_github_private = false
watch_roots = ["/tmp"]
[[remotes]]
name = "test"
push_url = ""
"#;
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(!result.is_valid(), "empty push_url should fail");
}
#[test]
fn test_validate_config_empty_auto_create_account_is_silent() {
// Empty auto_create_account is silently accepted: resolve_account() extracts
// the account from the push_url. The config is valid AND the warning is
// intentionally suppressed (it was noise — see policy.rs).
let tmp = tempfile::TempDir::new().unwrap();
let content = r#"
auto_github_private = false
watch_roots = ["/tmp"]
[[remotes]]
name = "github"
push_url = "https://github.com/{account}/{repo}.git"
auto_create = true
auto_create_account = ""
"#;
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(
result.is_valid(),
"auto_create=true with empty account is valid (account extracted from push_url)"
);
assert!(
!result
.warnings
.iter()
.any(|w| w.contains("auto_create_account")),
"empty auto_create_account should not warn (resolve_account() handles it), got: {:?}",
result.warnings
);
}
#[test]
fn test_validate_config_no_watch_roots_error() {
let tmp = tempfile::TempDir::new().unwrap();
let content = r#"
auto_github_private = false
watch_roots = []
remotes = []
"#;
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(!result.is_valid(), "no watch_roots should fail");
assert!(
result.errors.iter().any(|e| e.contains("watch_roots")),
"should mention watch_roots"
);
}
#[test]
fn test_validate_config_warns_on_no_remotes() {
let tmp = tempfile::TempDir::new().unwrap();
let content = r#"
auto_github_private = false
watch_roots = ["/tmp"]
remotes = []
"#;
std::fs::write(tmp.path().join("policy.toml"), content).unwrap();
let result = validate_config(tmp.path().join("policy.toml").as_path());
assert!(result.is_valid(), "no remotes is a warning not error");
assert!(
result.warnings.iter().any(|w| w.contains("no remotes")),
"should warn about no remotes"
);
}
#[test]
fn test_standard_files_short_form() {
let toml = r#"
standard_files = ["LICENSE"]
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert_eq!(policy.standard_files.len(), 1);
assert_eq!(policy.standard_files[0].source, "templates/LICENSE");
assert_eq!(policy.standard_files[0].target, "LICENSE");
assert!(!policy.standard_files[0].overwrite);
}
#[test]
fn test_standard_files_short_form_funding_yml() {
// FUNDING.yml is the second default standard file. The short form must
// resolve its source to templates/FUNDING.yml and target to the repo
// root name. Repos that need the GitHub-required .github/ subdir must
// use the long form.
let toml = r#"
standard_files = ["LICENSE", "FUNDING.yml"]
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert_eq!(policy.standard_files.len(), 2);
assert_eq!(policy.standard_files[1].source, "templates/FUNDING.yml");
assert_eq!(policy.standard_files[1].target, "FUNDING.yml");
assert!(!policy.standard_files[1].overwrite);
}
#[test]
fn test_standard_files_funding_yml_github_subdir_long_form() {
// GitHub discovers FUNDING.yml at .github/FUNDING.yml. The long form
// is required to install the file in that subdirectory while still
// pulling the template from templates/FUNDING.yml.
let toml = r#"
[[standard_files]]
source = "templates/LICENSE"
target = "LICENSE"
[[standard_files]]
source = "templates/FUNDING.yml"
target = ".github/FUNDING.yml"
overwrite = false
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert_eq!(policy.standard_files.len(), 2);
let funding = &policy.standard_files[1];
assert_eq!(funding.source, "templates/FUNDING.yml");
assert_eq!(funding.target, ".github/FUNDING.yml");
assert!(!funding.overwrite);
}
#[test]
fn test_standard_files_long_form() {
let toml = r#"
[[standard_files]]
source = "templates/CUSTOM"
target = "NOTICE"
overwrite = true
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert_eq!(policy.standard_files.len(), 1);
assert_eq!(policy.standard_files[0].source, "templates/CUSTOM");
assert_eq!(policy.standard_files[0].target, "NOTICE");
assert!(policy.standard_files[0].overwrite);
}
#[test]
fn test_standard_files_mixed_form() {
let toml = r#"
[[standard_files]]
source = "templates/LICENSE"
target = "LICENSE"
[[standard_files]]
source = "templates/CUSTOM"
target = "NOTICE"
overwrite = true
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert_eq!(policy.standard_files.len(), 2);
assert_eq!(policy.standard_files[0].source, "templates/LICENSE");
assert_eq!(policy.standard_files[0].target, "LICENSE");
assert!(!policy.standard_files[0].overwrite);
assert_eq!(policy.standard_files[1].source, "templates/CUSTOM");
assert_eq!(policy.standard_files[1].target, "NOTICE");
assert!(policy.standard_files[1].overwrite);
}
#[test]
fn test_standard_files_empty() {
let toml = r#"
standard_files = []
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert!(policy.standard_files.is_empty());
}
#[test]
fn test_standard_files_default_empty() {
let toml = r#"
pulse_interval_secs = 1
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert!(policy.standard_files.is_empty());
}
#[test]
fn test_default_policy_does_not_force_funding_yml() {
// FUNDING.yml is Dracon-specific. External users must opt in explicitly;
// the default policy must not force it.
let policy = SyncPolicy::default();
assert!(policy.standard_files.is_empty());
assert!(!policy
.standard_files
.iter()
.any(|cfg| cfg.target == "FUNDING.yml" || cfg.target == ".github/FUNDING.yml"));
}
#[test]
fn test_license_only_policy_does_not_force_funding_yml() {
// A generic external user can keep the starter policy with only LICENSE.
let toml = r#"
standard_files = ["LICENSE"]
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert_eq!(policy.standard_files.len(), 1);
assert_eq!(policy.standard_files[0].target, "LICENSE");
assert!(!policy
.standard_files
.iter()
.any(|cfg| cfg.target == "FUNDING.yml" || cfg.target == ".github/FUNDING.yml"));
}
#[test]
fn test_standard_files_auto_default_true() {
let toml = r#"
pulse_interval_secs = 1
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert!(policy.standard_files_auto);
}
#[test]
fn test_standard_files_auto_explicit_true() {
let toml = r#"
pulse_interval_secs = 1
standard_files_auto = true
"#;
let policy: SyncPolicy = toml::from_str(toml).unwrap();
assert!(policy.standard_files_auto);
}
#[test]
fn test_validate_toml_field_ordering_warns_on_post_section_fields() {
use crate::policy::ValidateResult;
let toml = r#"
pulse_interval_secs = 1
[sync]
auto_pull = true
[remote "origin"]
url = "git@github.com:foo/bar.git"
"#;
let content = toml;
let mut result = ValidateResult::default();
check_toml_field_ordering(content, &mut result);
assert!(
result.warnings.iter().any(|w| {
w.contains("'auto_pull' appears after a section header")
|| w.contains("'url' appears after a section header")
}),
"expected warning about fields after section, got: {:?}",
result.warnings
);
}
#[test]
fn test_validate_toml_field_ordering_ok_with_all_fields_before_sections() {
use crate::policy::ValidateResult;
let toml = r#"
pulse_interval_secs = 1
standard_files_auto = true
auto_github_private = false
"#;
let content = toml;
let mut result = ValidateResult::default();
check_toml_field_ordering(content, &mut result);
assert!(
result.warnings.is_empty(),
"expected no warnings, got: {:?}",
result.warnings
);
}
/// Goal 546d4f9c: durability check. The `dracon-sync.example.toml`
/// must stay in sync with the code defaults. If a future change
/// updates one but not the other, the operator's "commit all
/// unless super-good reason" policy silently regresses on fresh
/// installs. This test catches that drift.
///
/// Date: 2026-06-15 (goal 9aaf0b08 / 546d4f9c).
#[test]
fn test_example_toml_matches_policy_defaults() {
use std::path::PathBuf;
// `dracon-sync.example.toml` lives at
// <workspace>/dracon-sync/dracon-sync.example.toml.
// CARGO_MANIFEST_DIR points at <workspace>/dracon-sync
// for the dracon-sync crate, so the file is at
// $CARGO_MANIFEST_DIR/dracon-sync.example.toml.
let example_path =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("dracon-sync.example.toml");
let content = std::fs::read_to_string(&example_path).unwrap_or_else(|e| {
panic!(
"could not read example config at {}: {}",
example_path.display(),
e
)
});
// Parse the example config into a `SyncPolicy` so the
// comparison exercises the same loader a real daemon uses.
let example: SyncPolicy =
toml::from_str(&content).expect("dracon-sync.example.toml must parse as SyncPolicy");
// 1. `exclude_file_patterns` in the example must be
// empty, matching the code default of
// `default_exclude_file_patterns() = Vec::new()`.
// Logs and DBs are committed by default under the
// operator's "commit all unless super-good reason"
// policy.
let example_excluded_files = &example.exclude_file_patterns;
assert!(
example_excluded_files.is_empty(),
"example.toml exclude_file_patterns must be empty \
(commit logs/DBs by default), got: {:?}",
example_excluded_files
);
assert_eq!(
example_excluded_files,
&default_exclude_file_patterns(),
"example.toml exclude_file_patterns must match code \
default (drift = silent regression)"
);
// 2. `untracked_exclude_patterns` in the example must
// match the code default
// `default_untracked_exclude_patterns()`. The example
// is the recommended config; if it diverges from the
// code default, fresh installs get a different policy
// than expected.
let example_untracked = &example.untracked_exclude_patterns;
let default_untracked = default_untracked_exclude_patterns();
assert_eq!(
example_untracked, &default_untracked,
"example.toml untracked_exclude_patterns must match \
code default (drift = silent regression on fresh \
install).\n example: {:?}\n default: {:?}",
example_untracked, default_untracked
);
// 3. `max_stage_file_bytes` in the example must equal the
// code default (100 MiB).
let example_max = example.max_stage_file_bytes;
assert_eq!(
example_max,
default_max_stage_file_bytes(),
"example.toml max_stage_file_bytes must match code \
default (drift = silent regression)"
);
}
}
#[cfg(test)]
mod override_coverage_dump {
#[test]
fn dump_field_sets() {
let g = serde_json::to_value(crate::policy::SyncPolicy::default()).unwrap();
let o = serde_json::to_value(crate::policy::RepoPolicyOverride::default()).unwrap();
let gk: std::collections::BTreeSet<String> =
g.as_object().unwrap().keys().cloned().collect();
let ok: std::collections::BTreeSet<String> =
o.as_object().unwrap().keys().cloned().collect();
println!(
"GLOBAL_ONLY_CANDIDATES: {:?}",
gk.difference(&ok).collect::<Vec<_>>()
);
println!(
"OVERRIDE_ONLY_CANDIDATES: {:?}",
ok.difference(&gk).collect::<Vec<_>>()
);
println!("COUNTS: global={} override={}", gk.len(), ok.len());
}
}