dracon-sync 0.1.10

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

use crate::git::gh_cmd;

#[derive(Serialize)]
struct SyncAlertEntry {
    ts_unix: u64,
    repo: String,
    reason: String,
    details: String,
}

fn sync_alert_ledger_path() -> PathBuf {
    if let Ok(state_dir) = std::env::var("DRACON_SYNC_STATE_DIR") {
        if !state_dir.is_empty() {
            return PathBuf::from(state_dir).join("dracon-sync-alerts.jsonl");
        }
    }
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".local")
        .join("state")
        .join("dracon")
        .join("dracon-sync-alerts.jsonl")
}

pub(crate) fn record_sync_alert(repo_path: &Path, reason: &str, details: &str) {
    let repo = repo_path
        .to_string_lossy()
        .trim_end_matches('/')
        .to_string();
    let entry = SyncAlertEntry {
        ts_unix: crate::policy::timestamp_secs(),
        repo,
        reason: reason.to_string(),
        details: details.to_string(),
    };
    let line = match serde_json::to_string(&entry) {
        Ok(line) => line,
        Err(e) => {
            eprintln!("⚠️ failed to serialize sync alert: {}", e);
            return;
        }
    };
    let path = sync_alert_ledger_path();
    if let Some(parent) = path.parent() {
        if let Err(e) = std::fs::create_dir_all(parent) {
            eprintln!(
                "⚠️ failed to create sync alert dir {}: {}",
                parent.display(),
                e
            );
            return;
        }
    }
    match OpenOptions::new().create(true).append(true).open(&path) {
        Ok(mut file) => {
            if let Err(e) = writeln!(file, "{line}") {
                eprintln!("⚠️ failed to write sync alert {}: {}", path.display(), e);
            }
        }
        Err(e) => eprintln!("⚠️ failed to open sync alert {}: {}", path.display(), e),
    }
    eprintln!("πŸ”” sync alert: {} β€” {}: {}", entry.repo, reason, details);
}

pub(crate) fn send_sync_conflict_notification(repo_path: &Path, reason: &str, details: &str) {
    record_sync_alert(repo_path, reason, details);

    let repo_name = repo_path
        .file_name()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| repo_path.display().to_string());

    let title = format!("Dracon Sync: {}", reason);
    let body = format!(
        "Repository '{}' needs manual resolution.\nReason: {}\nDetails: {}",
        repo_name, reason, details
    );

    // Spawn in background to avoid blocking the daemon loop
    tokio::spawn(async move {
        if let Err(e) = notify_rust::Notification::new()
            .summary(&title)
            .body(&body)
            .urgency(notify_rust::Urgency::Critical)
            .show()
        {
            eprintln!("⚠️ failed to send desktop notification: {}", e);
        }
    });
}

/// Send a desktop notification when a push operation fails persistently.
/// Rate-limited to max 1 notification per repo per 5 minutes.
#[allow(dead_code)]
pub(crate) fn notify_push_failure(
    repo_path: &Path,
    remote: &str,
    error: &str,
    consecutive_failures: usize,
    cooldowns: &mut std::collections::HashMap<String, std::time::Instant>,
) {
    let repo_name = repo_path
        .file_name()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| repo_path.display().to_string());

    let notify_key = format!("push-fail-{}", repo_path.display());
    let now = std::time::Instant::now();
    let cooldown_secs = 300; // 5 minutes

    // Check cooldown
    if let Some(cooldown_until) = cooldowns.get(&notify_key) {
        if now < *cooldown_until {
            return; // still in cooldown
        }
        cooldowns.remove(&notify_key);
    }

    let title = "Dracon Sync: Push Failed";
    let body = format!(
        "Repository '{}' failed to push to {}.\nConsecutive failures: {}\nError: {}",
        repo_name, remote, consecutive_failures, error
    );

    // Set cooldown before spawning to prevent race conditions
    cooldowns.insert(
        notify_key,
        now + std::time::Duration::from_secs(cooldown_secs),
    );

    // Spawn in background to avoid blocking the daemon loop
    tokio::spawn(async move {
        if let Err(e) = notify_rust::Notification::new()
            .summary(title)
            .body(&body)
            .show()
        {
            eprintln!("⚠️ failed to send desktop notification: {}", e);
        }
    });
}

use crate::exclude::{
    excluded_dir_names_set, has_sync_relevant_dirty_entries, is_excluded_dir_name,
};
use crate::git::multi_remote::push_mirror_remotes;
use crate::git::{
    current_branch, detect_large_blobs_ahead, discover_git_repos, has_origin_remote,
    has_tracking_upstream, push_with_retries, remote_branch_exists, repo_diff_entries,
    rewrite_ahead_paths, run_git_capture_output, run_git_with_timeout, set_upstream_to_branch,
    top_level_dir,
};
use crate::policy::{
    timestamp_secs, RepoPolicyOverride, SyncPolicy, DEFAULT_GIT_HOST_BLOB_LIMIT_BYTES,
};

fn ansi(color: &str, text: &str) -> String {
    if !crate::print::should_color() {
        return text.to_string();
    }
    let codes = match color {
        "31" => "31",
        "32" => "32",
        "33" => "33",
        "34" => "34",
        "35" => "35",
        "36" => "36",
        "37" => "37",
        "1" => "1",
        _ => "0",
    };
    format!("\x1b[{}m{}\x1b[0m", codes, text)
}

fn shorten_when(s: &str) -> String {
    let s = s.trim();

    // Parse "N minutes ago" and convert to hours+minutes if >= 60
    if let Some(rest) = s.strip_suffix(" minutes ago") {
        if let Ok(mins) = rest.parse::<u64>() {
            if mins >= 60 {
                let h = mins / 60;
                let m = mins % 60;
                if m == 0 {
                    return format!("{}h", h);
                }
                return format!("{}h {}m", h, m);
            }
            return format!("{}m", mins);
        }
    }
    if let Some(rest) = s.strip_suffix(" minute ago") {
        if let Ok(mins) = rest.parse::<u64>() {
            return format!("{}m", mins);
        }
    }

    // Convert seconds to minutes if >= 60
    if let Some(rest) = s.strip_suffix(" seconds ago") {
        if let Ok(secs) = rest.parse::<u64>() {
            if secs >= 60 {
                let m = secs / 60;
                let s_remainder = secs % 60;
                if s_remainder == 0 {
                    return format!("{}m", m);
                }
                return format!("{}m {}s", m, s_remainder);
            }
            return format!("{}s", secs);
        }
    }
    if let Some(rest) = s.strip_suffix(" second ago") {
        if let Ok(secs) = rest.parse::<u64>() {
            return format!("{}s", secs);
        }
    }

    // Convert hours to days when >= 24
    if let Some(rest) = s.strip_suffix(" hours ago") {
        if let Ok(hrs) = rest.parse::<u64>() {
            if hrs >= 24 {
                let d = hrs / 24;
                let h = hrs % 24;
                if h == 0 {
                    return format!("{}d", d);
                }
                return format!("{}d {}h", d, h);
            }
            return format!("{}h", hrs);
        }
    }
    if let Some(rest) = s.strip_suffix(" hour ago") {
        if let Ok(hrs) = rest.parse::<u64>() {
            return format!("{}h", hrs);
        }
    }

    // Convert days to weeks when >= 7
    if let Some(rest) = s.strip_suffix(" days ago") {
        if let Ok(days) = rest.parse::<u64>() {
            if days >= 7 {
                let w = days / 7;
                let d = days % 7;
                if d == 0 {
                    return format!("{}w", w);
                }
                return format!("{}w {}d", w, d);
            }
            return format!("{}d", days);
        }
    }
    if let Some(rest) = s.strip_suffix(" day ago") {
        if let Ok(days) = rest.parse::<u64>() {
            return format!("{}d", days);
        }
    }

    // Convert months to years when >= 12
    if let Some(rest) = s.strip_suffix(" months ago") {
        if let Ok(months) = rest.parse::<u64>() {
            if months >= 12 {
                let y = months / 12;
                let mo = months % 12;
                if mo == 0 {
                    return format!("{}y", y);
                }
                return format!("{}y {}mo", y, mo);
            }
            return format!("{}mo", months);
        }
    }
    if let Some(rest) = s.strip_suffix(" month ago") {
        if let Ok(months) = rest.parse::<u64>() {
            return format!("{}mo", months);
        }
    }

    // Weeks and years stay as-is (w, y)
    s.replace(" weeks ago", "w")
        .replace(" week ago", "w")
        .replace(" years ago", "y")
        .replace(" year ago", "y")
}

/// Render the ACTIVITY column. The original column was just the
/// time of the last commit (a duplicate of the LAST COMMIT column),
/// which made it impossible to tell whether a row was "actively
/// being processed" or "stalled" when the timestamp was the same
/// across many rows. This function returns a real activity label:
///
///   - "now"        : daemon has an in-flight task for this repo
///                    (currently being processed)
///   - "pushing Xm" : push_status=PENDING, push has been in
///                    progress for X minutes
///   - "stalled Xm" : dirty tracked work exists, last commit >
///                    settle threshold, no in-flight task
///   - "settling"   : dirty tracked work exists, fingerprint
///                    not yet stable (waiting for inactivity delay)
///   - "synced Xm"  : clean, in sync, recent commit (within 1h)
///   - "idle Xm"    : clean, no in-flight, last commit 1h-24h ago
///   - "cold Xd"    : clean, no activity for > 24h
///   - "β€”"          : unknown / no data
pub(crate) fn activity_label(row: &RepoReportRow) -> String {
    // Parse the last_when string ("N minutes ago", "N hours ago", etc.)
    // into a number of minutes. Returns None if unparseable.
    let last_when_mins = parse_relative_minutes_to_u64(&row.last_when);
    let in_flight = load_in_flight_for_path(&row.repo);

    // 1. in-flight = "now" β€” but only for rows whose state can
    //    legitimately be in-flight. A `Synced` / `Idle` / `Cold` /
    //    `Untracked` / `Healthy` row is clean; the in_flight
    //    entry for it is leftover from a previous cycle and
    //    should be ignored. This eliminates false "πŸ”„ now"
    //    indicators on OK/idle/synced repos.
    if in_flight {
        let in_flight_state_suppressed = matches!(
            row.state_cause,
            StateCause::Synced
                | StateCause::Idle
                | StateCause::Cold
                | StateCause::Untracked
                | StateCause::Healthy
        );
        if !in_flight_state_suppressed {
            return "πŸ”„ now".to_string();
        }
    }

    // 2. push_status PENDING = "pushing Xm (N ahead)" so the operator
    // can tell at a glance whether the push is stuck because there's a
    // large backlog (high ahead count) vs. some other transient reason.
    if row.push_status == "PENDING" {
        let duration = last_when_mins
            .map(|m| format!(" {}m", m))
            .unwrap_or_default();
        let ahead_suffix = if row.ahead > 0 {
            format!(" ({} ahead)", row.ahead)
        } else {
            String::new()
        };
        return format!("🟣 pushing{}{}", duration, ahead_suffix);
    }

    // 2b. push_status PUSH_STUCK = retry budget exhausted, the
    // daemon has given up auto-pushing. Show `πŸ›‘ push-stuck Xm`
    // so the operator knows to investigate. The HINT column
    // names the actual error.
    if row.push_status == "PUSH_STUCK" {
        let duration = last_when_mins
            .map(|m| format!(" {}m", m))
            .unwrap_or_default();
        let ahead_suffix = if row.ahead > 0 {
            format!(" ({} ahead)", row.ahead)
        } else {
            String::new()
        };
        return format!("πŸ›‘ push-stuck{}{}", duration, ahead_suffix);
    }

    // 2c. Unowned = "🚫 unowned: <reason>" so the operator
    // knows the daemon is intentionally not touching this repo.
    if let StateCause::Unowned { detail, .. } = &row.state_cause {
        return format!("🚫 unowned: {}", truncate(detail, 40));
    }

    let has_dirty = row.modified > 0 || row.staged > 0;

    // 3. dirty + recent commit (within settle threshold) = "settling"
    if has_dirty {
        // The settle threshold is roughly 2Γ— the inactivity_push_delay
        // (default 5s Γ— 2 = 10s, but we round up to 1m for the column).
        let settle_threshold_mins: u64 = 1;
        let last_mins = last_when_mins.unwrap_or(0);
        if last_mins <= settle_threshold_mins {
            return "⏳ settling".to_string();
        }
        // 4. dirty + stable fingerprint + no in-flight = "stalled Xm"
        return format!(
            "⏸ stalled {}",
            last_when_mins
                .map(|m| shorten_mins(m))
                .unwrap_or_else(|| "?".to_string())
        );
    }

    // 5-7. clean repos: synced / idle / cold
    match last_when_mins {
        None => "β€”".to_string(),
        Some(m) if m < 60 => format!("🟒 synced {}m", m),
        Some(m) if m < 60 * 24 => {
            format!("βšͺ idle {}", shorten_mins(m))
        }
        Some(m) => format!("⚫ cold {}", shorten_mins_days(m)),
    }
}

/// Read the in_flight set from disk and return whether the given
/// repo path is in it. We use the daemon's `save_in_flight` JSON
/// file, written on every daemon cycle. A missing file means
/// "no daemon activity" (or daemon not running).
///
/// Staleness filter: if the on-disk file is older than
/// `IN_FLIGHT_MAX_AGE_SECS` (default 30s), the file is considered
/// stale and treated as empty. This handles the case where a slow
/// push from the previous cycle kept a repo in `in_flight`, the
/// trailing drain timed out before that task completed, and the
/// next cycle's `save_in_flight` would re-write the same stale
/// set. The new cycle's COLLECT phase does NOT carry that repo in
/// `in_flight` (it gets cleared at cycle start), so the disk file
/// is the only stale-source of the "πŸ”„ now" indicator. Filtering
/// by age makes the indicator reflect ground truth.
fn load_in_flight_for_path(repo_path: &str) -> bool {
    // If the file is older than the staleness threshold, treat as
    // empty β€” the daemon has effectively moved on, even if a slow
    // task is still running. The repo's state will be picked up
    // again when the new cycle's COLLECT phase dispatches it.
    //
    // Threshold: 5s. The daemon writes the file every
    // `pulse_interval_secs` (default 1s), so 5s = ~5 cycles.
    // A repo genuinely in-flight writes itself to the file on
    // each of those cycles. A repo whose in_flight entry is
    // LEFTOVER from a previous cycle (e.g. trailing drain timed
    // out) won't be re-added to the set on subsequent cycles
    // (the daemon's COLLECT clears the local set at cycle
    // start), so the on-disk file will go 5s+ without that
    // entry and the staleness filter will treat it as empty.
    const IN_FLIGHT_MAX_AGE_SECS: u64 = 5;
    if let Some(age) = crate::daemon::in_flight_file_age_secs() {
        if age > IN_FLIGHT_MAX_AGE_SECS {
            return false;
        }
    }
    let set = crate::daemon::load_in_flight();
    set.iter().any(|p| p.display().to_string() == repo_path)
}

/// Parse "N minutes ago" / "N hours ago" / etc. into a u64 number
/// of minutes. Mirrors the parsing in `parse_relative_minutes` but
/// returns a plain integer for use in arithmetic.
fn parse_relative_minutes_to_u64(s: &str) -> Option<u64> {
    let s = s.trim();
    if let Some(rest) = s.strip_suffix(" minutes ago") {
        return rest.parse().ok();
    }
    if let Some(rest) = s.strip_suffix(" minute ago") {
        return rest.parse().ok();
    }
    if let Some(rest) = s.strip_suffix(" hours ago") {
        return rest.parse::<u64>().ok().map(|h| h * 60);
    }
    if let Some(rest) = s.strip_suffix(" hour ago") {
        return rest.parse::<u64>().ok().map(|h| h * 60);
    }
    if let Some(rest) = s.strip_suffix(" days ago") {
        return rest.parse::<u64>().ok().map(|d| d * 60 * 24);
    }
    if let Some(rest) = s.strip_suffix(" day ago") {
        return rest.parse::<u64>().ok().map(|d| d * 60 * 24);
    }
    if let Some(rest) = s.strip_suffix(" seconds ago") {
        return rest.parse::<u64>().ok().map(|s| s / 60);
    }
    None
}

/// Render minutes as a compact label: <60m β†’ "Nm", 1h-24h β†’ "Nh",
/// >=24h β†’ "Nd".
fn shorten_mins(mins: u64) -> String {
    if mins < 60 {
        format!("{}m", mins)
    } else if mins < 60 * 24 {
        let h = mins / 60;
        format!("{}h", h)
    } else {
        shorten_mins_days(mins)
    }
}

fn shorten_mins_days(mins: u64) -> String {
    let d = mins / (60 * 24);
    format!("{}d", d)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RepoFilter {
    All,
    Concern,
    Warn,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ConcernRepairFilter {
    All,
    StuckPush,
    StuckPull,
}

#[derive(Debug, Serialize)]
pub(crate) struct RepoReportRow {
    repo: String,
    state_flags: Vec<String>,
    branch: String,
    modified: usize,
    staged: usize,
    untracked: usize,
    ahead: usize,
    behind: usize,
    last_hash: String,
    last_author: String,
    last_when: String,
    last_msg: String,
    last_unix: i64,
    last_push: String,
    push_status: String,
    push_error: String,
    concern: bool,
    warn: bool,
    hint: String,
    /// Derived "rough cause" of the row's current state. Combines the
    /// last-commit time, last-push time, dirty state, ahead/behind, and
    /// push status into a single small vocabulary the user can scan at
    /// a glance. See [`StateCause`].
    state_cause: StateCause,
    /// `state_cause` as a string, for downstream tools that want the
    /// label without having to enumerate the enum.
    state_cause_label: String,
    /// When the daemon last recorded an action for this repo (unix
    /// timestamp). `0` means "no record in the incident ledger".
    /// Distinguishes "user is actively editing" from "daemon is actively
    /// syncing" when both produce dirty/committing rows.
    daemon_last_action_unix: i64,
    /// Short label of the daemon's last action (e.g. "sync_triage",
    /// "push", "ok"). Empty when no record exists.
    daemon_last_action: String,
    /// Result of the daemon's last action (e.g. "ok", "fail",
    /// "planned"). Empty when no record exists.
    daemon_last_result: String,
    /// Human-friendly relative time of the daemon's last action
    /// (e.g. "23s", "2m"). `none` when no record exists.
    daemon_last_action_when: String,
}

#[derive(Debug, Serialize)]
pub(crate) struct RepoReportJson {
    policy: String,
    filter: String,
    repos: usize,
    ok: usize,
    warn: usize,
    concern: usize,
    failures: usize,
    rows: Vec<RepoReportRow>,
}

#[derive(Debug, Serialize)]
pub(crate) struct RemoteStatus {
    pub(crate) name: String,
    pub(crate) auth_type: String,
    pub(crate) auto_create: bool,
    pub(crate) priority: u32,
}

#[derive(Debug, Serialize)]
pub(crate) struct StatusJson {
    pub(crate) policy: String,
    pub(crate) roots: Vec<String>,
    pub(crate) repos_discovered: usize,
    pub(crate) pulse_interval_secs: u64,
    pub(crate) inactivity_push_delay_secs: u64,
    pub(crate) freeze: String,
    pub(crate) auto_commit: bool,
    pub(crate) auto_pull: bool,
    pub(crate) auto_push: bool,
    pub(crate) auto_bump_versions: bool,
    pub(crate) auto_repair_concerns: bool,
    pub(crate) auto_repair_warns: bool,
    pub(crate) auto_rewrite_large_blobs: bool,
    pub(crate) max_stage_file_bytes: u64,
    pub(crate) push_blob_threshold_bytes: u64,
    pub(crate) exclude_dirs: Vec<String>,
    pub(crate) exclude_file_patterns: Vec<String>,
    pub(crate) pull_op_timeout_secs: u64,
    pub(crate) push_op_timeout_secs: u64,
    pub(crate) repo_sync_timeout_secs: u64,
    pub(crate) stage_op_timeout_secs: u64,
    pub(crate) stage_cooldown_secs: u64,
    pub(crate) push_retries: u32,
    pub(crate) repair_cooldown_secs: u64,
    pub(crate) incident_ledger_max_lines: usize,
    pub(crate) incident_ledger_max_age_days: u64,
    pub(crate) system_repo: String,
    pub(crate) backup_policy: String,
    pub(crate) backup_dir: String,
    pub(crate) remotes: usize,
    pub(crate) remote_configs: Vec<RemoteStatus>,
}

#[derive(Debug, Serialize)]
pub(crate) struct RepairJson {
    policy: String,
    scope: String,
    mode: String,
    found: usize,
    planned: usize,
    attempted: usize,
    succeeded: usize,
    resolved_now: usize,
    manual_only: usize,
    ledger: String,
}

#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct RepairSummary {
    pub(crate) found: usize,
    pub(crate) planned: usize,
    pub(crate) attempted: usize,
    pub(crate) succeeded: usize,
    pub(crate) resolved_now: usize,
    pub(crate) manual_only: usize,
}

#[derive(Debug, Serialize, PartialEq)]
pub(crate) struct IncidentRecord {
    ts_unix: u64,
    scope: String,
    repo: String,
    reason: String,
    action: String,
    backup_branch: Option<String>,
    result: String,
    details: Option<String>,
}

impl IncidentRecord {
    pub(crate) fn new(
        ts_unix: u64,
        scope: impl Into<String>,
        repo: impl Into<String>,
        reason: impl Into<String>,
        action: impl Into<String>,
        backup_branch: Option<String>,
        result: impl Into<String>,
        details: Option<String>,
    ) -> Self {
        Self {
            ts_unix,
            scope: scope.into(),
            repo: repo.into(),
            reason: reason.into(),
            action: action.into(),
            backup_branch,
            result: result.into(),
            details,
        }
    }
}

pub(crate) fn incident_ledger_path(_policy_path: &Path) -> PathBuf {
    // IMPORTANT: Keep this ledger OUT of git repositories by default.
    // The policy file typically lives inside the system repo; writing next to it
    // causes perpetual DIRTY state and churn.
    if let Ok(custom) = std::env::var("DRACON_SYNC_LEDGER") {
        let p = PathBuf::from(custom);
        if !p.as_os_str().is_empty() {
            return p;
        }
    }

    if let Some(home) = dirs::home_dir() {
        return home
            .join(".local")
            .join("state")
            .join("dracon")
            .join("dracon-sync-incidents.jsonl");
    }

    PathBuf::from("/tmp/dracon-sync-incidents.jsonl")
}

/// Enforce incident ledger retention at any time.
/// Removes entries older than max_age_days and truncates to max_lines.
/// Returns the number of pruned entries (or 0 if nothing was removed).
pub(crate) fn enforce_retention(path: &Path, policy: &SyncPolicy) -> Result<usize> {
    if !path.exists() {
        return Ok(0);
    }
    let meta = std::fs::metadata(path)?;
    if meta.len() > 100 * 1024 * 1024 {
        eprintln!(
            "⚠️ incident ledger is {}MB (>100MB), truncating to last {} lines",
            meta.len() / (1024 * 1024),
            policy.incident_ledger_max_lines,
        );
        let content = std::fs::read_to_string(path)?;
        let lines: Vec<&str> = content
            .lines()
            .rev()
            .take(policy.incident_ledger_max_lines)
            .collect();
        let out = lines.iter().rev().copied().collect::<Vec<_>>().join("\n") + "\n";
        std::fs::write(path, &out)?;
        return Ok(lines.len());
    }
    let content = std::fs::read_to_string(path)?;
    let original_count = content.lines().count();
    let now = timestamp_secs();
    let age_cutoff = now.saturating_sub(policy.incident_ledger_max_age_days.saturating_mul(86_400));

    let mut kept: Vec<String> = Vec::new();
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let keep_by_age = serde_json::from_str::<serde_json::Value>(line)
            .ok()
            .and_then(|v| v.get("ts_unix").and_then(|t| t.as_u64()))
            .map(|ts| ts >= age_cutoff)
            .unwrap_or(true);
        if keep_by_age {
            kept.push(line.to_string());
        }
    }
    if kept.len() > policy.incident_ledger_max_lines {
        let drop_n = kept.len() - policy.incident_ledger_max_lines;
        kept.drain(0..drop_n);
    }
    let out = kept.join("\n") + "\n";
    std::fs::write(path, &out)?;

    let removed = original_count.saturating_sub(kept.len());
    Ok(removed)
}

pub(crate) fn append_incident_record(policy_path: &Path, record: &IncidentRecord) {
    let path = incident_ledger_path(policy_path);
    let line = match serde_json::to_string(record) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("⚠️ incident serialize failed: {}", e);
            return;
        }
    };
    let parent = path.parent().map(Path::to_path_buf);
    if let Some(dir) = parent {
        if let Err(e) = std::fs::create_dir_all(&dir) {
            eprintln!("⚠️ failed to create incident ledger dir: {}", e);
        }
    }
    match std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path)
    {
        Ok(mut file) => {
            use std::io::Write;
            if let Err(e) = writeln!(file, "{}", line) {
                eprintln!("⚠️ incident write failed ({}): {}", path.display(), e);
            }
        }
        Err(e) => eprintln!("⚠️ incident open failed ({}): {}", path.display(), e),
    }
    // ── lazy retention: only check when file has likely grown past max ──
    if path.exists() {
        if let Ok(metadata) = std::fs::metadata(&path) {
            // rough estimate: ~200 bytes per JSON line
            let approx_lines = metadata.len() as usize / 200;
            let policy = SyncPolicy::load(policy_path).ok();
            if let Some(ref p) = policy {
                if approx_lines >= p.incident_ledger_max_lines {
                    if let Err(e) = enforce_retention(&path, p).map(|_| ()) {
                        eprintln!("⚠️ incident retention failed ({}): {}", path.display(), e);
                    }
                }
            }
        }
    }
}

/// Enforce incident ledger retention at daemon startup.
/// Delegates to the shared [`enforce_retention`] function.
pub(crate) fn enforce_retention_at_startup(policy_path: &Path, policy: &SyncPolicy) -> Result<()> {
    let path = incident_ledger_path(policy_path);
    let removed = enforce_retention(&path, policy)?;
    if removed > 0 {
        eprintln!(
            "🧹 startup: pruned {} stale incident entries (remaining after reload)",
            removed,
        );
    }
    Ok(())
}

/// Build a map of repo path -> "did the daemon record a push failure in the
/// last 10 minutes?". Used by the report to distinguish "has unpushed
/// commits" (normal, daemon is working through the queue) from "push is
/// genuinely stuck" (daemon tried and failed). Returns `None` if the ledger
/// is missing or unreadable so the report still works in degraded mode.
fn build_recent_push_failure_map(policy_path: &Path) -> Option<HashMap<String, bool>> {
    use std::time::{SystemTime, UNIX_EPOCH};

    let path = incident_ledger_path(policy_path);
    // The ledger is append-only and can grow to thousands of lines. We only
    // care about the most recent ~10 minutes, so reading the whole file on
    // every `repos` call is O(ledger_size) and wasteful. Read the last
    // `RECENT_LINES_WINDOW` lines instead β€” a tight window that still
    // covers any plausible 10-minute push-failure rate.
    const RECENT_LINES_WINDOW: usize = 500;
    const PUSH_WINDOW_SECS: u64 = 600; // 10 minutes
    let recent = read_tail_lines(&path, RECENT_LINES_WINDOW).ok()?;
    if recent.is_empty() {
        return Some(HashMap::new());
    }
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let cutoff = now.saturating_sub(PUSH_WINDOW_SECS);
    let mut map: HashMap<String, bool> = HashMap::new();
    for line in recent {
        let entry: serde_json::Value = match serde_json::from_str(&line) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let scope = entry.get("scope").and_then(|v| v.as_str()).unwrap_or("");
        let result = entry.get("result").and_then(|v| v.as_str()).unwrap_or("");
        let ts = entry.get("ts_unix").and_then(|v| v.as_u64()).unwrap_or(0);
        // Push-related failures: any scope mentioning push/mirror with a
        // non-ok result, or an explicit "push" reason.
        let is_push_failure = result != "ok"
            && (scope.contains("push")
                || scope.contains("mirror")
                || entry
                    .get("reason")
                    .and_then(|v| v.as_str())
                    .map(|r| r.contains("push"))
                    .unwrap_or(false));
        if !is_push_failure || ts < cutoff {
            continue;
        }
        if let Some(repo) = entry.get("repo").and_then(|v| v.as_str()) {
            map.insert(repo.to_string(), true);
        }
    }
    Some(map)
}

/// Build a per-repo map of the daemon's last recorded action (timestamp
/// + action label + result) from the incident ledger. Used by the report
/// to show the user that the daemon IS actively working through dirty
/// repos β€” the `last_when`/`last_push` columns show the last *commit*
/// and *push* times, but those reset to the moment of the daemon's own
/// commit, so they don't distinguish "user is editing" from "daemon is
/// handling dirty work". The `DAEMON` column closes that gap.
///
/// Returns `None` if the ledger is missing or unreadable so the report
/// still works in degraded mode.
fn build_daemon_last_action_map(
    policy_path: &Path,
) -> Option<HashMap<String, (i64, String, String)>> {
    let path = incident_ledger_path(policy_path);
    // The ledger is append-only and can grow to thousands of lines. We only
    // care about the most recent entries, so reading the whole file on
    // every `repos` call is O(ledger_size) and wasteful. Read the last
    // `RECENT_LINES_WINDOW` lines instead.
    const RECENT_LINES_WINDOW: usize = 2000;
    let recent = read_tail_lines(&path, RECENT_LINES_WINDOW).ok()?;
    if recent.is_empty() {
        return Some(HashMap::new());
    }
    let mut map: HashMap<String, (i64, String, String)> = HashMap::new();
    for line in recent {
        let entry: serde_json::Value = match serde_json::from_str(&line) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let ts = entry.get("ts_unix").and_then(|v| v.as_i64()).unwrap_or(0);
        let action = entry
            .get("action")
            .and_then(|v| v.as_str())
            .unwrap_or("-")
            .to_string();
        let result = entry
            .get("result")
            .and_then(|v| v.as_str())
            .unwrap_or("-")
            .to_string();
        if let Some(repo) = entry.get("repo").and_then(|v| v.as_str()) {
            // Keep the most recent (highest ts) entry per repo.
            let entry_data = (ts, action, result);
            map.entry(repo.to_string())
                .and_modify(|existing| {
                    if ts > existing.0 {
                        *existing = entry_data.clone();
                    }
                })
                .or_insert(entry_data);
        }
    }
    Some(map)
}

/// Read up to `max_lines` trailing lines from a file, returning them in
/// chronological order (oldest first). Streams the file in chunks from the
/// end so the operation is O(tail-size) regardless of total file size.
///
/// If the file is smaller than `max_lines`, returns the whole file. If the
/// file cannot be read (missing, permission denied, etc.), returns the
/// underlying IO error so the caller can decide whether to surface it.
fn read_tail_lines(path: &Path, max_lines: usize) -> std::io::Result<Vec<String>> {
    use std::io::{Read, Seek, SeekFrom};
    const CHUNK_SIZE: usize = 16 * 1024;
    let mut file = std::fs::File::open(path)?;
    let len = file.metadata()?.len() as usize;
    if len == 0 {
        return Ok(Vec::new());
    }
    // Read from the end in CHUNK_SIZE pieces until we have at least
    // `max_lines` newlines or hit the start of the file.
    let mut buf: Vec<u8> = Vec::new();
    let mut remaining = len;
    let mut pos = len;
    while remaining > 0 && buf.iter().filter(|&&b| b == b'\n').count() <= max_lines {
        let take = remaining.min(CHUNK_SIZE);
        pos -= take;
        file.seek(SeekFrom::Start(pos as u64))?;
        let mut chunk = vec![0u8; take];
        file.read_exact(&mut chunk)?;
        // Prepend because we're reading backwards.
        let mut new_buf = chunk;
        new_buf.append(&mut buf);
        buf = new_buf;
        remaining = pos;
    }
    // Split into lines. If the read window started mid-line, the first
    // parsed entry will be a partial line; drop it after checking the byte
    // immediately before the window.
    let text = match std::str::from_utf8(&buf) {
        Ok(s) => s,
        Err(_) => return Ok(Vec::new()),
    };
    let mut lines: Vec<&str> = text.lines().collect();
    if pos > 0 {
        // A newline immediately before the window means we started at a
        // line boundary. Any other byte means the first parsed line is
        // only the tail of a longer line and must be dropped.
        let mut probe = std::fs::File::open(path)?;
        probe.seek(SeekFrom::Start((pos - 1) as u64))?;
        let mut byte = [0u8; 1];
        if probe.read_exact(&mut byte).is_ok() && byte[0] != b'\n' {
            // We started mid-line, drop the first partial.
            if !lines.is_empty() {
                lines.remove(0);
            }
        }
    }
    // Keep only the last `max_lines` lines.
    if lines.len() > max_lines {
        let drop = lines.len() - max_lines;
        lines.drain(..drop);
    }
    Ok(lines.into_iter().map(|s| s.to_string()).collect())
}

pub(crate) fn repo_state_flags(
    status: &dracon_git::types::RepoStatus,
    has_origin: bool,
    has_upstream: bool,
) -> Vec<String> {
    repo_state_flags_with_push_failure(status, has_origin, has_upstream, false)
}

/// Like [`repo_state_flags`], but only emits `STUCK_PUSH` when the daemon
/// has actually recorded a recent push failure for this repo. Without that
/// signal, an `AHEAD:N` repo is just "has unpushed commits waiting" and
/// should not be flagged as stuck β€” the daemon may be waiting for the
/// inactivity delay or for a multi-remote round to finish.
pub(crate) fn repo_state_flags_with_push_failure(
    status: &dracon_git::types::RepoStatus,
    has_origin: bool,
    has_upstream: bool,
    recent_push_failure: bool,
) -> Vec<String> {
    let mut flags = Vec::new();
    if !status.is_clean {
        flags.push("DIRTY".to_string());
    }
    if status.ahead > 0 {
        flags.push(format!("AHEAD:{}", status.ahead));
    }
    if status.behind > 0 {
        flags.push(format!("BEHIND:{}", status.behind));
    }
    if !has_origin {
        flags.push("NO_ORIGIN".to_string());
    }
    if has_origin && !has_upstream {
        flags.push("NO_UPSTREAM".to_string());
    }
    if status.ahead > 0 && has_origin && has_upstream && recent_push_failure {
        flags.push("STUCK_PUSH".to_string());
    }
    if status.behind > 0 && has_origin && has_upstream {
        flags.push("STUCK_PULL".to_string());
    }
    if flags.is_empty() {
        flags.push("OK".to_string());
    }
    flags
}

/// Apply per-repo `intentional_no_upstream` semantics to a row of flags.
///
/// When the operator has flagged a repo as intentionally isolated
/// (`.dracon/dracon-sync.toml` sets `intentional_no_upstream = true`),
/// the `NO_UPSTREAM` flag is replaced by the explicit
/// `INTENTIONAL_NO_UPSTREAM` flag and the row is no longer classified
/// as a hidden concern. The intent of the original `NO_UPSTREAM` flag
/// (i.e. "this branch is untracked") is preserved, but the operator
/// has already said it does not want it remediated.
pub(crate) fn apply_intentional_no_upstream(mut flags: Vec<String>) -> Vec<String> {
    if flags.iter().any(|f| f == "NO_UPSTREAM") {
        flags.retain(|f| f != "NO_UPSTREAM");
        if !flags.iter().any(|f| f == "INTENTIONAL_NO_UPSTREAM") {
            flags.push("INTENTIONAL_NO_UPSTREAM".to_string());
        }
    }
    flags
}

/// Kept for backward-compatible test coverage. New code should use
/// [`repo_is_concern_with_push_failure`] which also considers recent
/// push failures and the behind-count.
#[allow(dead_code, unused_variables)]
pub(crate) fn repo_is_concern(
    _status: &dracon_git::types::RepoStatus,
    has_origin: bool,
    has_upstream: bool,
) -> bool {
    !has_origin || !has_upstream
}

/// Like [`repo_is_concern`], but also flags a repo as a concern when it has
/// unpushed commits (ahead > 0) **and** a recent push failure was recorded
/// in the incident ledger. Without the push-failure signal, an AHEAD repo
/// is just "has unpushed commits" and the daemon is working through the
/// queue; that should be a WARN, not a CONCERN.
///
/// `behind > 0` remains a concern unconditionally: the local is older
/// than the remote and risks losing history if the divergence grows.
pub(crate) fn repo_is_concern_with_push_failure(
    status: &dracon_git::types::RepoStatus,
    has_origin: bool,
    has_upstream: bool,
    recent_push_failure: bool,
) -> bool {
    if !has_origin || !has_upstream {
        return true;
    }
    if status.behind > 0 {
        return true;
    }
    status.ahead > 0 && recent_push_failure
}

pub(crate) fn repo_is_stuck_push(
    status: &dracon_git::types::RepoStatus,
    has_origin: bool,
    has_upstream: bool,
    recent_push_failure: bool,
) -> bool {
    status.ahead > 0 && has_origin && has_upstream && recent_push_failure
}

pub(crate) fn repo_is_stuck_pull(
    status: &dracon_git::types::RepoStatus,
    has_origin: bool,
    has_upstream: bool,
) -> bool {
    status.behind > 0 && has_origin && has_upstream
}

#[cfg(test)]
pub(crate) fn repo_is_warn(
    status: &dracon_git::types::RepoStatus,
    has_origin: bool,
    has_upstream: bool,
) -> bool {
    // WARN: has TRACKED modifications or staged changes, but not a concern.
    // Untracked files remain visible in the UT column, but they are not
    // sync-relevant by themselves. This keeps audit/research artifacts visible
    // without turning build artifacts, screenshots, or local evidence into WARNs.
    //
    // CHANGED 2026-06-15 (goal 0ab367b5 / Junk-Runner-bevy WARN fix):
    // upgraded `dracon-git` 94.2.7 β†’ 94.7.0 which fixed the
    // `is_wt_new()`-counted-as-modified bug and added `untracked_files`
    // to `RepoStatus`. Junk-Runner-bevy 91 "MOD" was 3 untracked
    // test-results/ PNGs.
    !repo_is_concern(status, has_origin, has_upstream)
        && (status.modified_files > 0 || status.staged_files > 0)
}

/// Coarse "what is this repo doing right now?" classification derived
/// from the existing signals β€” last-commit time, last-push time, dirty
/// state, ahead/behind, and push status. The vocabulary is intentionally
/// small so the user can scan the table at a glance and tell apart
/// "freshly synced", "waiting on the daemon", "stalled", and
/// "cold idle".
///
/// The vocabulary:
///
/// - `Working`   β€” clean, in sync, and both commit and push are within
///   `active_commit_minutes` (default 5m). This means "the daemon is
///   currently working through this repo" (it just committed and
///   pushed). Distinct from `Synced`: `Synced` is the longer-term clean
///   state, `Working` is the short window after a recent sync cycle.
/// - `Committing` β€” unpushed commits are waiting, or the last commit is
///   within `committing_commit_minutes` but outside the active window.
/// - `Pushing`   β€” `push_status = PENDING` (the daemon is mid-cycle).
/// - `Synced`    β€” clean, `ahead=0, behind=0`, commit/push within
///   `committing_commit_minutes` but outside the active window.
/// - `Stalled`   β€” dirty tracked/staged work that has been sitting for
///   longer than `committing_commit_minutes` without push progress. This
///   is the case the user described as "stalling for minutes".
/// - `Dirty`     β€” dirty tracked/staged work that is still recent and
///   expected to be picked up by normal sync; `sync-now --warns` forces
///   the same triage immediately.
/// - `Untracked` β€” only untracked files (no modified, no staged).
/// - `Intentional` β€” repo flagged `intentional_no_upstream = true`.
/// - `Failed`    β€” `push_status = FAIL` or `STUCK`.
/// - `Idle`      β€” clean, no recent activity, last commit within
///   `cold_commit_minutes`.
/// - `Cold`      β€” last commit older than `cold_commit_minutes` (default 24h).
/// - `Healthy`   β€” fallback when nothing else matches.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum StateCause {
    Working,
    Committing,
    Pushing,
    Synced,
    Stalled,
    Dirty,
    Untracked,
    Intentional,
    Failed,
    Idle,
    Cold,
    Healthy,
    /// Repo is not owned by the operator (per the
    /// `auto_skip_unowned` ownership guard). The daemon skips
    /// auto-commit and auto-push for this repo. `reason` is
    /// the stable kebab-case classifier (e.g. `untrusted_origin`,
    /// `untrusted_author`); `detail` is the human-readable
    /// explanation (e.g. the actual bad origin URL).
    Unowned { reason: String, detail: String },
}

impl StateCause {
    pub(crate) fn as_str(&self) -> &'static str {
        match self {
            StateCause::Working => "working",
            StateCause::Committing => "committing",
            StateCause::Pushing => "pushing",
            StateCause::Synced => "synced",
            StateCause::Stalled => "stalled",
            StateCause::Dirty => "dirty",
            StateCause::Untracked => "untracked-only",
            StateCause::Intentional => "intentional",
            StateCause::Failed => "failed",
            StateCause::Idle => "idle",
            StateCause::Cold => "cold",
            StateCause::Healthy => "healthy",
            // For Unowned, the label is computed separately
            // (it's a dynamic String, not a &'static str). See
            // `state_cause_label_string` for the dynamic case.
            StateCause::Unowned { .. } => "unowned",
        }
    }

    /// Icon used in the human-readable table. The colour of the row is
    /// picked separately by `cause_color`.
    pub(crate) fn icon(&self) -> &'static str {
        match self {
            StateCause::Working => "πŸ”„",
            StateCause::Committing => "🟑",
            StateCause::Pushing => "🟣",
            StateCause::Synced => "🟒",
            StateCause::Stalled => "πŸ”΄",
            StateCause::Dirty => "🟠",
            StateCause::Untracked => "βšͺ",
            StateCause::Intentional => "🟣",
            StateCause::Failed => "β›”",
            StateCause::Idle => "βšͺ",
            StateCause::Cold => "⚫",
            StateCause::Healthy => "βœ…",
            StateCause::Unowned { .. } => "🚫",
        }
    }
}

/// Compute the state_cause_label string. For most variants this
/// is just `state_cause.as_str()`, but `Unowned` carries a
/// dynamic reason string that needs to be returned as the label
/// (e.g. `unowned:untrusted_origin` for machine parsing, or just
/// the reason for the table cell).
pub(crate) fn state_cause_label_string(cause: &StateCause) -> String {
    match cause {
        StateCause::Unowned { reason, .. } => format!("unowned:{}", reason),
        other => other.as_str().to_string(),
    }
}

/// Borrowed `as_str` for a `&StateCause`. Required because we
/// dropped `Copy` from `StateCause` (it now carries String
/// fields in the Unowned variant). Most call sites are
/// refactored to use this.
pub(crate) fn state_cause_as_str(cause: &StateCause) -> &'static str {
    match cause {
        StateCause::Working => "working",
        StateCause::Committing => "committing",
        StateCause::Pushing => "pushing",
        StateCause::Synced => "synced",
        StateCause::Stalled => "stalled",
        StateCause::Dirty => "dirty",
        StateCause::Untracked => "untracked-only",
        StateCause::Intentional => "intentional",
        StateCause::Failed => "failed",
        StateCause::Idle => "idle",
        StateCause::Cold => "cold",
        StateCause::Healthy => "healthy",
        StateCause::Unowned { .. } => "unowned",
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct StateCauseThresholds {
    pub(crate) active_minutes: u64,
    pub(crate) committing_minutes: u64,
    pub(crate) cold_minutes: u64,
}

impl StateCauseThresholds {
    pub(crate) fn from_policy(policy: &SyncPolicy, override_: &RepoPolicyOverride) -> Self {
        Self {
            active_minutes: override_
                .active_commit_minutes
                .unwrap_or(policy.active_commit_minutes),
            committing_minutes: override_
                .committing_commit_minutes
                .unwrap_or(policy.committing_commit_minutes),
            cold_minutes: override_
                .cold_commit_minutes
                .unwrap_or(policy.cold_commit_minutes),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct StateCauseInputs<'a> {
    pub(crate) flags: &'a [String],
    pub(crate) push_status: &'a str,
    pub(crate) modified: usize,
    pub(crate) staged: usize,
    pub(crate) untracked: usize,
    pub(crate) ahead: usize,
    pub(crate) behind: usize,
    /// Last commit age in minutes, if known. None means we could not read it.
    pub(crate) last_commit_minutes: Option<i64>,
    /// Last push age in minutes, if known. None means we could not read it.
    pub(crate) last_push_minutes: Option<i64>,
}

/// Classify a single repo's "rough cause" given the current signals.
///
/// The classification is order-dependent: more specific states are
/// checked first. The intent is that the user can read the column
/// top-to-bottom and trust the first matching label.
pub(crate) fn classify_state_cause(
    inputs: &StateCauseInputs,
    thresholds: &StateCauseThresholds,
) -> StateCause {
    let last_commit = inputs.last_commit_minutes;
    let last_push = inputs.last_push_minutes;

    if inputs.push_status == "PENDING" {
        return StateCause::Pushing;
    }
    if inputs.push_status == "FAIL" || inputs.push_status == "STUCK" {
        return StateCause::Failed;
    }
    if inputs.flags.iter().any(|f| f == "INTENTIONAL_NO_UPSTREAM") {
        return StateCause::Intentional;
    }

    let has_dirty = inputs.modified > 0 || inputs.staged > 0;
    let in_sync = inputs.ahead == 0 && inputs.behind == 0;
    let has_untracked_only = inputs.modified == 0 && inputs.staged == 0 && inputs.untracked > 0;
    let recent_commit = last_commit
        .map(|m| m >= 0 && m <= thresholds.active_minutes as i64)
        .unwrap_or(false);
    let recent_push = last_push
        .map(|m| m >= 0 && m <= thresholds.active_minutes as i64)
        .unwrap_or(false);

    // Dirty tracked/staged work is not automatically "stalled". Recent
    // dirty work is expected to be picked up by normal sync or
    // `repair warns --apply`; only older dirty work with no push progress
    // is the user's "we changed files and then stopped" pain case.
    if has_dirty {
        if inputs.ahead > 0 {
            return StateCause::Committing;
        }
        let recent_commit_or_push = last_commit
            .map(|m| m >= 0 && m <= thresholds.committing_minutes as i64)
            .unwrap_or(false)
            || last_push
                .map(|m| m >= 0 && m <= thresholds.committing_minutes as i64)
                .unwrap_or(false);
        if recent_commit_or_push {
            return StateCause::Dirty;
        }
        return StateCause::Stalled;
    }

    if has_untracked_only {
        return StateCause::Untracked;
    }

    if inputs.behind > 0 {
        return StateCause::Stalled;
    }

    if in_sync && recent_commit && recent_push {
        return StateCause::Working;
    }

    if let Some(m) = last_commit {
        if m >= 0 && m <= thresholds.committing_minutes as i64 {
            if in_sync {
                return StateCause::Synced;
            }
            return StateCause::Committing;
        }
    }

    if let Some(m) = last_commit {
        if m > thresholds.cold_minutes as i64 {
            return StateCause::Cold;
        }
    }

    if last_commit.is_some() {
        return StateCause::Idle;
    }

    StateCause::Healthy
}

/// Parse a git-style relative time string ("5 minutes ago", "2 days ago",
/// "1 hour ago", "8 hours ago", "29 minutes ago") into minutes.
///
/// Returns None for input we cannot parse, including:
/// - the sentinel "-" the daemon emits when no time is available;
/// - any string without a recognizable number + unit.
/// - special "weird" forms like "yesterday", "a week ago" (treated as None).
pub(crate) fn parse_relative_minutes(text: &str) -> Option<i64> {
    let trimmed = text.trim();
    if trimmed.is_empty() || trimmed == "-" {
        return None;
    }
    let body = trimmed.strip_suffix(" ago").unwrap_or(trimmed);
    let mut iter = body.split_whitespace();
    let n_str = iter.next()?;
    let n: i64 = n_str.parse().ok()?;
    let unit = iter.next()?;
    let minutes = match unit {
        "second" | "seconds" => 0,
        "minute" | "minutes" => n,
        "hour" | "hours" => n * 60,
        "day" | "days" => n * 24 * 60,
        "week" | "weeks" => n * 7 * 24 * 60,
        "month" | "months" => n * 30 * 24 * 60,
        "year" | "years" => n * 365 * 24 * 60,
        _ => return None,
    };
    Some(minutes)
}

/// Compute the user-visible hint for a row of state flags.
///
/// When the operator has flagged a repo as intentionally isolated
/// (see [`crate::policy::RepoPolicyOverride::intentional_no_upstream`]),
/// the row builder appends the explicit `INTENTIONAL_NO_UPSTREAM`
/// flag. That flag is checked first here so the row reports the
/// operator's intent instead of a misleading "set upstream" hint.
pub(crate) fn repo_hint(flags: &[String], warn: bool, concern: bool) -> String {
    if flags.iter().any(|f| f == "INTENTIONAL_NO_UPSTREAM") {
        return "intentional legacy isolation, no upstream configured".to_string();
    }
    if flags.iter().any(|f| f == "NO_ORIGIN") {
        return "set origin remote".to_string();
    }
    if flags.iter().any(|f| f == "NO_UPSTREAM") {
        return "run repair-concerns --apply (set upstream)".to_string();
    }
    if flags.iter().any(|f| f.starts_with("AHEAD:")) {
        if warn {
            return "daemon will push after changes settle".to_string();
        }
        return "run repair-concerns --apply (push or rewrite)".to_string();
    }
    if flags.iter().any(|f| f.starts_with("BEHIND:")) {
        return "run repair-concerns --apply (pull/merge)".to_string();
    }
    if warn {
        return "daemon handles after changes settle; run sync-now --warns to force now"
            .to_string();
    }
    if concern {
        return "run repair-concerns --apply".to_string();
    }
    "healthy".to_string()
}

pub(crate) fn push_large_blob_threshold_bytes(policy: &SyncPolicy) -> u64 {
    policy
        .max_stage_file_bytes
        .min(policy.max_push_blob_bytes)
        .min(DEFAULT_GIT_HOST_BLOB_LIMIT_BYTES)
}

pub(crate) fn truncate(value: &str, max_chars: usize) -> String {
    if value.chars().count() <= max_chars {
        return value.to_string();
    }
    let shortened: String = value.chars().take(max_chars.saturating_sub(1)).collect();
    format!("{}…", shortened)
}

/// Single `git log` call that extracts all commit metadata in one process.
/// Returns (hash, author, relative_time, unix_timestamp, subject).
/// Previously the report called this 3 times per repo (hash via libgit2,
/// author via `%an`, time via `%ar`, timestamp via `%ct`) which tripled
/// the wall-clock time on repos with many entries.
pub(crate) async fn git_log_meta(repo: &Path) -> Option<(String, String, String, i64, String)> {
    let repo_str = repo.to_str()?;
    // %H = hash, %an = author, %ar = relative, %ct = unix, %s = subject
    // Separator `\x1f` (unit separator) is unlikely in commit fields.
    let out = crate::git::git_cmd()
        .args([
            "-C",
            repo_str,
            "log",
            "-1",
            "--format=%H%x1f%an%x1f%ar%x1f%ct%x1f%s",
        ])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let line = String::from_utf8_lossy(&out.stdout);
    parse_git_log_meta_line(&line)
}

fn parse_git_log_meta_line(line: &str) -> Option<(String, String, String, i64, String)> {
    let line = line.trim();
    if line.is_empty() {
        return None;
    }
    let parts: Vec<&str> = line.split('\x1f').collect();
    if parts.len() < 5 {
        return None;
    }
    let subject = if parts.len() > 5 {
        parts[4..].join("\u{1f}")
    } else {
        parts[4].to_string()
    };
    let unix = parts[3].parse::<i64>().unwrap_or(0);
    Some((
        parts[0].to_string(),
        parts[1].to_string(),
        parts[2].to_string(),
        unix,
        subject,
    ))
}

fn repo_failure_message(prefix: &str, repo: &Path, error: impl std::fmt::Display) -> String {
    format!(
        "{} {} | {}: {}",
        ansi("31", "❌"),
        repo.display(),
        prefix,
        error
    )
}

/// Resolve the human-readable "last pushed N ago" string for a single repo's
/// current branch. Returns "-" when the branch is empty (detached HEAD) or
/// otherwise unsafe for use in a `git reflog show origin/{branch}` argument.
/// Resolve the human-readable "last pushed N ago" string for a single repo's
/// current branch. Returns "-" when the branch is empty (detached HEAD) or
/// otherwise unsafe for use in a `git log -1 --format=%cr origin/{branch}`
/// argument, when the remote-tracking branch does not exist, or when git
/// itself fails / returns empty output.
///
/// Implementation note: an earlier version used
/// `git reflog show origin/{branch} --format=%cr -1`. That works on repos
/// whose remote-tracking reflog has multiple entries (a `FETCH_HEAD` with
/// periodic fetches), but for repos that were freshly cloned and never
/// fetched again, `git reflog show origin/<branch>` returns empty output
/// even though the ref is perfectly valid. `git log -1 --format=%cr
/// origin/<branch>` returns the committer date of the current
/// remote-tracking tip in both cases, so it is the right primitive.
fn last_push_for_branch(repo: &Path, branch: &str) -> String {
    if branch.is_empty() || !crate::git::is_safe_branch_name(branch) {
        return "-".to_string();
    }
    let repo_str = repo.to_str().unwrap_or("").to_string();
    let out = crate::git::git_cmd()
        .args([
            "-C",
            &repo_str,
            "log",
            "-1",
            "--format=%cr",
            &format!("origin/{}", branch),
        ])
        .output();
    match out {
        Ok(o) if o.status.success() => {
            let s = String::from_utf8_lossy(&o.stdout);
            s.lines()
                .next()
                .map(|l| l.trim().to_string())
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| "-".to_string())
        }
        _ => "-".to_string(),
    }
}

fn emit_repo_failure(json: bool, prefix: &str, repo: &Path, error: impl std::fmt::Display) {
    let msg = repo_failure_message(prefix, repo, error);
    if json {
        eprintln!("{msg}");
    } else {
        println!("{msg}");
    }
}

/// Count tracked modified files in `repo` that are NOT covered by
pub(crate) async fn run_repos_report(
    policy_path: &Path,
    filter: RepoFilter,
    json: bool,
    sort: &str,
    filter_name: Option<&str>,
    full_path: bool,
) -> Result<()> {
    let policy = SyncPolicy::load(policy_path)?;
    let roots = policy.watch_root_paths();
    let excluded_dir_names = excluded_dir_names_set(&policy);
    let repos = discover_git_repos(
        &roots,
        &excluded_dir_names,
        &policy.exclude_repos,
        Some(&policy.system_repo),
    );
    let mut rows: Vec<RepoReportRow> = Vec::new();
    let mut init_or_status_failures = 0usize;

    // Read the incident ledger once and build a per-repo map of "did the
    // daemon record a push failure in the last 10 minutes?". This lets the
    // report distinguish "has unpushed commits" (normal, daemon is working)
    // from "push is genuinely stuck" (daemon tried and failed).
    let recent_push_failures = build_recent_push_failure_map(policy_path);
    // Also build a per-repo map of the daemon's most recent recorded
    // action (timestamp + label + result). The `last_when` / `last_push`
    // columns show commit/push times but reset to the moment of the
    // daemon's own commit, so they don't reveal whether the daemon is
    // actively syncing vs. whether the user is still editing. The
    // `DAEMON` column closes that gap.
    let daemon_last_actions = build_daemon_last_action_map(policy_path);

    for repo in repos {
        let svc = match GitService::new(&repo) {
            Ok(svc) => svc,
            Err(e) => {
                init_or_status_failures += 1;
                emit_repo_failure(json, "init_failed", &repo, &e);
                continue;
            }
        };

        let status = match svc.get_status().await {
            Ok(status) => status,
            Err(e) => {
                init_or_status_failures += 1;
                emit_repo_failure(json, "status_failed", &repo, &e);
                continue;
            }
        };
        // Per-repo opt-out: when a repo declares itself intentionally
        // isolated (e.g. a legacy private mirror that the operator no
        // longer wants auto-tracked), suppress the implicit concern and
        // surface the intent explicitly.
        let repo_override = crate::policy::load_repo_override(&repo);
        // Skip `repo_diff_entries()` here β€” it calls `git diff --name-status HEAD`
        // which applies the clean filter (dracon-warden age encryption) to every
        // modified file. For repos with many large filtered files (e.g. pnpm-lock.yaml),
        // this takes 10+ seconds per repo and makes the report feel like it's hanging.
        //
        // Libgit2 already correctly excludes .gitignore'd files (target/,
        // node_modules/, build outputs) from its modified count, so it gives us
        // the same "real source changes" answer without the slow clean-filter pass.
        let effective_status = status.clone();

        let has_origin = has_origin_remote(&repo);
        let has_upstream = has_tracking_upstream(&repo);

        // Classification: a repo is WARN if it has TRACKED modifications or
        // staged changes. Untracked files (e.g., target/, node_modules/) are
        // NOT counted β€” they are build artifacts that shouldn't trigger
        // WARN. A repo with only untracked build artifacts is OK.
        // The `recent_push_failure` signal is computed once and used for
        // both the `concern` classification and the `STUCK_PUSH` flag so
        // they stay in sync with the user-visible `repos` table.
        //
        // CHANGED 2026-06-15 (goal 0ab367b5): upgraded `dracon-git` to
        // 94.7.0 which fixed the `is_wt_new()` double-count bug. Junk-Runner-bevy
        // is the canonical case: 3 untracked test-results/ PNGs were
        // being counted as 91 "modified".
        let real_is_dirty = status.modified_files > 0 || status.staged_files > 0;
        let recent_push_failure = recent_push_failures
            .as_ref()
            .map(|m| {
                m.get(repo.to_string_lossy().as_ref())
                    .copied()
                    .unwrap_or(false)
            })
            .unwrap_or(false);
        let mut concern = repo_is_concern_with_push_failure(
            &effective_status,
            has_origin,
            has_upstream,
            recent_push_failure,
        );
        // Repos that the operator has flagged as intentionally isolated
        // (`.dracon/dracon-sync.toml` -> `intentional_no_upstream = true`)
        // are not a hidden concern: the operator has explicitly chosen
        // not to wire the local branch to a remote. The flag below also
        // reclassifies the row so the user sees the explicit intent
        // instead of the implicit "set upstream" hint.
        if repo_override.intentional_no_upstream && concern && !has_upstream {
            concern = false;
        }
        let warn = !concern && real_is_dirty;

        // Flags still use effective_status for ahead/behind/origin detection.
        // Only mark STUCK_PUSH when the daemon has actually recorded a recent
        // push failure for this repo. Without that signal, an AHEAD repo is
        // just "has unpushed commits" β€” the daemon may be in its inactivity
        // delay or mid-cycle.
        let mut flags = repo_state_flags_with_push_failure(
            &effective_status,
            has_origin,
            has_upstream,
            recent_push_failure,
        );
        if repo_override.intentional_no_upstream {
            flags = apply_intentional_no_upstream(flags);
        }

        // ── Ownership override (compute early) ─────────
        // If the policy says to skip unowned repos
        // (`auto_skip_unowned = true`) and this repo is
        // classified as Unowned or Unknown by
        // `ownership::detect_ownership`, override the
        // state_cause to `Unowned { reason, detail }`. We
        // compute this here (before the hint logic) so the
        // HINT column can also surface the unowned reason.
        // Per-repo override `auto_skip_unowned = false`
        // re-enables the daemon for a specific repo.
        let repo_override_for_ownership = crate::policy::load_repo_override(&repo);
        let effective_skip = repo_override_for_ownership
            .auto_skip_unowned
            .unwrap_or(policy.auto_skip_unowned);
        let trusted_for_ownership = crate::ownership::TrustedSet {
            emails: policy.trusted_emails.clone(),
            authors: policy.trusted_authors.clone(),
            remote_hosts: policy.trusted_remote_hosts.clone(),
        };
        let ownership_report = if effective_skip {
            Some(crate::ownership::detect_ownership(
                &repo,
                &trusted_for_ownership,
                repo_override_for_ownership.owned,
            ))
        } else {
            None
        };

        // Pull the daemon's push-retry tracking (consecutive
        // failures + last error message). When the retry budget
        // is exhausted, override the push_status / push_error /
        // hint so the operator sees WHY the push is stuck
        // instead of an opaque `pushing Xm`.
        let stuck_info = crate::daemon::get_stuck_push_info(&repo);
        let push_max_retries = policy.push_max_retries;
        let push_budget_exhausted = stuck_info
            .as_ref()
            .map(|info| {
                push_max_retries > 0
                    && info.consecutive_failures >= push_max_retries
            })
            .unwrap_or(false);

        // ── Unowned hint override ─────────────────────────
        // If the ownership check above classified this repo
        // as Unowned or Unknown (with auto_skip_unowned = true),
        // surface that in the HINT column. The operator
        // needs to know WHY the daemon isn't touching this
        // repo, and what to do about it (run `ownership
        // --explain` to see the raw signals).
        let unowned_hint = match &ownership_report {
            Some(crate::ownership::OwnershipReport::Unowned { reason, .. }) => Some(format!(
                "🚫 unowned: {} β€” run ownership --explain",
                reason
            )),
            Some(crate::ownership::OwnershipReport::Unknown { .. }) => Some(
                "🚫 unowned: unknown β€” run ownership --explain".to_string(),
            ),
            _ => None,
        };

        let hint = if let Some(h) = unowned_hint {
            h
        } else if push_budget_exhausted {
            let info = stuck_info.as_ref().unwrap();
            let error_summary = if info.last_error.is_empty() {
                format!("{} consecutive push failures", info.consecutive_failures)
            } else {
                // Trim long error messages so the HINT column
                // doesn't blow up the table width.
                let trimmed = if info.last_error.chars().count() > 60 {
                    let truncated: String = info.last_error.chars().take(57).collect();
                    format!("{}...", truncated)
                } else {
                    info.last_error.clone()
                };
                format!(
                    "πŸ›‘ push-stuck ({} failures): {} β€” run repair-concerns --apply",
                    info.consecutive_failures, trimmed
                )
            };
            error_summary
        } else {
            repo_hint(&flags, warn, concern)
        };

        // Calculate push status from flags
        let (push_status, push_error) = if push_budget_exhausted {
            let info = stuck_info.as_ref().unwrap();
            let err = if info.last_error.is_empty() {
                format!("{} consecutive push failures", info.consecutive_failures)
            } else {
                info.last_error.clone()
            };
            ("PUSH_STUCK".to_string(), err)
        } else if flags.iter().any(|f| f == "STUCK_PUSH") {
            (
                "STUCK".to_string(),
                format!("ahead={}, push failing", effective_status.ahead),
            )
        } else if flags.iter().any(|f| f == "INTENTIONAL_NO_UPSTREAM") {
            (
                "INTENTIONAL".to_string(),
                "intentional legacy isolation, no upstream configured".to_string(),
            )
        } else if flags.iter().any(|f| f == "NO_UPSTREAM") {
            ("FAIL".to_string(), "no upstream set".to_string())
        } else if effective_status.ahead > 0 && has_origin && has_upstream {
            (
                "PENDING".to_string(),
                format!("{} unpushed commits", effective_status.ahead),
            )
        } else {
            ("OK".to_string(), String::new())
        };

        // Single git log call extracts all commit fields in one process.
        let last_meta = git_log_meta(&repo).await;
        let (last_hash, last_author, last_when, last_unix, last_msg) = match last_meta {
            Some((h, a, w, u, m)) => (truncate(&h, 12), a, w, u, truncate(&m, 72)),
            None => (
                "-".to_string(),
                "-".to_string(),
                "-".to_string(),
                0i64,
                "-".to_string(),
            ),
        };
        // Get last push time from reflog for the current branch only.
        // Scanning all origin/* branches was the second-biggest cost; we only
        // care about the branch we're on. Empty branch (detached HEAD) and
        // unsafe branch names (with shell-special chars) skip the reflog call
        // to avoid `git reflog show origin/` (ambiguous argument) errors.
        let last_push = last_push_for_branch(&repo, &effective_status.branch);

        // Derive the "rough cause" classification that combines all the
        // signals above into a single small-vocabulary label. This is the
        // field the user actually reads to decide whether a repo is
        // actively being worked on, stalling, or cold-idle.
        let thresholds = StateCauseThresholds::from_policy(&policy, &repo_override);
        let last_commit_minutes = parse_relative_minutes(&last_when);
        let last_push_minutes = parse_relative_minutes(&last_push);
        let inputs = StateCauseInputs {
            flags: &flags,
            push_status: &push_status,
            modified: effective_status.modified_files,
            staged: effective_status.staged_files,
            untracked: effective_status.untracked_files,
            ahead: effective_status.ahead,
            behind: effective_status.behind,
            last_commit_minutes,
            last_push_minutes,
        };
        let state_cause = classify_state_cause(&inputs, &thresholds);

        // ── Apply ownership override to state_cause ─────
        // Use the precomputed `ownership_report` from
        // earlier in this function. When the policy says
        // to skip unowned repos AND the repo is classified
        // as Unowned or Unknown, override state_cause to
        // `Unowned { reason, detail }`. The ACTIVITY column
        // shows `🚫 unowned: <reason>` and the HINT column
        // points the operator at `ownership --explain
        // <repo>`.
        let state_cause = match ownership_report {
            Some(crate::ownership::OwnershipReport::Unowned { reason, detail }) => {
                StateCause::Unowned { reason, detail }
            }
            Some(crate::ownership::OwnershipReport::Unknown { detail }) => {
                StateCause::Unowned {
                    reason: "unknown".to_string(),
                    detail,
                }
            }
            _ => state_cause,
        };

        // Look up the daemon's most recent recorded action for this repo
        // from the incident ledger. The map is keyed by the same canonical
        // repo path string we use everywhere else.
        let repo_key = repo.to_string_lossy().to_string();
        let (
            daemon_last_action_unix,
            daemon_last_action,
            daemon_last_result,
            daemon_last_action_when,
        ) = match daemon_last_actions.as_ref().and_then(|m| m.get(&repo_key)) {
            Some((ts, action, result)) if *ts > 0 => {
                let now_secs = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs() as i64)
                    .unwrap_or(0);
                let delta = now_secs.saturating_sub(*ts);
                let when = if delta < 1 {
                    "1s".to_string()
                } else if delta < 60 {
                    format!("{}s ago", delta)
                } else if delta < 3600 {
                    format!("{}m ago", delta / 60)
                } else if delta < 86400 {
                    format!("{}h ago", delta / 3600)
                } else {
                    format!("{}d ago", delta / 86400)
                };
                (*ts, action.clone(), result.clone(), shorten_when(&when))
            }
            _ => (0, String::new(), String::new(), "none".to_string()),
        };

        rows.push(RepoReportRow {
            repo: repo.display().to_string(),
            state_flags: flags,
            branch: effective_status.branch,
            modified: effective_status.modified_files,
            staged: effective_status.staged_files,
            untracked: effective_status.untracked_files,
            ahead: effective_status.ahead,
            behind: effective_status.behind,
            last_hash,
            last_author,
            last_when,
            last_msg,
            last_unix,
            last_push,
            push_status,
            push_error,
            concern,
            warn,
            hint,
            state_cause: state_cause.clone(),
            state_cause_label: state_cause_label_string(&state_cause),
            daemon_last_action_unix,
            daemon_last_action,
            daemon_last_result,
            daemon_last_action_when,
        });
    }

    match sort {
        "name" => rows.sort_by(|a, b| a.repo.cmp(&b.repo)),
        "modified" => rows.sort_by_key(|b| std::cmp::Reverse(b.modified)),
        "ahead" => rows.sort_by_key(|b| std::cmp::Reverse(b.ahead)),
        "behind" => rows.sort_by_key(|b| std::cmp::Reverse(b.behind)),
        _ => rows.sort_by_key(|a| std::cmp::Reverse(a.last_unix)),
    }

    let concern_count_all = rows.iter().filter(|r| r.concern).count();
    let warn_count_all = rows.iter().filter(|r| r.warn).count();
    let ok_count_all = rows
        .len()
        .saturating_sub(concern_count_all + warn_count_all);
    match filter {
        RepoFilter::All => {}
        RepoFilter::Concern => rows.retain(|r| r.concern),
        RepoFilter::Warn => rows.retain(|r| r.warn),
    }

    if let Some(pattern) = filter_name {
        let pat = pattern.to_lowercase();
        rows.retain(|r| {
            let name = std::path::Path::new(&r.repo)
                .file_name()
                .map(|n| n.to_string_lossy().to_lowercase())
                .unwrap_or_default();
            name.contains(&pat)
        });
    }

    let concern_count = rows.iter().filter(|r| r.concern).count();
    let warn_count = rows.iter().filter(|r| r.warn).count();
    let ok_count = rows.len().saturating_sub(concern_count + warn_count);
    let filter_text = match filter {
        RepoFilter::All => "all",
        RepoFilter::Concern => "only_concern",
        RepoFilter::Warn => "only_warn",
    };

    if json {
        let payload = RepoReportJson {
            policy: policy_path.display().to_string(),
            filter: filter_text.to_string(),
            repos: rows.len(),
            ok: ok_count,
            warn: warn_count,
            concern: concern_count,
            failures: init_or_status_failures,
            rows,
        };
        println!("{}", serde_json::to_string_pretty(&payload)?);
        return Ok(());
    }

    println!("πŸ“œ {}", policy_path.display());
    match filter {
        RepoFilter::All => {}
        RepoFilter::Concern => {
            println!(
                "πŸ“Š FILTER: only concern repos (showing {} of {})",
                rows.len(),
                concern_count_all
            );
        }
        RepoFilter::Warn => {
            println!(
                "πŸ“Š FILTER: only warn repos (showing {} of {})",
                rows.len(),
                warn_count_all
            );
        }
    }
    // ---- Summary one-liner (color-aware, no raw ANSI when piped) ----
    let ok_str = ansi("32", &format!("βœ… OK {ok_count}"));
    let warn_str = ansi("33", &format!("⚠️  WARN {warn_count}"));
    let concern_str = ansi("31", &format!("❌ CONCERN {concern_count}"));
    let filter_note = match filter {
        RepoFilter::All => String::new(),
        RepoFilter::Concern | RepoFilter::Warn => format!(
            "  (all: OK {} WARN {} CONCERN {})",
            ok_count_all, warn_count_all, concern_count_all
        ),
    };
    println!(
        "πŸ“¦ {total} repos  {ok_str}  {warn_str}  {concern_str}  β›” init/status failed: {init_or_status_failures}{filter_note}",
        total = rows.len(),
    );
    println!();

    // ---- Legend line (one-liner mapping column codes to their meaning) ----
    println!(
        "ℹ️  Legend: MOD = modified tracked Β· STG = staged Β· UT = untracked Β· ↑ = ahead of upstream Β· ↓ = behind upstream Β· PUSH = push status Β· STATE = derived cause (working=daemon just synced/committing/pushing/synced=clean & in sync/stalled/dirty/untracked-only/intentional/failed/idle/cold/healthy) Β· ACTIVITY = real activity indicator (now=daemon processing this repo Β· pushing Xm (N ahead)=push in progress, N unpushed commits Β· stalled Xm=dirty & no daemon action for X minutes Β· settling=dirty & waiting for fingerprint stability Β· synced/idle/cold=clean & waiting) Β· DAEMON = daemon's last recorded action (e.g. '23s sync_triage') so you can tell the daemon is working through dirty rows vs. you're editing right now"
    );
    println!();

    use comfy_table::{
        presets::UTF8_FULL_CONDENSED, Attribute, Cell, Color, ContentArrangement, Table,
    };

    let mut table = Table::new();
    table.load_preset(UTF8_FULL_CONDENSED);
    table.set_content_arrangement(ContentArrangement::Dynamic);
    // Single-line header cells: icon + space + label (no newline)
    let mk_h = |icon: &str, label: &str| -> Cell {
        Cell::new(format!("{icon} {label}")).add_attribute(Attribute::Bold)
    };
    // Set fixed column widths so the table doesn't wrap rows on 100+ col terminals
    // and truncates gracefully on narrower ones.
    table.set_header(vec![
        Cell::new("#"),
        mk_h("🏷", "STATUS"),
        mk_h("πŸ“¦", "REPO"),
        mk_h("🌿", "BRANCH"),
        mk_h("πŸ“", "MOD"),
        mk_h("πŸ“₯", "STG"),
        mk_h("❓", "UT"),
        mk_h("↑", "AHEAD"),
        mk_h("↓", "BEHIND"),
        mk_h("πŸš€", "PUSH"),
        mk_h("πŸ“œ", "LAST COMMIT"),
        mk_h("πŸ“€", "PUSHED"),
        mk_h("⏰", "ACTIVITY"),
        mk_h("πŸ‘€", "AUTHOR"),
        mk_h("🩺", "STATE"),
        mk_h("πŸ€–", "DAEMON"),
        mk_h("πŸ’‘", "HINT"),
    ]);

    for (idx, row) in rows.iter().enumerate() {
        let (status_text, status_color) = if row.concern {
            ("❌ CONCERN".to_string(), Color::Red)
        } else if row.warn {
            ("⚠️  WARN".to_string(), Color::Yellow)
        } else {
            ("βœ… OK".to_string(), Color::Green)
        };

        let repo_name = if full_path {
            row.repo.clone()
        } else {
            std::path::Path::new(&row.repo)
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| row.repo.clone())
        };

        let push_color = match row.push_status.as_str() {
            "OK" | "INTENTIONAL" => Color::Green,
            "PENDING" => Color::Yellow,
            "FAIL" | "STUCK" => Color::Red,
            _ => Color::White,
        };

        let state_color = match row.state_cause {
            StateCause::Working | StateCause::Synced => Color::Green,
            StateCause::Committing | StateCause::Pushing | StateCause::Dirty => Color::Yellow,
            StateCause::Stalled | StateCause::Failed => Color::Red,
            StateCause::Intentional => Color::Magenta,
            StateCause::Untracked | StateCause::Idle => Color::White,
            StateCause::Cold | StateCause::Healthy => Color::DarkGrey,
            // Unowned: red β€” the daemon is intentionally not
            // touching this repo, the operator must intervene.
            StateCause::Unowned { .. } => Color::Red,
        };

        // Color-code numeric columns based on severity
        let modified_color = if row.modified > 0 {
            Color::Yellow
        } else {
            Color::White
        };
        let staged_color = if row.staged > 0 {
            Color::Cyan
        } else {
            Color::White
        };
        let ahead_color = if row.ahead > 0 {
            Color::Yellow
        } else {
            Color::White
        };
        let behind_color = if row.behind > 0 {
            Color::Red
        } else {
            Color::White
        };

        // Color branches: main/master in bold, others in cyan
        let branch_color = if row.branch == "main" || row.branch == "master" {
            Color::White
        } else {
            Color::Cyan
        };

        // Compose a one-line commit summary: "<short-hash> <subject>"
        let commit_summary = if row.last_hash == "-" {
            "-".to_string()
        } else {
            format!("{} {}", row.last_hash, row.last_msg)
        };

        table.add_row(vec![
            Cell::new(idx + 1),
            Cell::new(status_text).fg(status_color),
            Cell::new(repo_name),
            Cell::new(&row.branch).fg(branch_color),
            Cell::new(row.modified).fg(modified_color),
            Cell::new(row.staged).fg(staged_color),
            Cell::new(row.untracked),
            Cell::new(row.ahead).fg(ahead_color),
            Cell::new(row.behind).fg(behind_color),
            Cell::new(&row.push_status).fg(push_color),
            Cell::new(commit_summary),
            Cell::new(shorten_when(&row.last_push)),
            Cell::new(activity_label(&row)),
            Cell::new(&row.last_author),
            Cell::new(format!(
                "{} {}",
                row.state_cause.icon(),
                row.state_cause.as_str()
            ))
            .fg(state_color),
            Cell::new(format!(
                "{} {}",
                row.daemon_last_action_when, row.daemon_last_action
            ))
            .fg(if row.daemon_last_result == "fail" {
                Color::Red
            } else if row.daemon_last_result == "ok" {
                Color::Green
            } else if row.daemon_last_action_when == "none" {
                Color::DarkGrey
            } else {
                Color::Cyan
            }),
            Cell::new(&row.hint).fg(if row.concern {
                Color::Red
            } else if row.warn {
                Color::Yellow
            } else {
                Color::Green
            }),
        ]);
    }

    println!("{table}");

    Ok(())
}

pub(crate) fn log_incident(
    policy_path: &Path,
    scope: impl Into<String>,
    repo: impl Into<String>,
    reason: impl Into<String>,
    action: impl Into<String>,
    backup_branch: Option<String>,
    result: impl Into<String>,
    details: Option<String>,
) {
    let record = IncidentRecord::new(
        timestamp_secs(),
        scope,
        repo,
        reason,
        action,
        backup_branch,
        result,
        details,
    );
    append_incident_record(policy_path, &record);
}

struct RepairState {
    attempted_ops: usize,
    succeeded_ops: usize,
    manual_only: usize,
    has_origin: bool,
    has_upstream: bool,
    push_ok: bool,
}

async fn handle_no_origin(
    state: &mut RepairState,
    repo: &Path,
    apply: bool,
    human: bool,
    policy: &SyncPolicy,
    reason: &str,
    policy_path: &Path,
) -> bool {
    if state.has_origin {
        return false;
    }
    state.attempted_ops += 1;
    if apply {
        let private_remote = if policy.auto_github_private {
            if human {
                println!("   plan: create GitHub private repo as origin");
            }
            create_github_private_remote(repo, &policy.auto_github_private_account, true)
        } else {
            if human {
                println!("   plan: create private bare repo as origin");
            }
            create_private_remote(repo)
        };
        if let Some(private_remote) = private_remote {
            state.succeeded_ops += 1;
            state.has_origin = true;
            state.has_upstream = true;
            if human {
                println!("   ok: created private remote: {}", private_remote);
            }
            log_incident(
                policy_path,
                "concern",
                repo.display().to_string(),
                reason,
                "create_private_remote",
                None,
                "ok",
                Some(format!("created private remote: {}", private_remote)),
            );
        } else {
            state.manual_only += 1;
            if human {
                println!("   fail: could not create private remote");
            }
            log_incident(
                policy_path,
                "concern",
                repo.display().to_string(),
                reason,
                "create_private_remote",
                None,
                "fail",
                Some("failed to create private remote".to_string()),
            );
        }
    }
    true
}

async fn handle_no_upstream(
    state: &mut RepairState,
    repo: &Path,
    apply: bool,
    human: bool,
    push_timeout_secs: u64,
    _push_retries: u32,
    reason: &str,
    policy_path: &Path,
) -> bool {
    if state.has_upstream {
        return false;
    }
    state.attempted_ops += 1;
    if human {
        println!("   plan: set upstream via `git push -u origin HEAD`");
    }
    if apply {
        match run_git_with_timeout(
            repo,
            &["push", "-u", "origin", "HEAD"],
            push_timeout_secs,
            "push -u",
        )
        .await
        {
            Ok(()) => {
                state.succeeded_ops += 1;
                state.has_upstream = true;
                if human {
                    println!("   ok: upstream configured");
                }
                log_incident(
                    policy_path,
                    "concern",
                    repo.display().to_string(),
                    reason,
                    "set_upstream_push_u",
                    None,
                    "ok",
                    None,
                );
            }
            Err(e) => {
                if human {
                    println!("   fail: upstream configure failed: {}", e);
                }
                log_incident(
                    policy_path,
                    "concern",
                    repo.display().to_string(),
                    reason,
                    "set_upstream_push_u",
                    None,
                    "fail",
                    Some(e.to_string()),
                );
                return true;
            }
        }
    }
    false
}

async fn handle_behind(
    state: &mut RepairState,
    repo: &Path,
    apply: bool,
    human: bool,
    pull_timeout_secs: u64,
    reason: &str,
    policy_path: &Path,
) -> bool {
    state.attempted_ops += 1;
    if human {
        println!("   plan: pull --no-rebase (merge)");
    }
    if apply {
        match run_git_with_timeout(
            repo,
            &["pull", "--no-rebase"],
            pull_timeout_secs,
            "pull/merge",
        )
        .await
        {
            Ok(()) => {
                state.succeeded_ops += 1;
                if human {
                    println!("   ok: pulled");
                }
                log_incident(
                    policy_path,
                    "concern",
                    repo.display().to_string(),
                    reason,
                    "pull_merge",
                    None,
                    "ok",
                    None,
                );
            }
            Err(e) => {
                if human {
                    println!("   fail: pull failed: {}", e);
                }
                log_incident(
                    policy_path,
                    "concern",
                    repo.display().to_string(),
                    reason,
                    "pull_merge",
                    None,
                    "fail",
                    Some(e.to_string()),
                );
            }
        }
    }
    false
}

#[allow(clippy::too_many_arguments)]
async fn handle_ahead(
    state: &mut RepairState,
    repo: &Path,
    apply: bool,
    human: bool,
    push_timeout_secs: u64,
    push_retries: u32,
    blob_threshold: u64,
    rewrite_large_any: bool,
    excluded_dir_names: &std::collections::BTreeSet<String>,
    reason: &str,
    policy_path: &Path,
    svc: &GitService,
) -> bool {
    state.attempted_ops += 1;
    if human {
        println!("   plan: push origin HEAD");
    }
    state.push_ok = false;
    if !apply {
        return false;
    }
    #[allow(unused_assignments)]
    match push_with_retries(repo, push_timeout_secs, push_retries, "push").await {
        Ok(()) => {
            state.succeeded_ops += 1;
            state.push_ok = true;
            if human {
                println!("   ok: pushed");
            }
            log_incident(
                policy_path,
                "concern",
                repo.display().to_string(),
                reason,
                "push_origin_head",
                None,
                "ok",
                None,
            );
            // Also push to mirror remotes (codeberg, gitlab, etc.)
            if let Ok(policy) = SyncPolicy::load(policy_path) {
                if !policy.remotes.is_empty() {
                    let mirror_results = push_mirror_remotes(
                        repo,
                        &policy.remotes,
                        push_timeout_secs,
                        push_retries,
                        true,
                    )
                    .await;
                    for (name, result) in &mirror_results {
                        if let Err(e) = result {
                            if human {
                                println!("   warn: mirror push to {} failed: {}", name, e);
                            }
                        }
                    }
                }
            }
        }
        Err(e) => {
            if human {
                println!("   fail: push failed: {}", e);
            }

            let err_str = e.to_string().to_lowercase();

            // Check if push failed because remote doesn't exist or is unreachable
            // In this case, auto-create a private bare repo as the remote
            let no_remote = err_str.contains("no such remote")
                || err_str.contains("remote does not exist")
                || err_str.contains("repository not found")
                || err_str.contains("could not resolve host")
                || err_str.contains("does not appear to be a git repository")
                || (err_str.contains("exit status: 128") && err_str.contains("fatal:"));

            if no_remote {
                // Try to create a private bare repo and use it as origin
                if human {
                    println!("   info: no remote detected, creating private bare repo");
                }
                if let Some(private_remote) = create_private_remote(repo) {
                    if human {
                        println!("   info: created private remote: {}", private_remote);
                    }
                    // Retry push with new remote
                    match push_with_retries(repo, push_timeout_secs, push_retries, "push").await {
                        Ok(()) => {
                            state.succeeded_ops += 1;
                            state.push_ok = true;
                            if human {
                                println!("   ok: pushed to private remote");
                            }
                            log_incident(
                                policy_path,
                                "concern",
                                repo.display().to_string(),
                                reason,
                                "push_origin_head",
                                None,
                                "ok",
                                Some(format!("pushed to private remote: {}", private_remote)),
                            );
                            return true;
                        }
                        Err(e2) => {
                            if human {
                                println!("   fail: push to private remote also failed: {}", e2);
                            }
                            log_incident(
                                policy_path,
                                "concern",
                                repo.display().to_string(),
                                reason,
                                "push_origin_head",
                                None,
                                "fail",
                                Some(e2.to_string()),
                            );
                            return true;
                        }
                    }
                } else {
                    if human {
                        println!("   fail: could not create private remote");
                    }
                    log_incident(
                        policy_path,
                        "concern",
                        repo.display().to_string(),
                        reason,
                        "push_origin_head",
                        None,
                        "fail",
                        Some(e.to_string()),
                    );
                    return true;
                }
            }

            // For permission denied or other errors on existing remote,
            // just record failure and continue - no permanent marking
            // These will retry on next cycle naturally
            log_incident(
                policy_path,
                "concern",
                repo.display().to_string(),
                reason,
                "push_origin_head",
                None,
                "fail",
                Some(e.to_string()),
            );
            // Don't continue here - let it fall through to large blob detection below
            // (but without the manual_only marking)

            let large = detect_large_blobs_ahead(repo, blob_threshold)
                .await
                .unwrap_or_default();
            if !large.is_empty() {
                if human {
                    println!(
                        "   detect: large blobs in ahead range ({} entries)",
                        large.len()
                    );
                }
                let mut dirs = BTreeSet::new();
                for (_, path) in &large {
                    if let Some(dir) = top_level_dir(path) {
                        if is_excluded_dir_name(&dir, excluded_dir_names) {
                            dirs.insert(dir);
                        }
                    }
                }
                let dirs: Vec<String> = dirs.into_iter().collect();
                let rewrite_paths: Vec<String> = if !dirs.is_empty() {
                    dirs
                } else if rewrite_large_any {
                    let mut unique = BTreeSet::new();
                    for (_, p) in &large {
                        unique.insert(p.clone());
                    }
                    unique.into_iter().collect()
                } else {
                    Vec::new()
                };

                if rewrite_paths.is_empty() {
                    if human {
                        println!("   manual: large blobs found but not in excluded dirs");
                    }
                    log_incident(
                        policy_path,
                        "concern",
                        repo.display().to_string(),
                        reason,
                        "large_blob_detected",
                        None,
                        "manual",
                        Some(format!(
                            "threshold={} entries={} rewrite_allowed=false",
                            blob_threshold,
                            large.len()
                        )),
                    );
                } else {
                    if human {
                        println!(
                            "   plan: rewrite ahead history removing paths {:?}",
                            rewrite_paths
                        );
                    }
                    match rewrite_ahead_paths(repo, &rewrite_paths, "backup/pre-sync-largeblob-fix")
                    {
                        Ok(Some(backup_branch)) => {
                            let backup_branch_for_log = backup_branch.clone();
                            if human {
                                println!(
                                    "   ok: rewrite complete (backup branch: {})",
                                    backup_branch
                                );
                            }
                            match push_with_retries(
                                repo,
                                push_timeout_secs,
                                push_retries,
                                "push-after-rewrite",
                            )
                            .await
                            {
                                Ok(()) => {
                                    state.succeeded_ops += 1;
                                    state.push_ok = true;
                                    if human {
                                        println!("   ok: pushed after rewrite");
                                    }
                                    log_incident(
                                        policy_path,
                                        "concern",
                                        repo.display().to_string(),
                                        reason,
                                        "rewrite_then_push",
                                        Some(backup_branch_for_log),
                                        "ok",
                                        Some(format!("paths={:?}", rewrite_paths)),
                                    );
                                    // Also push to mirror remotes
                                    if let Ok(policy) = SyncPolicy::load(policy_path) {
                                        if !policy.remotes.is_empty() {
                                            push_mirror_remotes(
                                                repo,
                                                &policy.remotes,
                                                push_timeout_secs,
                                                push_retries,
                                                true,
                                            )
                                            .await;
                                        }
                                    }
                                }
                                Err(e2) => {
                                    if human {
                                        println!("   fail: push after rewrite failed: {}", e2);
                                    }
                                    log_incident(
                                        policy_path,
                                        "concern",
                                        repo.display().to_string(),
                                        reason,
                                        "rewrite_then_push",
                                        Some(backup_branch),
                                        "fail",
                                        Some(e2.to_string()),
                                    );
                                }
                            }
                        }
                        Ok(None) => {}
                        Err(rewrite_err) => {
                            if human {
                                println!("   fail: rewrite failed: {}", rewrite_err);
                            }
                            log_incident(
                                policy_path,
                                "concern",
                                repo.display().to_string(),
                                reason,
                                "rewrite_large_blob",
                                None,
                                "fail",
                                Some(rewrite_err.to_string()),
                            );
                        }
                    }
                }
            } else {
                let branch = current_branch(repo).unwrap_or_default();
                let dry_run = run_git_capture_output(
                    repo,
                    &["push", "--dry-run", "origin", "HEAD"],
                    "push --dry-run",
                )
                .unwrap_or_default();
                let looks_branch_mismatch = dry_run.to_ascii_lowercase().contains("up-to-date");
                if looks_branch_mismatch
                    && !branch.is_empty()
                    && remote_branch_exists(repo, &branch)
                    && has_tracking_upstream(repo)
                {
                    if human {
                        println!(
                            "   plan: align upstream to origin/{} (possible branch mismatch)",
                            branch
                        );
                    }
                    match set_upstream_to_branch(repo, &branch) {
                        Ok(()) => {
                            if human {
                                println!("   ok: upstream realigned");
                            }
                            match push_with_retries(
                                repo,
                                push_timeout_secs,
                                push_retries,
                                "push-after-upstream-align",
                            )
                            .await
                            {
                                Ok(()) => {
                                    state.succeeded_ops += 1;
                                    state.push_ok = true;
                                    if human {
                                        println!("   ok: pushed after upstream align");
                                    }
                                    log_incident(
                                        policy_path,
                                        "concern",
                                        repo.display().to_string(),
                                        reason,
                                        "realign_upstream_then_push",
                                        None,
                                        "ok",
                                        Some(format!("branch={}", branch)),
                                    );
                                    // Also push to mirror remotes
                                    if let Ok(policy) = SyncPolicy::load(policy_path) {
                                        if !policy.remotes.is_empty() {
                                            push_mirror_remotes(
                                                repo,
                                                &policy.remotes,
                                                push_timeout_secs,
                                                push_retries,
                                                true,
                                            )
                                            .await;
                                        }
                                    }
                                }
                                Err(e2) => {
                                    if human {
                                        println!(
                                            "   fail: push after upstream align failed: {}",
                                            e2
                                        );
                                    }
                                    log_incident(
                                        policy_path,
                                        "concern",
                                        repo.display().to_string(),
                                        reason,
                                        "realign_upstream_then_push",
                                        None,
                                        "fail",
                                        Some(e2.to_string()),
                                    );
                                }
                            }
                        }
                        Err(set_err) => {
                            if human {
                                println!("   fail: upstream align failed: {}", set_err);
                            }
                        }
                    }
                }
            }
        }
    }
    if !state.push_ok {
        log_incident(
            policy_path,
            "concern",
            repo.display().to_string(),
            reason,
            "push_origin_head",
            None,
            "fail",
            Some("push did not clear concern".to_string()),
        );
    }
    if state.push_ok {
        if let Ok(next_after_push) = svc.get_status().await {
            if next_after_push.ahead > 0 {
                let branch = current_branch(repo).unwrap_or_default();
                if !branch.is_empty() && remote_branch_exists(repo, &branch) {
                    if human {
                        println!(
                            "   plan: realign upstream to origin/{} (ahead still > 0 after push)",
                            branch
                        );
                    }
                    match set_upstream_to_branch(repo, &branch) {
                        Ok(()) => {
                            if human {
                                println!("   ok: upstream realigned");
                            }
                        }
                        Err(e) => {
                            if human {
                                println!("   fail: upstream realign failed: {}", e);
                            }
                        }
                    }
                }
            }
        }
    }
    false
}

async fn verify_resolution(
    repo: &Path,
    apply: bool,
    human: bool,
    resolved: &mut usize,
    reason: &str,
    policy_path: &Path,
    svc: &GitService,
) {
    if !apply {
        return;
    }
    if let Ok(next) = svc.get_status().await {
        let has_origin = has_origin_remote(repo);
        let has_upstream = has_tracking_upstream(repo);
        let still_concern = next.ahead > 0 || next.behind > 0 || !has_origin || !has_upstream;
        if !still_concern {
            *resolved += 1;
            if human {
                println!("   resolved: concern cleared");
            }
            log_incident(
                policy_path,
                "concern",
                repo.display().to_string(),
                reason,
                "verify_resolved",
                None,
                "ok",
                None,
            );
        } else {
            if human {
                println!(
                    "   remaining: ahead={} behind={} origin={} upstream={}",
                    next.ahead, next.behind, has_origin, has_upstream
                );
            }
            // Only notify on true divergence (both ahead AND behind) - that's
            // the only case where we have no automatic resolution.
            // If just ahead > 0, we can push. If just behind > 0, we can pull.
            if next.ahead > 0 && next.behind > 0 {
                let details = format!("ahead={} behind={}", next.ahead, next.behind);
                send_sync_conflict_notification(repo, reason, &details);
            }
            log_incident(
                policy_path,
                "concern",
                repo.display().to_string(),
                reason,
                "verify_resolved",
                None,
                "remaining",
                Some(format!("ahead={} behind={}", next.ahead, next.behind)),
            );
        }
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) async fn run_repair_concerns(
    policy_path: &Path,
    apply: bool,
    only_repo: Option<PathBuf>,
    push_timeout_override: Option<u64>,
    push_retries: u32,
    rewrite_large_any: bool,
    filter: ConcernRepairFilter,
    json: bool,
) -> Result<RepairSummary> {
    let human = !json;
    macro_rules! out {
        ($($arg:tt)*) => {{
            if human {
                println!($($arg)*);
            }
        }};
    }

    let policy = SyncPolicy::load(policy_path)?;
    let roots = policy.watch_root_paths();
    let excluded_dir_names = excluded_dir_names_set(&policy);
    let repos = if let Some(target_repo) = &only_repo {
        vec![target_repo.clone()]
    } else {
        discover_git_repos(
            &roots,
            &excluded_dir_names,
            &policy.exclude_repos,
            Some(&policy.system_repo),
        )
    };
    if repos.is_empty() {
        if let Some(target_repo) = &only_repo {
            out!(
                "⚠️ target repo not discovered in policy roots: {}",
                target_repo.display()
            );
        }
        return Ok(RepairSummary::default());
    }
    let push_timeout_secs = push_timeout_override
        .unwrap_or(policy.push_op_timeout_secs)
        .max(10);
    let push_retries = push_retries.max(1);
    let blob_threshold = push_large_blob_threshold_bytes(&policy);

    let mut concerns = 0usize;
    let mut state = RepairState {
        attempted_ops: 0,
        succeeded_ops: 0,
        manual_only: 0,
        has_origin: false,
        has_upstream: false,
        push_ok: false,
    };
    let mut resolved = 0usize;
    // Use the same refined concern logic as the `repos` command: an
    // AHEAD repo is only a concern if a recent push failure was recorded.
    let recent_push_failures = build_recent_push_failure_map(policy_path);

    for repo in repos {
        let svc = match GitService::new(&repo) {
            Ok(svc) => svc,
            Err(e) => {
                eprintln!("⚠️ {} init_failed: {}", repo.display(), e);
                continue;
            }
        };
        let mut status = match svc.get_status().await {
            Ok(status) => status,
            Err(e) => {
                eprintln!("⚠️ {} status_failed: {}", repo.display(), e);
                continue;
            }
        };
        // Repos the operator has flagged as intentionally isolated are
        // not a hidden concern: skip them entirely so `repair concerns`
        // does not propose `git push -u origin HEAD` against a remote
        // the operator has explicitly chosen to leave unconnected.
        let repo_override = crate::policy::load_repo_override(&repo);
        if repo_override.intentional_no_upstream
            && !has_tracking_upstream(&repo)
            && only_repo.is_none()
        {
            out!(
                "ℹ️  {}  skipped: intentional_no_upstream set in .dracon/dracon-sync.toml",
                repo.display()
            );
            continue;
        }

        state.has_origin = has_origin_remote(&repo);
        state.has_upstream = has_tracking_upstream(&repo);
        // Use the same refined concern logic as the `repos` command:
        // an AHEAD repo is only a concern if a recent push failure was
        // recorded. This keeps `repair concerns` consistent with the
        // user-visible `repos` table.
        let recent_push_failure = recent_push_failures
            .as_ref()
            .map(|m| {
                m.get(repo.to_string_lossy().as_ref())
                    .copied()
                    .unwrap_or(false)
            })
            .unwrap_or(false);
        let is_concern = repo_is_concern_with_push_failure(
            &status,
            state.has_origin,
            state.has_upstream,
            recent_push_failure,
        );
        if !is_concern {
            continue;
        }
        let stuck_push = repo_is_stuck_push(
            &status,
            state.has_origin,
            state.has_upstream,
            recent_push_failure,
        );
        let stuck_pull = repo_is_stuck_pull(&status, state.has_origin, state.has_upstream);
        if matches!(filter, ConcernRepairFilter::StuckPush) && !stuck_push {
            continue;
        }
        if matches!(filter, ConcernRepairFilter::StuckPull) && !stuck_pull {
            continue;
        }
        concerns += 1;
        let flags = repo_state_flags_with_push_failure(
            &status,
            state.has_origin,
            state.has_upstream,
            recent_push_failure,
        );
        let reason = flags.join(",");

        out!(
            "\nπŸ”Ž {}  state: ahead={} behind={} clean={} origin={} upstream={}",
            repo.display(),
            status.ahead,
            status.behind,
            status.is_clean,
            state.has_origin,
            state.has_upstream
        );

        if handle_no_origin(
            &mut state,
            &repo,
            apply,
            human,
            &policy,
            &reason,
            policy_path,
        )
        .await
        {
            continue;
        }

        if handle_no_upstream(
            &mut state,
            &repo,
            apply,
            human,
            push_timeout_secs,
            push_retries,
            &reason,
            policy_path,
        )
        .await
        {
            continue;
        }

        #[allow(clippy::collapsible_if)]
        if status.behind > 0 && state.has_upstream {
            if handle_behind(
                &mut state,
                &repo,
                apply,
                human,
                policy.pull_op_timeout_secs,
                &reason,
                policy_path,
            )
            .await
            {
                continue;
            }
            // Re-fetch status after pull β€” the repo state may have changed
            // (e.g. diverged repo is now just ahead after merge).
            if let Ok(new_status) = svc.get_status().await {
                status = new_status;
                state.has_upstream = has_tracking_upstream(&repo);
            }
        }

        #[allow(clippy::collapsible_if)]
        if status.ahead > 0 && state.has_upstream {
            if handle_ahead(
                &mut state,
                &repo,
                apply,
                human,
                push_timeout_secs,
                push_retries,
                blob_threshold,
                rewrite_large_any,
                &excluded_dir_names,
                &reason,
                policy_path,
                &svc,
            )
            .await
            {
                continue;
            }
        }

        verify_resolution(
            &repo,
            apply,
            human,
            &mut resolved,
            &reason,
            policy_path,
            &svc,
        )
        .await;
    }

    let summary = RepairSummary {
        found: concerns,
        planned: state.attempted_ops,
        attempted: if apply { state.attempted_ops } else { 0 },
        succeeded: state.succeeded_ops,
        resolved_now: if apply { resolved } else { 0 },
        manual_only: state.manual_only,
    };
    if json {
        let payload = RepairJson {
            policy: policy_path.display().to_string(),
            scope: "concern".to_string(),
            mode: if apply {
                "apply".to_string()
            } else {
                "dry_run".to_string()
            },
            found: summary.found,
            planned: summary.planned,
            attempted: summary.attempted,
            succeeded: summary.succeeded,
            resolved_now: summary.resolved_now,
            manual_only: summary.manual_only,
            ledger: incident_ledger_path(policy_path).display().to_string(),
        };
        println!("{}", serde_json::to_string_pretty(&payload)?);
    } else if summary.found > 0 {
        println!("\nβœ… Concern management summary");
        println!("   concerns_found: {}", summary.found);
        println!("   operations_planned: {}", summary.planned);
        println!("   operations_succeeded: {}", summary.succeeded);
        println!("   manual_only: {}", summary.manual_only);
        if apply {
            println!("   concerns_resolved_now: {}", summary.resolved_now);
        } else {
            println!("   dry_run: true (rerun with --apply to execute)");
        }
        println!("   ledger: {}", incident_ledger_path(policy_path).display());
    }

    Ok(summary)
}

pub(crate) async fn run_repair_warns(
    policy_path: &Path,
    apply: bool,
    only_repo: Option<PathBuf>,
    json: bool,
) -> Result<RepairSummary> {
    let human = !json;
    macro_rules! out {
        ($($arg:tt)*) => {{
            if human {
                println!($($arg)*);
            }
        }};
    }

    let policy = SyncPolicy::load(policy_path)?;
    let roots = policy.watch_root_paths();
    let excluded_dir_names = excluded_dir_names_set(&policy);
    let repos = if let Some(target_repo) = &only_repo {
        vec![target_repo.clone()]
    } else {
        discover_git_repos(
            &roots,
            &excluded_dir_names,
            &policy.exclude_repos,
            Some(&policy.system_repo),
        )
    };
    if repos.is_empty() {
        if let Some(target_repo) = &only_repo {
            out!(
                "⚠️ target repo not discovered in policy roots: {}",
                target_repo.display()
            );
        }
        return Ok(RepairSummary::default());
    }

    let mut warns = 0usize;
    let mut attempted = 0usize;
    let mut succeeded = 0usize;

    for repo in repos {
        let svc = match GitService::new(&repo) {
            Ok(svc) => svc,
            Err(e) => {
                eprintln!("⚠️ {} init_failed: {}", repo.display(), e);
                continue;
            }
        };
        let status = match svc.get_status().await {
            Ok(status) => status,
            Err(e) => {
                eprintln!("⚠️ {} status_failed: {}", repo.display(), e);
                continue;
            }
        };
        let entries = repo_diff_entries(&repo).await.unwrap_or_default();
        let effective_dirty = has_sync_relevant_dirty_entries(
            &repo,
            &entries,
            &excluded_dir_names,
            &policy.exclude_file_patterns,
            policy.max_stage_file_bytes,
            &policy.auto_commit_exclude_patterns,
        );
        let has_origin = has_origin_remote(&repo);
        let has_upstream = has_tracking_upstream(&repo);
        let mut effective_status = status.clone();
        effective_status.is_clean = !effective_dirty;
        effective_status.modified_files = status.modified_files;
        effective_status.staged_files = status.staged_files;
        // CHANGED 2026-06-15 (goal 0ab367b5 / Junk-Runner-bevy WARN fix):
        // `dracon-git` was upgraded 94.2.7 β†’ 94.7.0. The new version
        // correctly separates untracked from modified (the old version
        // counted `is_wt_new()` as modified, causing 91 false MOD for
        // Junk-Runner-bevy when 3 untracked test-results/ PNGs were
        // involved). `RepoStatus` now has an `untracked_files` field
        // so we copy it through.
        effective_status.untracked_files = status.untracked_files;
        // Use real dirty state for classification β€” a repo with TRACKED
        // modified files is WARN even if the daemon wouldn't auto-commit them.
        // Untracked files (build artifacts) do NOT count as dirty.
        let real_is_dirty = status.modified_files > 0 || status.staged_files > 0;
        if !real_is_dirty {
            continue;
        }
        warns += 1;
        let flags = repo_state_flags(&effective_status, has_origin, has_upstream);
        let reason = flags.join(",");
        out!(
            "\n🟑 {}  state={} modified={} staged={}",
            repo.display(),
            reason,
            effective_status.modified_files,
            effective_status.staged_files
        );
        out!("   plan: run normal sync triage (stage/commit/push)");
        if !apply {
            append_incident_record(
                policy_path,
                &IncidentRecord {
                    ts_unix: timestamp_secs(),
                    scope: "warn".to_string(),
                    repo: repo.display().to_string(),
                    reason,
                    action: "dry_run_sync_triage".to_string(),
                    backup_branch: None,
                    result: "planned".to_string(),
                    details: None,
                },
            );
            continue;
        }

        attempted += 1;
        match crate::sync::sync_repo(
            &repo,
            &policy,
            &excluded_dir_names,
            0,
            None,
            false,
            Some(policy_path),
        )
        .await
        {
            Ok(outcome) => {
                succeeded += 1;
                out!("   ok: triage complete changed={}", outcome.has_changes());
                append_incident_record(
                    policy_path,
                    &IncidentRecord {
                        ts_unix: timestamp_secs(),
                        scope: "warn".to_string(),
                        repo: repo.display().to_string(),
                        reason,
                        action: "sync_triage".to_string(),
                        backup_branch: None,
                        result: "ok".to_string(),
                        details: Some(format!("changed={}", outcome.has_changes())),
                    },
                );
            }
            Err(e) => {
                out!("   fail: sync triage failed: {}", e);
                append_incident_record(
                    policy_path,
                    &IncidentRecord {
                        ts_unix: timestamp_secs(),
                        scope: "warn".to_string(),
                        repo: repo.display().to_string(),
                        reason,
                        action: "sync_triage".to_string(),
                        backup_branch: None,
                        result: "fail".to_string(),
                        details: Some(e.to_string()),
                    },
                );
            }
        }
    }

    let summary = RepairSummary {
        found: warns,
        planned: warns,
        attempted,
        succeeded,
        resolved_now: 0,
        manual_only: 0,
    };
    if json {
        let payload = RepairJson {
            policy: policy_path.display().to_string(),
            scope: "warn".to_string(),
            mode: if apply {
                "apply".to_string()
            } else {
                "dry_run".to_string()
            },
            found: summary.found,
            planned: summary.planned,
            attempted: summary.attempted,
            succeeded: summary.succeeded,
            resolved_now: summary.resolved_now,
            manual_only: summary.manual_only,
            ledger: incident_ledger_path(policy_path).display().to_string(),
        };
        println!("{}", serde_json::to_string_pretty(&payload)?);
    } else if summary.found > 0 {
        println!("\nβœ… Warn management summary");
        println!("   warns_found: {}", summary.found);
        println!("   operations_planned: {}", summary.planned);
        println!("   operations_attempted: {}", summary.attempted);
        println!("   operations_succeeded: {}", summary.succeeded);
        if !apply {
            println!("   dry_run: true (rerun with --apply to execute)");
        }
        println!("   ledger: {}", incident_ledger_path(policy_path).display());
    }
    Ok(summary)
}

pub(crate) fn create_github_private_remote(
    repo: &Path,
    account: &str,
    private: bool,
) -> Option<String> {
    let repo_name = repo.file_name()?.to_str()?.to_string();

    // FIRST REPO CREATE ATTEMPT:
    // Try to create a private GitHub repo matching the local directory name.
    // If it already exists, we reuse it below β€” we NEVER append a suffix.
    //   ⚠️  HISTORY: A previous version had a loop that appended -1, -2, -N to
    //   repo names when the base name was taken. This created 15+ orphan repos
    //   (dracon-demons-1..-9, browser-extensions-shared-1..-6).
    //   The suffix approach is DANGEROUS because:
    //   1. Every daemon cycle creates a new orphan repo
    //   2. GitHub counts orphan repos against quotas
    //   3. No cleanup mechanism existed
    //   NEVER reintroduce a suffix loop here or in any repo creation function.
    let mut cmd = gh_cmd();
    cmd.args(["repo", "create", &repo_name]);
    if private {
        cmd.arg("--private");
    } else {
        cmd.arg("--public");
    }
    let output = cmd.current_dir(repo).output().ok()?;

    if output.status.success() {
        let remote_url = format!("https://github.com/{}/{}.git", account, repo_name);

        let add_result = crate::git::git_cmd()
            .args(["remote", "add", "origin", &remote_url])
            .current_dir(repo)
            .output();

        if let Err(e) = add_result {
            eprintln!("⚠️ failed to add origin for {}: {}", repo.display(), e);
        }

        let mut current_branch =
            crate::git::current_branch(repo).unwrap_or_else(|| "main".to_string());

        if current_branch == "master" {
            if let Err(e) = crate::git::git_cmd()
                .args(["branch", "-m", "master", "main"])
                .current_dir(repo)
                .output()
            {
                eprintln!(
                    "⚠️ failed to rename master to main in {}: {}",
                    repo.display(),
                    e
                );
            } else {
                current_branch = "main".to_string();
            }
        }

        let push_result = crate::git::git_cmd()
            .args([
                "push",
                "-u",
                "origin",
                &format!("HEAD:refs/heads/{}", current_branch),
            ])
            .current_dir(repo)
            .output();

        if let Ok(push_output) = push_result {
            if !push_output.status.success() {
                let stderr = String::from_utf8_lossy(&push_output.stderr);
                eprintln!(
                    "⚠️ failed to push initial commit for {}: {}",
                    repo.display(),
                    stderr
                );
            }
        } else {
            eprintln!(
                "⚠️ failed to push initial commit for {}: could not execute",
                repo.display()
            );
        }

        if !crate::git::has_tracking_upstream(repo) {
            let _ = crate::git::git_cmd()
                .args(["branch", "--set-upstream-to=origin/main", &current_branch])
                .current_dir(repo)
                .output();
        }

        return Some(remote_url);
    }

    // Repo already exists β€” reuse it instead of creating a new one with a suffix
    let remote_url = format!("https://github.com/{}/{}.git", account, repo_name);

    // Check if origin already exists locally before adding
    let has_origin = crate::git::git_cmd()
        .args(["remote", "get-url", "origin"])
        .current_dir(repo)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    if !has_origin {
        let add_result = crate::git::git_cmd()
            .args(["remote", "add", "origin", &remote_url])
            .current_dir(repo)
            .output();

        if let Err(e) = add_result {
            eprintln!("⚠️ failed to add origin for {}: {}", repo.display(), e);
        }
    }

    let mut current_branch = crate::git::current_branch(repo).unwrap_or_else(|| "main".to_string());

    if current_branch == "master" {
        if let Err(e) = crate::git::git_cmd()
            .args(["branch", "-m", "master", "main"])
            .current_dir(repo)
            .output()
        {
            eprintln!(
                "⚠️ failed to rename master to main in {}: {}",
                repo.display(),
                e
            );
        } else {
            current_branch = "main".to_string();
        }
    }

    let _ = crate::git::git_cmd()
        .args([
            "push",
            "-u",
            "origin",
            &format!("HEAD:refs/heads/{}", current_branch),
        ])
        .current_dir(repo)
        .output();

    if !crate::git::has_tracking_upstream(repo) {
        let _ = crate::git::git_cmd()
            .args(["branch", "--set-upstream-to=origin/main", &current_branch])
            .current_dir(repo)
            .output();
    }

    Some(remote_url)
}

fn create_private_remote(repo: &Path) -> Option<String> {
    // NEVER overwrite an existing origin. Only create a local bare repo
    // for repos that genuinely have no remote configured.
    if has_origin_remote(repo) {
        eprintln!(
            "⚠️ refusing to create private remote for {} β€” origin already exists",
            repo.display()
        );
        return None;
    }

    let repo_name = repo.file_name()?.to_str()?.to_string();
    let private_remotes_dir = dirs::data_dir()
        .unwrap_or_else(|| dirs::home_dir().unwrap_or_else(|| PathBuf::from(".")))
        .join("dracon/private-remotes");

    if !private_remotes_dir.exists() {
        std::fs::create_dir_all(&private_remotes_dir).ok()?;
    }

    let bare_repo_path = private_remotes_dir.join(format!("{}.git", repo_name));
    let mut final_path = bare_repo_path.clone();
    let mut counter = 1;
    while final_path.exists() {
        final_path = private_remotes_dir.join(format!("{}-{}.git", repo_name, counter));
        counter += 1;
    }

    let bare_name = final_path.file_name()?.to_str()?;

    let output = crate::git::git_cmd()
        .args(["init", "--bare", bare_name])
        .current_dir(&private_remotes_dir)
        .output()
        .ok()?;

    if !output.status.success() {
        std::fs::create_dir_all(&final_path).ok()?;
        let output = crate::git::git_cmd()
            .args(["init", "--bare"])
            .current_dir(&final_path)
            .output()
            .ok()?;
        if !output.status.success() {
            return None;
        }
    }

    let remote_url = format!("file://{}", final_path.display());

    let add_result = crate::git::git_cmd()
        .args(["remote", "add", "origin", &remote_url])
        .current_dir(repo)
        .output();

    if let Err(e) = add_result {
        eprintln!("⚠️ failed to add origin for {}: {}", repo.display(), e);
    }

    Some(remote_url)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::EnvRestorer;
    use dracon_git::types::RepoStatus;
    use std::os::unix::fs::PermissionsExt;

    fn make_status(is_clean: bool, ahead: usize, behind: usize) -> RepoStatus {
        let mut status = RepoStatus::default();
        status.branch = String::new();
        status.is_clean = is_clean;
        status.ahead = ahead;
        status.behind = behind;
        status.modified_files = if is_clean { 0 } else { 1 };
        status.untracked_files = 0;
        status.staged_files = 0;
        status.last_commit_hash = None;
        status.last_commit_msg = None;
        status
    }

    #[test]
    fn test_repo_failure_message_includes_prefix_and_error() {
        let msg = repo_failure_message("init_failed", Path::new("/tmp/repo"), "boom");
        assert!(msg.contains("init_failed"));
        assert!(msg.contains("/tmp/repo"));
        assert!(msg.contains("boom"));
    }

    #[test]
    fn test_repo_failure_message_includes_status_prefix() {
        let msg = repo_failure_message("status_failed", Path::new("/tmp/repo"), "status boom");
        assert!(msg.contains("status_failed"));
        assert!(msg.contains("status boom"));
    }

    #[test]
    fn test_parse_git_log_meta_line_preserves_subject_with_separator() {
        // Commit subject that itself contains the unit-separator character
        // must be reconstructed verbatim rather than truncated at the first
        // extra field.
        let line = "hash0\u{1f}author\u{1f}2 hours ago\u{1f}1700000000\u{1f}a\u{1f}b\u{1f}c";
        let parsed = parse_git_log_meta_line(line).expect("parse");
        assert_eq!(parsed.0, "hash0");
        assert_eq!(parsed.1, "author");
        assert_eq!(parsed.2, "2 hours ago");
        assert_eq!(parsed.3, 1_700_000_000);
        assert_eq!(parsed.4, "a\u{1f}b\u{1f}c");
    }

    #[test]
    fn test_parse_git_log_meta_line_simple_subject() {
        let line = "h\u{1f}me\u{1f}1m\u{1f}1234\u{1f}hello world";
        let parsed = parse_git_log_meta_line(line).expect("parse");
        assert_eq!(parsed.4, "hello world");
    }

    #[test]
    fn test_parse_git_log_meta_line_rejects_too_few_fields() {
        assert!(parse_git_log_meta_line("a\u{1f}b").is_none());
    }

    #[test]
    fn test_parse_git_log_meta_line_rejects_blank() {
        assert!(parse_git_log_meta_line("   ").is_none());
    }

    #[test]
    fn test_last_push_for_branch_skips_unsafe_branch_names() {
        // Branch names that would break the reflog argument or shell quoting
        // must be skipped without invoking git at all. The repo path is
        // intentionally not a real repository β€” the helper must return "-"
        // before reaching git.
        for bad in [
            "",                // detached HEAD
            "-evil",           // leading dash
            "feat with space", // contains space
            "main\nbad",       // newline injection
            "feat;rm -rf",     // shell metachar
            "main?",           // glob meta
        ] {
            assert_eq!(
                last_push_for_branch(Path::new("/nonexistent/repo"), bad),
                "-",
                "branch {bad:?} should be skipped"
            );
        }
    }

    #[test]
    fn test_last_push_for_branch_uses_log_not_reflog() {
        // Regression: a freshly-cloned repo with no further fetches has
        // an empty reflog for `origin/<branch>`. The old helper used
        // `git reflog show origin/main --format=%cr -1`, which returned
        // empty output in that state and surfaced as a misleading "-"
        // in the PUSHED column even though the remote-tracking ref was
        // valid. The helper now uses
        // `git log -1 --format=%cr origin/main`, which returns the
        // committer date of the remote tip in both cases.
        let parent = tempfile::tempdir().unwrap();
        let bare = parent.path().join("bare.git");
        let repo = parent.path().join("repo");
        std::fs::create_dir_all(&bare).unwrap();
        std::fs::create_dir_all(&repo).unwrap();
        let run = |args: &[&str]| {
            std::process::Command::new("git")
                .args(args)
                .current_dir(&repo)
                .output()
                .unwrap()
        };
        let run_bare = |args: &[&str]| {
            std::process::Command::new("git")
                .args(args)
                .current_dir(&bare)
                .output()
                .unwrap()
        };
        // Seed an initial commit in the bare repo via a working tree.
        run_bare(&["init", "--bare", "--initial-branch=main"]);
        let seed = parent.path().join("seed");
        std::fs::create_dir_all(&seed).unwrap();
        let run_seed = |args: &[&str]| {
            std::process::Command::new("git")
                .args(args)
                .current_dir(&seed)
                .output()
                .unwrap()
        };
        run_seed(&["init", "-b", "main"]);
        run_seed(&["config", "user.email", "ops@dracon.uk"]);
        run_seed(&["config", "user.name", "DraconDev"]);
        run_seed(&["config", "commit.gpgsign", "false"]);
        run_seed(&["config", "core.hooksPath", "/dev/null"]);
        std::fs::write(seed.join("README.md"), "seed\n").unwrap();
        run_seed(&["add", "README.md"]);
        run_seed(&["commit", "--no-verify", "-m", "seed"]);
        run_seed(&["remote", "add", "origin", bare.to_str().unwrap()]);
        let push_seed = run_seed(&["push", "origin", "main"]);
        assert!(
            push_seed.status.success(),
            "seed push failed: stdout={} stderr={}",
            String::from_utf8_lossy(&push_seed.stdout),
            String::from_utf8_lossy(&push_seed.stderr),
        );
        // Clone the bare repo so the local reflog for origin/main starts
        // empty (no subsequent fetches, no pushes).
        let clone = std::process::Command::new("git")
            .args(["clone", bare.to_str().unwrap(), repo.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(
            clone.status.success(),
            "clone failed: stdout={} stderr={}",
            String::from_utf8_lossy(&clone.stdout),
            String::from_utf8_lossy(&clone.stderr),
        );
        run(&["config", "user.email", "ops@dracon.uk"]);
        run(&["config", "user.name", "DraconDev"]);
        // Sanity: `git reflog show origin/main` is empty for a freshly-
        // cloned repo with no subsequent fetches, so the old helper
        // would have returned "-" here.
        let reflog_out = run(&["reflog", "show", "origin/main", "--format=%cr", "-1"]);
        let reflog_str = String::from_utf8_lossy(&reflog_out.stdout);
        assert!(
            reflog_str.trim().is_empty(),
            "test setup precondition: reflog must be empty in this scenario, got {:?}",
            reflog_str,
        );
        // `git log -1 --format=%cr origin/main` must return a real
        // date (this is what the helper now uses).
        let log_out = run(&["log", "-1", "--format=%cr", "origin/main"]);
        let log_str = String::from_utf8_lossy(&log_out.stdout);
        assert!(
            !log_str.trim().is_empty(),
            "test setup precondition: `git log` must return a real date for origin/main, got {:?}",
            log_str,
        );
        let pushed = last_push_for_branch(&repo, "main");
        assert_ne!(
            pushed, "-",
            "last_push_for_branch must not return '-' for a valid remote-tracking ref even when the reflog is empty (got {:?})",
            pushed
        );
    }

    #[test]
    fn test_truncate_exact_length() {
        assert_eq!(truncate("hello", 5), "hello");
    }

    #[test]
    fn test_truncate_shorter() {
        assert_eq!(truncate("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_longer() {
        assert_eq!(truncate("hello world", 5), "hell…");
    }

    #[test]
    fn test_truncate_empty() {
        assert_eq!(truncate("", 5), "");
    }

    #[test]
    fn test_truncate_unicode_truncation() {
        let s = "hello δΈ–η•Œ test";
        let result = truncate(s, 10);
        assert!(result.ends_with('…'));
    }

    #[test]
    fn test_sync_alert_ledger_path_uses_state_dir() {
        let _guard = EnvRestorer::new("DRACON_SYNC_STATE_DIR", "/tmp/dracon-sync-test-state");
        let path = sync_alert_ledger_path();
        assert_eq!(
            path,
            PathBuf::from("/tmp/dracon-sync-test-state/dracon-sync-alerts.jsonl")
        );
    }

    #[test]
    fn test_record_sync_alert_appends_jsonl() {
        let tmp = tempfile::tempdir().unwrap();
        let _guard = EnvRestorer::new(
            "DRACON_SYNC_STATE_DIR",
            tmp.path().to_string_lossy().as_ref(),
        );
        let repo = tmp.path().join("repo");
        record_sync_alert(&repo, "Stuck on Push", "ahead=3, clean");
        let ledger = tmp.path().join("dracon-sync-alerts.jsonl");
        let content = std::fs::read_to_string(ledger).unwrap();
        assert!(content.contains("\"reason\":\"Stuck on Push\""));
        assert!(content.contains("\"details\":\"ahead=3, clean\""));
        assert!(content.contains("\"repo\":\""));
        assert!(content.contains("repo\""));
    }

    #[test]
    fn test_repo_state_flags_ok() {
        let status = make_status(true, 0, 0);
        let flags = repo_state_flags(&status, true, true);
        assert!(flags.contains(&"OK".to_string()));
    }

    #[test]
    fn test_repo_state_flags_dirty() {
        let mut status = make_status(false, 0, 0);
        status.modified_files = 2;
        let flags = repo_state_flags(&status, true, true);
        assert!(flags.contains(&"DIRTY".to_string()));
    }

    #[test]
    fn test_repo_state_flags_ahead() {
        let status = make_status(true, 3, 0);
        let flags = repo_state_flags(&status, true, true);
        assert!(flags.iter().any(|f| f.starts_with("AHEAD:")));
    }

    #[test]
    fn test_repo_state_flags_behind() {
        let status = make_status(true, 0, 2);
        let flags = repo_state_flags(&status, true, true);
        assert!(flags.iter().any(|f| f.starts_with("BEHIND:")));
    }

    #[test]
    fn test_repo_state_flags_no_origin() {
        let status = make_status(true, 0, 0);
        let flags = repo_state_flags(&status, false, false);
        assert!(flags.contains(&"NO_ORIGIN".to_string()));
    }

    #[test]
    fn test_repo_state_flags_no_upstream() {
        let status = make_status(true, 0, 0);
        let flags = repo_state_flags(&status, true, false);
        assert!(flags.contains(&"NO_UPSTREAM".to_string()));
    }

    #[test]
    fn test_repo_state_flags_stuck_push() {
        let status = make_status(false, 5, 0);
        // STUCK_PUSH now requires an explicit recent push failure signal.
        // Without it, an AHEAD repo is just "has unpushed commits".
        let flags = repo_state_flags_with_push_failure(&status, true, true, true);
        assert!(flags.contains(&"STUCK_PUSH".to_string()));
        let flags_no_failure = repo_state_flags(&status, true, true);
        assert!(!flags_no_failure.contains(&"STUCK_PUSH".to_string()));
        assert!(flags_no_failure.contains(&"AHEAD:5".to_string()));
    }

    #[test]
    fn test_repo_state_flags_stuck_pull() {
        let status = make_status(false, 0, 3);
        let flags = repo_state_flags(&status, true, true);
        assert!(flags.contains(&"STUCK_PULL".to_string()));
    }

    #[test]
    fn test_repo_state_flags_multiple() {
        let status = make_status(false, 3, 2);
        let flags = repo_state_flags(&status, true, true);
        assert!(flags.contains(&"DIRTY".to_string()));
        assert!(flags.iter().any(|f| f.starts_with("AHEAD:")));
        assert!(flags.iter().any(|f| f.starts_with("BEHIND:")));
    }

    #[test]
    fn test_repo_is_concern_no_origin() {
        let status = make_status(true, 0, 0);
        assert!(repo_is_concern(&status, false, false));
    }

    #[test]
    fn test_repo_is_concern_no_upstream() {
        let status = make_status(true, 0, 0);
        assert!(repo_is_concern(&status, true, false));
    }

    #[test]
    fn test_repo_is_concern_ahead() {
        // Old behavior: any ahead was a concern. The new
        // repo_is_concern_with_push_failure requires a recent push
        // failure signal; without it, ahead is just "has unpushed
        // commits" and is a WARN, not a CONCERN.
        let status = make_status(false, 5, 0);
        assert!(repo_is_concern_with_push_failure(&status, true, true, true));
        assert!(!repo_is_concern_with_push_failure(
            &status, true, true, false
        ));
    }

    #[test]
    fn test_repo_is_concern_behind() {
        let status = make_status(false, 0, 3);
        assert!(repo_is_concern_with_push_failure(
            &status, true, true, false
        ));
    }

    #[test]
    fn test_repo_stuck_filters_require_same_signals_as_repos() {
        let ahead = make_status(false, 5, 0);
        let behind = make_status(false, 0, 3);
        assert!(!repo_is_stuck_push(&ahead, true, true, false));
        assert!(repo_is_stuck_push(&ahead, true, true, true));
        assert!(!repo_is_stuck_push(&ahead, false, true, true));
        assert!(!repo_is_stuck_push(&ahead, true, false, true));
        assert!(repo_is_stuck_pull(&behind, true, true));
        assert!(!repo_is_stuck_pull(&behind, false, true));
        assert!(!repo_is_stuck_pull(&behind, true, false));
    }

    #[test]
    fn test_repo_is_concern_clean_healthy() {
        let status = make_status(true, 0, 0);
        assert!(!repo_is_concern_with_push_failure(
            &status, true, true, false
        ));
    }

    #[test]
    fn test_repo_is_warn_dirty() {
        let status = make_status(false, 0, 0);
        assert!(repo_is_warn(&status, true, true));
    }

    #[test]
    fn test_repo_is_warn_not_concern() {
        let status = make_status(false, 0, 0);
        assert!(!repo_is_warn(&status, false, false));
    }

    #[test]
    fn test_repo_hint_no_origin() {
        let hint = repo_hint(&["NO_ORIGIN".into()], false, false);
        assert_eq!(hint, "set origin remote");
    }

    #[test]
    fn test_repo_hint_no_upstream() {
        let hint = repo_hint(&["NO_UPSTREAM".into()], false, false);
        assert_eq!(hint, "run repair-concerns --apply (set upstream)");
    }

    #[test]
    fn test_repo_hint_intentional_no_upstream() {
        // INTENTIONAL_NO_UPSTREAM must take precedence over NO_UPSTREAM
        // so the operator never sees a misleading "set upstream" hint
        // for a repo they have explicitly flagged as intentionally
        // isolated.
        let hint = repo_hint(&["INTENTIONAL_NO_UPSTREAM".into()], false, false);
        assert_eq!(hint, "intentional legacy isolation, no upstream configured");
    }

    #[test]
    fn test_apply_intentional_no_upstream_replaces_flag() {
        // NO_UPSTREAM must be replaced (not duplicated) by
        // INTENTIONAL_NO_UPSTREAM, and other flags must be preserved.
        let flags = vec!["DIRTY".to_string(), "NO_UPSTREAM".to_string()];
        let result = apply_intentional_no_upstream(flags);
        assert!(!result.contains(&"NO_UPSTREAM".to_string()));
        assert!(result.contains(&"INTENTIONAL_NO_UPSTREAM".to_string()));
        assert!(result.contains(&"DIRTY".to_string()));
    }

    #[test]
    fn test_apply_intentional_no_upstream_idempotent() {
        // Calling the helper twice on a row that already has
        // INTENTIONAL_NO_UPSTREAM must not duplicate the flag.
        let once = apply_intentional_no_upstream(vec!["NO_UPSTREAM".into()]);
        let twice = apply_intentional_no_upstream(once.clone());
        assert_eq!(
            twice
                .iter()
                .filter(|f| *f == "INTENTIONAL_NO_UPSTREAM")
                .count(),
            1
        );
    }

    #[test]
    fn test_apply_intentional_no_upstream_no_op_when_absent() {
        // Repos without NO_UPSTREAM should not be touched.
        let flags = vec!["OK".to_string()];
        let result = apply_intentional_no_upstream(flags.clone());
        assert_eq!(result, flags);
    }

    #[test]
    fn test_repo_hint_ahead_concern() {
        let hint = repo_hint(&["AHEAD:3".into()], false, false);
        assert_eq!(hint, "run repair-concerns --apply (push or rewrite)");
    }

    #[test]
    fn test_repo_hint_warn_with_pending_push() {
        let hint = repo_hint(&["DIRTY".into(), "AHEAD:3".into()], true, false);
        assert_eq!(hint, "daemon will push after changes settle");
    }

    #[test]
    fn test_repo_hint_behind() {
        let hint = repo_hint(&["BEHIND:2".into()], false, false);
        assert_eq!(hint, "run repair-concerns --apply (pull/merge)");
    }

    // -------------------------------------------------------------------
    // parse_relative_minutes tests
    // -------------------------------------------------------------------

    #[test]
    fn test_parse_relative_minutes_units() {
        assert_eq!(parse_relative_minutes("0 seconds ago"), Some(0));
        assert_eq!(parse_relative_minutes("23 seconds ago"), Some(0));
        assert_eq!(parse_relative_minutes("5 minutes ago"), Some(5));
        assert_eq!(parse_relative_minutes("1 minute ago"), Some(1));
        assert_eq!(parse_relative_minutes("2 hours ago"), Some(120));
        assert_eq!(parse_relative_minutes("8 hours ago"), Some(480));
        assert_eq!(parse_relative_minutes("2 days ago"), Some(2 * 24 * 60));
        assert_eq!(parse_relative_minutes("3 weeks ago"), Some(3 * 7 * 24 * 60));
        assert_eq!(parse_relative_minutes("1 month ago"), Some(30 * 24 * 60));
        assert_eq!(parse_relative_minutes("1 year ago"), Some(365 * 24 * 60));
    }

    #[test]
    fn test_parse_relative_minutes_sentinel() {
        // The daemon emits "-" as a sentinel when no time is available.
        // The parser must return None, not 0, so the classifier treats
        // it as "unknown" rather than "0 minutes ago".
        assert_eq!(parse_relative_minutes("-"), None);
        assert_eq!(parse_relative_minutes(""), None);
        assert_eq!(parse_relative_minutes("unknown"), None);
    }

    // -------------------------------------------------------------------
    // classify_state_cause tests
    // -------------------------------------------------------------------

    fn default_thresholds() -> StateCauseThresholds {
        StateCauseThresholds {
            active_minutes: 5,
            committing_minutes: 60,
            cold_minutes: 1440,
        }
    }

    fn empty_flags() -> Vec<String> {
        vec!["OK".to_string()]
    }

    #[test]
    fn test_classify_state_cause_working_is_freshly_synced() {
        let inputs = StateCauseInputs {
            flags: &empty_flags(),
            push_status: "OK",
            modified: 0,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(2),
            last_push_minutes: Some(2),
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Working
        );
    }

    #[test]
    fn test_classify_state_cause_synced_clean_recent_but_not_working() {
        let inputs = StateCauseInputs {
            flags: &empty_flags(),
            push_status: "OK",
            modified: 0,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(13),
            last_push_minutes: Some(13),
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Synced
        );
    }

    #[test]
    fn test_classify_state_cause_pushing_takes_precedence() {
        let pushing_flags: Vec<String> = vec!["DIRTY".to_string(), "AHEAD:3".to_string()];
        let inputs = StateCauseInputs {
            flags: &pushing_flags,
            push_status: "PENDING",
            modified: 5,
            staged: 0,
            untracked: 0,
            ahead: 3,
            behind: 0,
            last_commit_minutes: Some(2),
            last_push_minutes: Some(8),
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Pushing
        );
    }

    #[test]
    fn test_classify_state_cause_stalled_is_the_users_pain() {
        let dirty_flags: Vec<String> = vec!["DIRTY".to_string()];
        let inputs = StateCauseInputs {
            flags: &dirty_flags,
            push_status: "OK",
            modified: 3,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(90),
            last_push_minutes: Some(90),
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Stalled
        );
    }

    #[test]
    fn test_classify_state_cause_recent_dirty_is_dirty_not_stalled() {
        let dirty_flags: Vec<String> = vec!["DIRTY".to_string()];
        let inputs = StateCauseInputs {
            flags: &dirty_flags,
            push_status: "OK",
            modified: 4,
            staged: 0,
            untracked: 1,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(2),
            last_push_minutes: Some(2),
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Dirty
        );
    }

    #[test]
    fn test_classify_state_cause_dirty_within_committing_window_is_dirty() {
        let dirty_flags: Vec<String> = vec!["DIRTY".to_string()];
        let inputs = StateCauseInputs {
            flags: &dirty_flags,
            push_status: "OK",
            modified: 3,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(30),
            last_push_minutes: Some(45),
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Dirty
        );
    }

    #[test]
    fn test_classify_state_cause_old_dirty_is_stalled() {
        let dirty_flags: Vec<String> = vec!["DIRTY".to_string()];
        let inputs = StateCauseInputs {
            flags: &dirty_flags,
            push_status: "OK",
            modified: 3,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(90),
            last_push_minutes: Some(90),
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Stalled
        );
    }

    #[test]
    fn test_classify_state_cause_intentional_flag() {
        let intentional_flags: Vec<String> = vec!["INTENTIONAL_NO_UPSTREAM".to_string()];
        let inputs = StateCauseInputs {
            flags: &intentional_flags,
            push_status: "INTENTIONAL",
            modified: 0,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(60 * 8),
            last_push_minutes: None,
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Intentional
        );
    }

    #[test]
    fn test_classify_state_cause_failed_takes_precedence() {
        let upstream_flags: Vec<String> = vec!["NO_UPSTREAM".to_string()];
        let inputs = StateCauseInputs {
            flags: &upstream_flags,
            push_status: "FAIL",
            modified: 0,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(60),
            last_push_minutes: None,
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Failed
        );
    }

    #[test]
    fn test_classify_state_cause_idle_within_cold_window() {
        let inputs = StateCauseInputs {
            flags: &empty_flags(),
            push_status: "OK",
            modified: 0,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(4 * 60),
            last_push_minutes: Some(4 * 60),
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Idle
        );
    }

    #[test]
    fn test_classify_state_cause_cold_beyond_threshold() {
        let inputs = StateCauseInputs {
            flags: &empty_flags(),
            push_status: "OK",
            modified: 0,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(2 * 24 * 60),
            last_push_minutes: Some(2 * 24 * 60),
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Cold
        );
    }

    #[test]
    fn test_classify_state_cause_untracked_only() {
        let dirty_flags: Vec<String> = vec!["DIRTY".to_string()];
        let inputs = StateCauseInputs {
            flags: &dirty_flags,
            push_status: "OK",
            modified: 0,
            staged: 0,
            untracked: 5,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(60),
            last_push_minutes: Some(60),
        };
        assert_eq!(
            classify_state_cause(&inputs, &default_thresholds()),
            StateCause::Untracked
        );
    }

    #[test]
    fn test_classify_state_cause_uses_per_repo_overrides() {
        let over = RepoPolicyOverride {
            active_commit_minutes: Some(30),
            ..Default::default()
        };
        let policy = test_sync_policy();
        let thresholds = StateCauseThresholds::from_policy(&policy, &over);
        assert_eq!(thresholds.active_minutes, 30);
        let inputs = StateCauseInputs {
            flags: &empty_flags(),
            push_status: "OK",
            modified: 0,
            staged: 0,
            untracked: 0,
            ahead: 1,
            behind: 0,
            last_commit_minutes: Some(20),
            last_push_minutes: Some(20),
        };
        assert_eq!(
            classify_state_cause(&inputs, &thresholds),
            StateCause::Committing
        );
    }

    #[test]
    fn test_classify_state_cause_uses_global_when_no_override() {
        let over = RepoPolicyOverride::default();
        let policy = test_sync_policy();
        let thresholds = StateCauseThresholds::from_policy(&policy, &over);
        assert_eq!(thresholds.active_minutes, 5);
        let inputs = StateCauseInputs {
            flags: &empty_flags(),
            push_status: "OK",
            modified: 0,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_commit_minutes: Some(20),
            last_push_minutes: Some(20),
        };
        assert_eq!(
            classify_state_cause(&inputs, &thresholds),
            StateCause::Synced
        );
    }






    #[test]
    fn test_repo_is_warn_untracked_only_is_not_warn() {
        let mut status = RepoStatus::default();
        status.branch = String::new();
        status.is_clean = false;
        status.modified_files = 0;
        status.untracked_files = 5;
        status.staged_files = 0;
        status.ahead = 0;
        status.behind = 0;
        status.last_commit_hash = None;
        status.last_commit_msg = None;

        assert!(!repo_is_warn(&status, true, true));
        assert_eq!(repo_state_flags(&status, true, true), vec!["DIRTY"]);
    }

    #[test]
    fn test_repo_hint_healthy() {
        let hint = repo_hint(&["OK".into()], false, false);
        assert_eq!(hint, "healthy");
    }

    #[test]
    fn test_repo_hint_warn() {
        let hint = repo_hint(&["DIRTY".into()], true, false);
        assert_eq!(
            hint,
            "daemon handles after changes settle; run sync-now --warns to force now"
        );
    }

    #[test]
    fn test_repo_hint_concern() {
        let hint = repo_hint(&["DIRTY".into()], false, true);
        assert_eq!(hint, "run repair-concerns --apply");
    }

    #[test]
    fn test_push_large_blob_threshold_bytes() {
        let policy = SyncPolicy {
            max_stage_file_bytes: 200 * 1024 * 1024,
            max_push_blob_bytes: 50 * 1024 * 1024,
            ..test_sync_policy()
        };
        let threshold = push_large_blob_threshold_bytes(&policy);
        assert_eq!(threshold, 50 * 1024 * 1024);
    }

    #[test]
    fn test_push_large_blob_threshold_caps_at_git_limit() {
        let policy = SyncPolicy {
            max_stage_file_bytes: 200 * 1024 * 1024,
            max_push_blob_bytes: 200 * 1024 * 1024,
            ..test_sync_policy()
        };
        let threshold = push_large_blob_threshold_bytes(&policy);
        assert_eq!(threshold, DEFAULT_GIT_HOST_BLOB_LIMIT_BYTES);
    }

    #[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);
    }

    static LEDGER_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 {
            let lock = LEDGER_ENV_GUARD.lock().unwrap();
            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_incident_ledger_path_default() {
        let _guard = VarGuard::set_temp("DRACON_SYNC_LEDGER", "");
        let path = incident_ledger_path(std::path::Path::new("/fake/policy.toml"));
        assert!(path
            .to_string_lossy()
            .contains("dracon-sync-incidents.jsonl"));
    }

    #[test]
    fn test_incident_ledger_path_custom_env() {
        let _guard = VarGuard::set_temp("DRACON_SYNC_LEDGER", "/custom/path/ledger.jsonl");
        let path = incident_ledger_path(std::path::Path::new("/fake/policy.toml"));
        let result = path.to_string_lossy();
        assert_eq!(result, "/custom/path/ledger.jsonl");
    }

    fn test_sync_policy() -> SyncPolicy {
        SyncPolicy {
            system_repo: String::new(),
            pulse_interval_secs: 1,
            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,
            auto_repair_warns: true,
            auto_rewrite_large_blobs: true,
            sem_max_concurrent_sync: 4,
            auto_stage_untracked: true,
            untracked_exclude_patterns: crate::policy::default_untracked_exclude_patterns(),
            watch_roots: vec![],
            remotes: vec![],
            auto_github_private: false,
            auto_github_private_account: "DraconDev".to_string(),
            max_stage_file_bytes: 100 * 1024 * 1024,
            pull_op_timeout_secs: 30,
            push_op_timeout_secs: 300,
            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,
            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: crate::policy::default_trusted_emails(),
            trusted_authors: crate::policy::default_trusted_authors(),
            trusted_remote_hosts: crate::policy::default_trusted_remote_hosts(),
            settling_max_delay_secs: 60,
            dirty_max_age_action: crate::policy::DirtyMaxAgeAction::Commit,
            min_commit_interval_secs: 5,
            auto_commit_exclude_patterns: vec![],
            sync_visibility: false,
            sync_visibility_interval_hours: 24,
            sync_metadata: false,
            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,
        }
    }

    #[test]
    fn test_truncate_unicode_emoji() {
        let result = truncate("hello πŸ‘‹ world", 10);
        assert!(result.ends_with('…'));
    }

    #[test]
    fn test_repair_summary_default() {
        let summary = RepairSummary::default();
        assert_eq!(summary.found, 0);
        assert_eq!(summary.planned, 0);
        assert_eq!(summary.attempted, 0);
        assert_eq!(summary.succeeded, 0);
        assert_eq!(summary.resolved_now, 0);
        assert_eq!(summary.manual_only, 0);
    }

    #[test]
    fn test_repair_summary_debug() {
        let summary = RepairSummary {
            found: 1,
            planned: 2,
            attempted: 3,
            succeeded: 4,
            resolved_now: 5,
            manual_only: 6,
        };
        let debug = format!("{:?}", summary);
        assert!(debug.contains("found"));
    }

    #[test]
    fn test_ansi_colors() {
        // Force color on for this test (NO_COLOR may be set in the env).
        let saved = std::env::var_os("NO_COLOR");
        // SAFETY: this is a single-threaded test that owns the NO_COLOR slot.
        unsafe {
            std::env::remove_var("NO_COLOR");
        }
        let saved_force = std::env::var_os("DRACON_FORCE_COLOR");
        std::env::set_var("DRACON_FORCE_COLOR", "1");
        assert_eq!(ansi("31", "error"), "\x1b[31merror\x1b[0m");
        assert_eq!(ansi("32", "ok"), "\x1b[32mok\x1b[0m");
        assert_eq!(ansi("1", "bold"), "\x1b[1mbold\x1b[0m");
        assert_eq!(ansi("unknown", "default"), "\x1b[0mdefault\x1b[0m");
        // restore
        match saved {
            Some(v) => std::env::set_var("NO_COLOR", v),
            None => std::env::remove_var("NO_COLOR"),
        }
        match saved_force {
            Some(v) => std::env::set_var("DRACON_FORCE_COLOR", v),
            None => std::env::remove_var("DRACON_FORCE_COLOR"),
        }
    }

    #[test]
    fn test_repo_filter_variants() {
        assert_eq!(format!("{:?}", RepoFilter::All), "All");
        assert_eq!(format!("{:?}", RepoFilter::Concern), "Concern");
        assert_eq!(format!("{:?}", RepoFilter::Warn), "Warn");
    }

    #[test]
    fn test_concern_repair_filter_variants() {
        assert_eq!(format!("{:?}", ConcernRepairFilter::All), "All");
        assert_eq!(format!("{:?}", ConcernRepairFilter::StuckPush), "StuckPush");
        assert_eq!(format!("{:?}", ConcernRepairFilter::StuckPull), "StuckPull");
    }

    #[test]
    fn test_incident_record_serialization() {
        let record = IncidentRecord {
            ts_unix: 1700000000,
            scope: "test".to_string(),
            repo: "/test/repo".to_string(),
            reason: "test reason".to_string(),
            action: "test action".to_string(),
            backup_branch: Some("backup".to_string()),
            result: "success".to_string(),
            details: Some("details".to_string()),
        };
        let json = serde_json::to_string(&record).unwrap();
        assert!(json.contains("1700000000"));
        assert!(json.contains("test reason"));
    }

    #[test]
    fn test_repo_report_row_structure() {
        let row = RepoReportRow {
            repo: "/test/repo".to_string(),
            state_flags: vec!["OK".to_string()],
            branch: "main".to_string(),
            modified: 0,
            staged: 0,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_hash: "abc123".to_string(),
            last_author: "test".to_string(),
            last_when: "2024-01-01".to_string(),
            last_msg: "test commit".to_string(),
            last_unix: 1700000000,
            last_push: "5m ago".to_string(),
            push_status: "OK".to_string(),
            push_error: String::new(),
            concern: false,
            warn: false,
            hint: "healthy".to_string(),
            state_cause: StateCause::Healthy,
            state_cause_label: "healthy".to_string(),
            daemon_last_action_unix: 0,
            daemon_last_action: String::new(),
            daemon_last_result: String::new(),
            daemon_last_action_when: "none".to_string(),
        };
        assert_eq!(row.repo, "/test/repo");
        assert_eq!(row.branch, "main");
        assert!(!row.concern);
    }

    /// Build a minimal RepoReportRow for activity_label testing.
    /// The `last_when` string is the natural-language relative time
    /// (e.g. "5 minutes ago") that the daemon emits from `git log`.
    fn make_activity_row(
        last_when: &str,
        modified: usize,
        staged: usize,
        push_status: &str,
    ) -> RepoReportRow {
        make_activity_row_with_state(
            last_when,
            modified,
            staged,
            push_status,
            StateCause::Healthy,
        )
    }

    fn make_activity_row_with_state(
        last_when: &str,
        modified: usize,
        staged: usize,
        push_status: &str,
        state_cause: StateCause,
    ) -> RepoReportRow {
        let label = state_cause.as_str().to_string();
        RepoReportRow {
            repo: "/tmp/test-activity-repo".to_string(),
            state_flags: vec![],
            branch: "main".to_string(),
            modified,
            staged,
            untracked: 0,
            ahead: 0,
            behind: 0,
            last_hash: "abc".to_string(),
            last_author: "test".to_string(),
            last_when: last_when.to_string(),
            last_msg: "test".to_string(),
            last_unix: 0,
            last_push: "5m ago".to_string(),
            push_status: push_status.to_string(),
            push_error: String::new(),
            concern: false,
            warn: false,
            hint: "test".to_string(),
            state_cause,
            state_cause_label: label,
            daemon_last_action_unix: 0,
            daemon_last_action: String::new(),
            daemon_last_result: String::new(),
            daemon_last_action_when: "none".to_string(),
        }
    }

    #[test]
    fn test_activity_label_push_pending() {
        // Push PENDING with 1-minute-old last commit β†’ "pushing 1m".
        let row = make_activity_row("1 minutes ago", 0, 0, "PENDING");
        let label = activity_label(&row);
        assert!(
            label.contains("pushing"),
            "expected 'pushing' in label, got: {}",
            label
        );
    }

    #[test]
    fn test_activity_label_push_pending_includes_ahead_count() {
        // Push PENDING with ahead=28 β†’ "pushing Xm (28 ahead)" so the
        // operator can tell at a glance that this stall is caused by
        // a large backlog, not a transient network blip.
        let mut row = make_activity_row("4 minutes ago", 0, 0, "PENDING");
        row.ahead = 28;
        let label = activity_label(&row);
        assert!(
            label.contains("pushing") && label.contains("28 ahead"),
            "expected 'pushing' and '28 ahead' in label, got: {}",
            label
        );
    }

    #[test]
    fn test_activity_label_dirty_recent_commit_settling() {
        // Dirty + recent commit (within settle threshold) β†’ "settling".
        // Note: when in_flight is empty, settling still applies.
        // The settle threshold is 1 minute, so 0 minutes ago is settling.
        let row = make_activity_row("0 minutes ago", 2, 0, "OK");
        let label = activity_label(&row);
        // Either "settling" or "stalled" is acceptable when last_when
        // is 0 minutes; the test just ensures the function returns
        // one of the activity states, not a bare timestamp.
        assert!(
            label.contains("settling") || label.contains("stalled"),
            "expected 'settling' or 'stalled', got: {}",
            label
        );
        // Critically, the label must NOT be a bare timestamp like "0m".
        assert!(
            !label.trim().ends_with("0m") || label.contains("stalled"),
            "label should not be a bare timestamp: {}",
            label
        );
    }

    #[test]
    fn test_activity_label_dirty_old_commit_stalled() {
        // Dirty + old commit (8 minutes ago) + no in-flight β†’ "stalled".
        let row = make_activity_row("8 minutes ago", 1, 0, "OK");
        let label = activity_label(&row);
        assert!(
            label.contains("stalled"),
            "expected 'stalled' in label, got: {}",
            label
        );
    }

    #[test]
    fn test_activity_label_clean_recent_synced() {
        // Clean + 30-minute-old commit β†’ "synced 30m".
        let row = make_activity_row("30 minutes ago", 0, 0, "OK");
        let label = activity_label(&row);
        assert!(
            label.contains("synced"),
            "expected 'synced' in label, got: {}",
            label
        );
    }

    #[test]
    fn test_activity_label_clean_idle() {
        // Clean + 2-hour-old commit β†’ "idle 2h".
        let row = make_activity_row("2 hours ago", 0, 0, "OK");
        let label = activity_label(&row);
        assert!(
            label.contains("idle"),
            "expected 'idle' in label, got: {}",
            label
        );
    }

    #[test]
    fn test_activity_label_clean_cold() {
        // Clean + 2-day-old commit β†’ "cold 2d".
        let row = make_activity_row("2 days ago", 0, 0, "OK");
        let label = activity_label(&row);
        assert!(
            label.contains("cold"),
            "expected 'cold' in label, got: {}",
            label
        );
    }

    #[test]
    fn test_activity_label_unparseable_time() {
        // Unparseable last_when β†’ "β€”".
        let row = make_activity_row("never", 0, 0, "OK");
        let label = activity_label(&row);
        assert!(label.contains("β€”"), "expected 'β€”' in label, got: {}", label);
    }

    #[test]
    fn test_activity_label_push_stuck_state() {
        // When `push_status == "PUSH_STUCK"` (the retry budget
        // is exhausted), the activity label must show
        // `πŸ›‘ push-stuck Xm (N ahead)` regardless of in_flight
        // state. This is a higher-priority indicator than the
        // generic `pushing Xm` because the daemon has given up
        // auto-pushing β€” the operator needs to intervene.
        let mut row = make_activity_row_with_state(
            "10 minutes ago",
            0,
            0,
            "PUSH_STUCK",
            StateCause::Pushing,
        );
        row.ahead = 1;
        let label = activity_label(&row);
        assert!(
            label.contains("πŸ›‘ push-stuck"),
            "PUSH_STUCK row should show 'πŸ›‘ push-stuck' indicator: got {}",
            label
        );
        assert!(
            label.contains("10m"),
            "should include the duration: got {}",
            label
        );
        assert!(
            label.contains("1 ahead"),
            "should include the ahead count: got {}",
            label
        );
    }

    // ============================================================
    // in_flight staleness filter
    // ============================================================

    #[test]
    fn test_load_in_flight_for_path_stale_file_treated_as_empty() {
        // When the on-disk in_flight file is older than the
        // staleness threshold (30s), `load_in_flight_for_path`
        // should return false even if the path is in the file.
        // This prevents the "πŸ”„ now" indicator from sticking
        // around when a slow push from the previous cycle kept
        // the repo in in_flight while the daemon has moved on.
        use std::time::SystemTime;
        // Write a file at the standard in_flight path with a
        // `written_at` timestamp from 2 minutes ago (well past
        // the 30s cutoff).
        let two_min_ago = SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs().saturating_sub(120))
            .unwrap_or(0);
        let _ = crate::daemon::save_in_flight_for_test(
            &[std::path::PathBuf::from(
                "/home/dracon/Dev/this-is-a-fake-repo-for-staleness-test",
            )],
            two_min_ago,
        );
        let result = load_in_flight_for_path("/home/dracon/Dev/this-is-a-fake-repo-for-staleness-test");
        assert!(!result, "stale in_flight file should be treated as empty");
        // Cleanup
        let _ = std::fs::remove_file(crate::daemon::in_flight_path_for_test());
    }

    #[test]
    fn test_load_in_flight_for_path_recent_file_honoured() {
        // When the on-disk in_flight file is fresh (within the
        // staleness threshold), the function should return true
        // for paths in the set.
        use std::time::SystemTime;
        let now = SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let _ = crate::daemon::save_in_flight_for_test(
            &[std::path::PathBuf::from(
                "/home/dracon/Dev/another-fake-repo-for-staleness-test",
            )],
            now,
        );
        let result = load_in_flight_for_path("/home/dracon/Dev/another-fake-repo-for-staleness-test");
        assert!(result, "fresh in_flight file should be honoured");
        let _ = std::fs::remove_file(crate::daemon::in_flight_path_for_test());
    }

    #[test]
    fn test_load_in_flight_for_path_10s_old_is_stale() {
        // The staleness threshold is 5s. A file written 10s ago
        // must be treated as stale (returns false). This is the
        // boundary case: under the 30s default this was fresh.
        use std::time::SystemTime;
        let ten_secs_ago = SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs().saturating_sub(10))
            .unwrap_or(0);
        let _ = crate::daemon::save_in_flight_for_test(
            &[std::path::PathBuf::from(
                "/home/dracon/Dev/repo-with-10s-old-inflight",
            )],
            ten_secs_ago,
        );
        let result = load_in_flight_for_path("/home/dracon/Dev/repo-with-10s-old-inflight");
        assert!(!result, "10s-old in_flight file should be stale at 5s threshold");
        let _ = std::fs::remove_file(crate::daemon::in_flight_path_for_test());
    }

    #[test]
    fn test_activity_label_suppresses_in_flight_for_clean_state() {
        // When the row's state_cause is `Synced`, `Idle`,
        // `Cold`, `Untracked`, or `Healthy`, the activity
        // label must NOT show "πŸ”„ now" even if the in_flight
        // file lists the repo path. This is the second leak
        // in the staleness filter: clean rows are never
        // legitimately in-flight, so the indicator is always
        // false-positive.
        use std::time::SystemTime;
        let now = SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let _ = crate::daemon::save_in_flight_for_test(
            &[std::path::PathBuf::from(
                "/home/dracon/Dev/repo-clean-but-listed-as-inflight",
            )],
            now,
        );
        // Build a row whose repo path matches the in_flight file
        // but whose state is one of the clean states.
        let mut row = make_activity_row_with_state(
            "5 minutes ago",
            0,
            0,
            "OK",
            StateCause::Synced,
        );
        row.repo = "/home/dracon/Dev/repo-clean-but-listed-as-inflight".to_string();
        let label = activity_label(&row);
        assert!(
            !label.contains("πŸ”„ now"),
            "Synced row should not show 'πŸ”„ now' even when in_flight file lists it: got {}",
            label
        );

        // Same for Idle
        row.state_cause = StateCause::Idle;
        row.state_cause_label = "idle".to_string();
        let label = activity_label(&row);
        assert!(
            !label.contains("πŸ”„ now"),
            "Idle row should not show 'πŸ”„ now': got {}",
            label
        );

        // Same for Cold
        row.state_cause = StateCause::Cold;
        row.state_cause_label = "cold".to_string();
        let label = activity_label(&row);
        assert!(
            !label.contains("πŸ”„ now"),
            "Cold row should not show 'πŸ”„ now': got {}",
            label
        );

        // But Dirty state SHOULD still show "πŸ”„ now"
        row.state_cause = StateCause::Dirty;
        row.state_cause_label = "dirty".to_string();
        let label = activity_label(&row);
        assert!(
            label.contains("πŸ”„ now"),
            "Dirty row SHOULD show 'πŸ”„ now' when in_flight: got {}",
            label
        );

        let _ = std::fs::remove_file(crate::daemon::in_flight_path_for_test());
    }

    #[test]
    fn test_repo_report_json_structure() {
        let json = RepoReportJson {
            policy: "default".to_string(),
            filter: "all".to_string(),
            repos: 1,
            ok: 1,
            warn: 0,
            concern: 0,
            failures: 0,
            rows: vec![],
        };
        assert_eq!(json.repos, 1);
        assert_eq!(json.ok, 1);
    }

    #[test]
    fn test_status_json_structure() {
        let status = StatusJson {
            policy: "default".to_string(),
            roots: vec!["~/code".to_string()],
            repos_discovered: 5,
            pulse_interval_secs: 30,
            inactivity_push_delay_secs: 300,
            freeze: "none".to_string(),
            auto_commit: true,
            auto_pull: true,
            auto_push: true,
            auto_bump_versions: true,
            auto_repair_concerns: true,
            auto_repair_warns: true,
            auto_rewrite_large_blobs: true,
            max_stage_file_bytes: 100 * 1024 * 1024,
            push_blob_threshold_bytes: 100 * 1024 * 1024,
            exclude_dirs: vec![],
            exclude_file_patterns: vec![],
            pull_op_timeout_secs: 30,
            push_op_timeout_secs: 300,
            repo_sync_timeout_secs: 420,
            stage_op_timeout_secs: 60,
            stage_cooldown_secs: 3600,
            push_retries: 3,
            repair_cooldown_secs: 60,
            incident_ledger_max_lines: 10000,
            incident_ledger_max_age_days: 30,
            system_repo: String::new(),
            backup_policy: String::new(),
            backup_dir: String::new(),
            remotes: 0,
            remote_configs: vec![],
        };
        assert_eq!(status.repos_discovered, 5);
        assert!(status.auto_commit);
    }

    #[test]
    fn test_push_large_blob_threshold_min_limit() {
        let policy = SyncPolicy {
            max_stage_file_bytes: 10 * 1024 * 1024,
            max_push_blob_bytes: 5 * 1024 * 1024,
            ..test_sync_policy()
        };
        let threshold = push_large_blob_threshold_bytes(&policy);
        assert_eq!(threshold, 5 * 1024 * 1024);
    }

    #[test]
    fn test_truncate_three_chars() {
        let result = truncate("hello", 3);
        assert_eq!(result, "he…");
    }

    #[test]
    fn test_truncate_exact_length_no_ellipsis() {
        let result = truncate("hello", 5);
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_truncate_empty_string() {
        let result = truncate("", 5);
        assert_eq!(result, "");
    }

    #[test]
    fn test_push_large_blob_threshold_bytes_custom() {
        let policy = SyncPolicy {
            max_push_blob_bytes: 50 * 1024 * 1024,
            ..test_sync_policy()
        };
        let threshold = push_large_blob_threshold_bytes(&policy);
        assert_eq!(threshold, 50 * 1024 * 1024);
    }

    #[test]
    fn test_push_large_blob_threshold_bytes_uses_min_of_all() {
        let policy = SyncPolicy {
            max_stage_file_bytes: 10 * 1024 * 1024,
            max_push_blob_bytes: 50 * 1024 * 1024,
            ..test_sync_policy()
        };
        let threshold = push_large_blob_threshold_bytes(&policy);
        assert_eq!(
            threshold,
            10 * 1024 * 1024,
            "should use smaller of stage and push limit"
        );
    }

    #[test]
    fn test_create_github_private_remote_success() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let repo = tmp.path().join("my-repo");
        crate::git::git_cmd()
            .args(["init", "-q", "-b", "master"])
            .arg(&repo)
            .status()
            .expect("git init");

        let gh_mock = tmp.path().join("gh");
        std::fs::write(&gh_mock, "#!/bin/sh\necho \"mock gh called\" >&2\nexit 0\n")
            .expect("write gh mock");
        std::fs::set_permissions(&gh_mock, std::fs::Permissions::from_mode(0o755))
            .expect("chmod gh");
        let _lock = crate::git::acquire_path_lock();
        let orig_path = std::env::var("PATH").unwrap_or_default();
        let _guard = EnvRestorer::new(
            "PATH",
            &format!("{}:{}", tmp.path().to_string_lossy(), orig_path),
        );

        let result = create_github_private_remote(&repo, "testaccount", true);

        assert!(result.is_some());
        assert_eq!(
            result.unwrap(),
            "https://github.com/testaccount/my-repo.git"
        );
    }

    #[test]
    fn test_create_github_private_remote_already_exists_reuses_without_suffix() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let repo = tmp.path().join("dracon-demons");
        crate::git::git_cmd()
            .args(["init", "-q", "-b", "master"])
            .arg(&repo)
            .status()
            .expect("git init");

        let gh_mock = tmp.path().join("gh");
        std::fs::write(
            &gh_mock,
            "#!/bin/sh\necho ' Name already exists' >&2\nexit 1\n",
        )
        .expect("write gh mock");
        std::fs::set_permissions(&gh_mock, std::fs::Permissions::from_mode(0o755))
            .expect("chmod gh");
        let _lock = crate::git::acquire_path_lock();
        let orig_path = std::env::var("PATH").unwrap_or_default();
        let _guard = EnvRestorer::new(
            "PATH",
            &format!("{}:{}", tmp.path().to_string_lossy(), orig_path),
        );

        let result = create_github_private_remote(&repo, "testaccount", true);

        assert!(result.is_some());
        let url = result.unwrap();
        assert!(!url.contains("-1"), "should NOT contain suffix -1: {}", url);
        assert!(!url.contains("-2"), "should NOT contain suffix -2: {}", url);
        assert_eq!(url, "https://github.com/testaccount/dracon-demons.git");
    }

    #[test]
    fn test_create_github_private_remote_origin_already_exists_does_not_add_duplicate() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let repo = tmp.path().join("existing-remote-repo");
        crate::git::git_cmd()
            .args(["init", "-q", "-b", "master"])
            .arg(&repo)
            .status()
            .expect("git init");
        crate::git::git_cmd()
            .args(["remote", "add", "origin", "git@github.com:old/old.git"])
            .current_dir(&repo)
            .status()
            .expect("git remote add");

        let gh_mock = tmp.path().join("gh");
        std::fs::write(&gh_mock, "#!/bin/sh\nexit 1\n").expect("write gh mock");
        std::fs::set_permissions(&gh_mock, std::fs::Permissions::from_mode(0o755))
            .expect("chmod gh");
        let _lock = crate::git::acquire_path_lock();
        let orig_path = std::env::var("PATH").unwrap_or_default();
        let _guard = EnvRestorer::new(
            "PATH",
            &format!("{}:{}", tmp.path().to_string_lossy(), orig_path),
        );

        let result = create_github_private_remote(&repo, "testaccount", true);

        assert!(result.is_some());
        let remotes = crate::git::multi_remote::list_remotes(&repo);
        assert_eq!(remotes.len(), 1, "should not add duplicate origin");
        assert_eq!(remotes[0], "origin");
    }

    #[test]
    fn test_create_github_private_remote_no_gh_installed_returns_none() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let repo = tmp.path().join("no-gh-repo");
        crate::git::git_cmd()
            .args(["init", "-q", "-b", "master"])
            .arg(&repo)
            .status()
            .expect("git init");

        let git_dir = std::path::Path::new("/run/current-system/sw/bin");
        let _lock = crate::git::acquire_path_lock();
        let _guard = EnvRestorer::new(
            "PATH",
            &format!(
                "{}:{}",
                tmp.path().to_string_lossy(),
                git_dir.to_string_lossy()
            ),
        );

        let result = create_github_private_remote(&repo, "testaccount", true);

        assert!(result.is_none());
    }

    #[test]
    fn test_shorten_when() {
        assert_eq!(shorten_when("5 seconds ago"), "5s");
        assert_eq!(shorten_when("29 minutes ago"), "29m");
        assert_eq!(shorten_when("74 minutes ago"), "1h 14m");
        assert_eq!(shorten_when("60 minutes ago"), "1h");
        assert_eq!(shorten_when("119 minutes ago"), "1h 59m");
        assert_eq!(shorten_when("3 hours ago"), "3h");
        assert_eq!(shorten_when("25 hours ago"), "1d 1h");
        assert_eq!(shorten_when("24 hours ago"), "1d");
        assert_eq!(shorten_when("48 hours ago"), "2d");
        assert_eq!(shorten_when("2 days ago"), "2d");
        assert_eq!(shorten_when("7 days ago"), "1w");
        assert_eq!(shorten_when("8 days ago"), "1w 1d");
        assert_eq!(shorten_when("14 days ago"), "2w");
        assert_eq!(shorten_when("12 months ago"), "1y");
        assert_eq!(shorten_when("13 months ago"), "1y 1mo");
        assert_eq!(shorten_when("6 weeks ago"), "6w");
        assert_eq!(shorten_when("just now"), "just now");
        assert_eq!(shorten_when("unknown"), "unknown");
    }

    #[test]
    fn test_push_status_calculation_from_flags() {
        // Test OK status - no issues
        let flags = ["OK".to_string()];
        let push_status = if flags.iter().any(|f| f == "STUCK_PUSH") {
            "STUCK"
        } else if flags.iter().any(|f| f == "NO_UPSTREAM") {
            "FAIL"
        } else {
            "OK"
        };
        assert_eq!(push_status, "OK");

        // Test STUCK status
        let flags = ["STUCK_PUSH".to_string()];
        let push_status = if flags.iter().any(|f| f == "STUCK_PUSH") {
            "STUCK"
        } else if flags.iter().any(|f| f == "NO_UPSTREAM") {
            "FAIL"
        } else {
            "OK"
        };
        assert_eq!(push_status, "STUCK");

        // Test FAIL status
        let flags = ["NO_UPSTREAM".to_string()];
        let push_status = if flags.iter().any(|f| f == "STUCK_PUSH") {
            "STUCK"
        } else if flags.iter().any(|f| f == "NO_UPSTREAM") {
            "FAIL"
        } else {
            "OK"
        };
        assert_eq!(push_status, "FAIL");
    }

    #[test]
    fn test_push_failure_notification_rate_limiting() {
        let mut cooldowns = std::collections::HashMap::new();
        let repo = std::path::PathBuf::from("/test/repo");
        let notify_key = format!("push-fail-{}", repo.display());
        let now = std::time::Instant::now();
        let cooldown_secs = 300;

        // First notification should be allowed
        assert!(!cooldowns.contains_key(&notify_key));

        // Set cooldown
        cooldowns.insert(
            notify_key.clone(),
            now + std::time::Duration::from_secs(cooldown_secs),
        );

        // Second notification within cooldown should be blocked
        let cooldown_until = cooldowns.get(&notify_key).unwrap();
        assert!(now < *cooldown_until, "should still be in cooldown");

        // After cooldown expires, notification should be allowed
        let expired_cooldown = now - std::time::Duration::from_secs(1);
        cooldowns.insert(notify_key.clone(), expired_cooldown);
        let cooldown_until = cooldowns.get(&notify_key).unwrap();
        assert!(now >= *cooldown_until, "cooldown should have expired");
    }

    #[test]
    fn test_repo_report_row_push_status_fields() {
        let row = RepoReportRow {
            repo: "/test/repo".to_string(),
            state_flags: vec!["STUCK_PUSH".to_string()],
            branch: "main".to_string(),
            modified: 0,
            staged: 0,
            untracked: 0,
            ahead: 5,
            behind: 0,
            last_hash: "abc123".to_string(),
            last_author: "test".to_string(),
            last_when: "2024-01-01".to_string(),
            last_msg: "test commit".to_string(),
            last_unix: 1700000000,
            last_push: "5m ago".to_string(),
            push_status: "STUCK".to_string(),
            push_error: "ahead=5, push failing".to_string(),
            concern: true,
            warn: false,
            hint: "run repair-concerns --apply (push or rewrite)".to_string(),
            state_cause: StateCause::Failed,
            state_cause_label: "failed".to_string(),
            daemon_last_action_unix: 0,
            daemon_last_action: String::new(),
            daemon_last_result: String::new(),
            daemon_last_action_when: "none".to_string(),
        };
        assert_eq!(row.push_status, "STUCK");
        assert!(row.push_error.contains("ahead=5"));
        assert!(row.concern);
    }

    // -------------------------------------------------------------------
    // read_tail_lines tests β€” used by build_recent_push_failure_map so
    // the incident-ledger scan is O(tail) instead of O(ledger_size).
    // -------------------------------------------------------------------

    #[test]
    fn read_tail_lines_empty_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("ledger.jsonl");
        std::fs::write(&path, b"").unwrap();
        let lines = read_tail_lines(&path, 100).unwrap();
        assert!(lines.is_empty());
    }

    #[test]
    fn read_tail_lines_small_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("ledger.jsonl");
        std::fs::write(&path, "line1\nline2\nline3\n").unwrap();
        let lines = read_tail_lines(&path, 100).unwrap();
        assert_eq!(lines, vec!["line1", "line2", "line3"]);
    }

    #[test]
    fn read_tail_lines_respects_window() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("ledger.jsonl");
        let body: String = (0..2000)
            .map(|i| format!("line{}", i))
            .collect::<Vec<_>>()
            .join("\n")
            + "\n";
        std::fs::write(&path, body).unwrap();
        let lines = read_tail_lines(&path, 50).unwrap();
        assert_eq!(lines.len(), 50);
        // Last 50 lines are line1950..line1999
        assert_eq!(lines.first().unwrap(), "line1950");
        assert_eq!(lines.last().unwrap(), "line1999");
    }

    #[test]
    fn read_tail_lines_handles_oversized_line() {
        // A single 20 KiB line should not confuse the chunk reader.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("ledger.jsonl");
        let big = "x".repeat(20_000);
        std::fs::write(&path, format!("{}\nshort\n", big)).unwrap();
        let lines = read_tail_lines(&path, 5).unwrap();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].len(), 20_000);
        assert_eq!(lines[1], "short");
    }

    #[test]
    fn read_tail_lines_handles_trailing_newline() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("ledger.jsonl");
        std::fs::write(&path, "a\nb\nc\n").unwrap();
        let lines = read_tail_lines(&path, 5).unwrap();
        // Trailing newline means three lines, no empty fourth.
        assert_eq!(lines, vec!["a", "b", "c"]);
    }

    // -------------------------------------------------------------------
    // build_recent_push_failure_map integration test.
    // -------------------------------------------------------------------

    #[test]
    fn build_recent_push_failure_map_returns_recent_failures() {
        use std::time::{SystemTime, UNIX_EPOCH};
        let dir = tempfile::tempdir().unwrap();
        let policy_path = dir.path().join("dracon-sync.toml");
        let ledger_path = dir.path().join("ledger.jsonl");
        std::fs::write(
            &policy_path,
            "pulse_interval_secs = 1\nwatch_roots = [\"/tmp\"]\n",
        )
        .unwrap();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let recent_ts = now - 30; // 30s ago, well within 10-min window
        let old_ts = now - 3600; // 1h ago, outside the window
        std::fs::write(
            &ledger_path,
            format!(
                "{{\"ts_unix\":{recent_ts},\"scope\":\"sync\",\"repo\":\"/tmp/recent-fail\",\"result\":\"fail\",\"reason\":\"push rejected\"}}\n\
                 {{\"ts_unix\":{old_ts},\"scope\":\"sync\",\"repo\":\"/tmp/old-fail\",\"result\":\"fail\",\"reason\":\"push rejected\"}}\n\
                 {{\"ts_unix\":{recent_ts},\"scope\":\"sync\",\"repo\":\"/tmp/recent-ok\",\"result\":\"ok\",\"reason\":\"pushed\"}}\n"
            ),
        )
        .unwrap();
        let ledger_str = ledger_path.to_string_lossy().to_string();
        let _ledger = EnvRestorer::new("DRACON_SYNC_LEDGER", &ledger_str);
        let map = build_recent_push_failure_map(&policy_path).unwrap();
        assert!(map.contains_key("/tmp/recent-fail"));
        assert!(!map.contains_key("/tmp/old-fail"));
        assert!(!map.contains_key("/tmp/recent-ok"));
    }

    #[test]
    fn build_recent_push_failure_map_missing_ledger_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        let policy_path = dir.path().join("dracon-sync.toml");
        let ledger_path = dir.path().join("missing-ledger.jsonl");
        std::fs::write(
            &policy_path,
            "pulse_interval_secs = 1\nwatch_roots = [\"/tmp\"]\n",
        )
        .unwrap();
        let ledger_str = ledger_path.to_string_lossy().to_string();
        let _ledger = EnvRestorer::new("DRACON_SYNC_LEDGER", &ledger_str);
        let map = build_recent_push_failure_map(&policy_path);
        assert!(map.is_none());
    }

    #[test]
    fn build_daemon_last_action_map_keeps_most_recent_per_repo() {
        let dir = tempfile::tempdir().unwrap();
        let policy_path = dir.path().join("dracon-sync.toml");
        let ledger_path = dir.path().join("ledger.jsonl");
        std::fs::write(
            &policy_path,
            "pulse_interval_secs = 1\nwatch_roots = [\"/tmp\"]\n",
        )
        .unwrap();
        // Two entries for the same repo: the second one is newer and
        // should win. A third entry for a different repo should also
        // appear.
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        let lines = vec![
            format!(
                "{{\"ts_unix\":{},\"scope\":\"sync\",\"repo\":\"/tmp/repo-a\",\"reason\":\"\",\"action\":\"sync_commit\",\"result\":\"ok\"}}",
                now - 60
            ),
            format!(
                "{{\"ts_unix\":{},\"scope\":\"sync\",\"repo\":\"/tmp/repo-a\",\"reason\":\"\",\"action\":\"sync_triage\",\"result\":\"ok\"}}",
                now - 5
            ),
            format!(
                "{{\"ts_unix\":{},\"scope\":\"warn\",\"repo\":\"/tmp/repo-b\",\"reason\":\"\",\"action\":\"dry_run_sync_triage\",\"result\":\"planned\"}}",
                now - 10
            ),
        ];
        std::fs::write(&ledger_path, lines.join("\n") + "\n").unwrap();
        let ledger_str = ledger_path.to_string_lossy().to_string();
        let _ledger = EnvRestorer::new("DRACON_SYNC_LEDGER", &ledger_str);
        let map = build_daemon_last_action_map(&policy_path).expect("map");
        let a = map.get("/tmp/repo-a").expect("repo-a entry");
        assert_eq!(a.1, "sync_triage", "newer action wins");
        assert_eq!(a.2, "ok");
        let b = map.get("/tmp/repo-b").expect("repo-b entry");
        assert_eq!(b.1, "dry_run_sync_triage");
        assert_eq!(b.2, "planned");
    }

    #[test]
    fn build_daemon_last_action_map_missing_ledger_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        let policy_path = dir.path().join("dracon-sync.toml");
        let ledger_path = dir.path().join("missing-ledger.jsonl");
        std::fs::write(
            &policy_path,
            "pulse_interval_secs = 1\nwatch_roots = [\"/tmp\"]\n",
        )
        .unwrap();
        let ledger_str = ledger_path.to_string_lossy().to_string();
        let _ledger = EnvRestorer::new("DRACON_SYNC_LEDGER", &ledger_str);
        let map = build_daemon_last_action_map(&policy_path);
        assert!(map.is_none());
    }
}