poi-tracker 0.28.0

Package-of-interest tracker for Fedora, EPEL, and CentOS SIGs
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
// SPDX-License-Identifier: Apache-2.0 OR MIT

mod act;
mod adopt;
mod config;
mod dependents;
mod deps;
mod derive;
mod gitlab_unshipped;
mod intersect;
mod kondo;
mod prune_retired;
mod reconcile;
mod semver_audit;
mod triage_retired;
mod triage_updates;
mod unkeep;
mod workspace;

use std::collections::BTreeMap;
use std::process::ExitCode;

use clap::{Parser, Subcommand};
use sandogasa_distgit::DistGitClient;

#[derive(Parser)]
#[command(
    about,
    long_about = None,
    max_term_width = 80,
    version = sandogasa_cli::version!(),
    before_help = sandogasa_cli::banner!()
)]
struct Cli {
    /// Exactly these inventory TOML file(s) (repeatable) — the most
    /// specific of the three ways to name inventories, and always
    /// honoured: it overrides whatever a workspace file would supply.
    #[arg(short, long, global = true)]
    inventory: Vec<String>,

    /// Every *.toml in DIR as an inventory, roles unknown — for
    /// commands that treat inventories alike (show, find, validate,
    /// export). Use -i to pick files, or a workspace to say which is
    /// which.
    #[arg(short = 'I', long, value_name = "DIR", global = true)]
    inventory_dir: Vec<String>,

    /// Run as if started in DIR (like `git -C`): the workspace file,
    /// relative inventory paths and outputs are looked up there.
    #[arg(short = 'C', long = "directory", value_name = "DIR", global = true)]
    directory: Option<String>,

    /// Workspace file (default: ./kondo.toml when present) naming which
    /// inventory is which — owned, keeps, derived, retired, cull — plus
    /// the graph and walk settings, so each subcommand knows its inputs
    /// without -i. Only fills flags not given on the command line;
    /// --no-defaults ignores it.
    #[arg(short = 'w', long, value_name = "PATH", global = true)]
    workspace: Option<String>,

    /// Which [[closure]] of the workspace a walk subcommand works on
    /// (default: the first).
    #[arg(long, value_name = "NAME", global = true)]
    closure: Option<String>,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Enact the standing cull verdicts interactively: orphan,
    /// remove own ACL, or give each package away, adjusting the
    /// inventories as you go.
    Act(ActArgs),
    /// Add a package to the inventory.
    Add(AddArgs),
    /// Adopt orphaned inventory packages on dist-git.
    Adopt(AdoptArgs),
    /// Render the standing cull verdicts as the grouped,
    /// announcement-ready report with runnable ACL commands.
    Announce(AnnounceArgs),
    /// Configure poi-tracker (Bugzilla API key, etc.).
    Config(sandogasa_cli::ConfigArgs),
    /// Classify inventory packages by who depends on them, over a
    /// saved dependency graph: leaves, packages other keeps carry,
    /// externally needed ones.
    Dependents(DependentsArgs),
    /// Inventory the dependencies pulled from other repos
    /// (e.g. EPEL).
    Deps(DepsArgs),
    /// Recompute a derived dependency inventory offline from a
    /// saved graph: owned packages the keeps reach.
    Derive(DeriveArgs),
    /// Export inventory to another format.
    Export(ExportArgs),
    /// Find which inventory file(s) contain a package.
    Find(FindArgs),
    /// Import from legacy JSON format.
    Import(ImportArgs),
    /// Keep only the inventory packages also present in other
    /// inventories, optionally merging them into a file.
    Intersect(IntersectArgs),
    /// Start keeping packages: walk them against the saved graph
    /// (fedrq only for what it lacks), merge, recompute the derived
    /// inventory.
    Keep(KeepArgs),
    /// Triage packages no essential inventory needs: keep as a
    /// cull candidate, file into an inventory, or drop.
    Kondo(KondoArgs),
    /// Mark (or remove) packages no longer carried on any
    /// active branch (dist-git project gone or retired
    /// everywhere).
    PruneRetired(PruneRetiredArgs),
    /// Bring the workspace's inventories up to date with its keeps:
    /// walk new keeps, recompute the derived inventories, ask the
    /// decisions a program cannot make, then triage what nothing
    /// justifies.
    Reconcile(ReconcileArgs),
    /// Remove a package from the inventory.
    Remove(RemoveArgs),
    /// Audit pending upstream updates by semver impact, flagging
    /// which are non-breaking, breaking, or need review.
    SemverAudit(SemverAuditArgs),
    /// Show inventory contents.
    Show(ShowArgs),
    /// Sync inventory from Fedora dist-git (Pagure) access.
    SyncDistgit(SyncDistgitArgs),
    /// Sync inventory from a GitLab RPM group.
    SyncGitlab(SyncGitlabArgs),
    /// Sync inventory from RPM Fusion's repositories, one workload
    /// per release.
    SyncRpmfusion(SyncRpmfusionArgs),
    /// Close open release-monitoring bugs as CANTFIX for any
    /// inventoried package that is retired on a dist-git branch.
    TriageRetired(TriageRetiredArgs),
    /// Triage open release-monitoring bugs for inventoried
    /// packages by bumping their Bugzilla priority to match the
    /// inventory.
    TriageUpdates(TriageUpdatesArgs),
    /// Stop keeping packages: over a saved dependency graph,
    /// report what the removal frees, and optionally edit the
    /// inventories.
    Unkeep(UnkeepArgs),
    /// Validate inventory consistency.
    Validate,
}

#[derive(clap::Args)]
struct PruneRetiredArgs {
    /// Active branch(es) to check against (CSV or repeated;
    /// e.g. `rawhide,f44,epel9`). Default: queried from Bodhi's
    /// active releases, plus rawhide.
    #[arg(
        long,
        value_delimiter = ',',
        value_name = "BRANCH,...",
        help_heading = "Selection"
    )]
    branch: Vec<String>,

    #[command(flatten, next_help_heading = "Selection")]
    filter: WalkFilterArgs,

    /// Parallel dist-git queries.
    #[arg(short = 'j', long, default_value = "8", help_heading = "Queries")]
    jobs: usize,

    /// Preview without modifying the inventory.
    #[arg(long, help_heading = "Writing")]
    dry_run: bool,

    /// Delete matched packages from the inventory instead of
    /// marking them `unshipped` (the default; marking survives
    /// re-syncs and lets triage-retired keep closing bugs).
    #[arg(long, conflicts_with = "dry_run", help_heading = "Writing")]
    remove: bool,

    /// Skip the confirmation prompt.
    #[arg(short, long, help_heading = "Writing")]
    yes: bool,

    /// Print progress to stderr.
    #[arg(short, long, help_heading = "Output")]
    verbose: bool,
}

#[derive(clap::Args)]
struct TriageRetiredArgs {
    /// Close ALL open bugs on retired branches, not just
    /// release-monitoring (Anitya) bugs. Use with care: this
    /// closes human-filed bugs (CVEs, FTBFS, etc.) too.
    #[arg(long, help_heading = "Selection")]
    all_reporters: bool,

    /// Batch mode: one Bugzilla query for bugs assigned to or
    /// CC'ing EMAIL (default: the configured email), matched
    /// against the inventory locally. Much faster on a large
    /// inventory, but misses bugs where EMAIL is neither
    /// assignee nor CC'd.
    #[arg(
        long,
        value_name = "EMAIL",
        num_args = 0..=1,
        help_heading = "Selection"
    )]
    batch: Option<Option<String>>,

    /// Dist-git branch(es) to check retirement against (CSV or
    /// repeated; e.g. `rawhide`, `epel10`, `f43`). Each branch
    /// scopes its own Bugzilla search — a `rawhide` retirement
    /// closes the Fedora/rawhide bug, an `epel9` retirement closes
    /// the Fedora EPEL/epel9 bug. A package retired on one branch
    /// but live on another only has bugs closed where it's dead.
    #[arg(
        long,
        value_delimiter = ',',
        value_name = "BRANCH,...",
        default_value = "rawhide",
        help_heading = "Selection"
    )]
    branch: Vec<String>,

    #[command(flatten, next_help_heading = "Selection")]
    filter: WalkFilterArgs,

    /// Bugzilla API key (or set BUGZILLA_API_KEY env var, or
    /// run `poi-tracker config`).
    #[arg(long, env = "BUGZILLA_API_KEY", help_heading = "Writing")]
    api_key: Option<String>,

    /// Also set `assigned_to` on each closed bug to the
    /// Bugzilla email set via `poi-tracker config`. Interactive
    /// mode prompts; with `-y` this flag is the only way to
    /// claim.
    #[arg(long, help_heading = "Writing")]
    claim: bool,

    /// Preview closures without applying them.
    #[arg(long, help_heading = "Writing")]
    dry_run: bool,

    /// Record results in the inventory's `retired_on` markers
    /// (adds and removes; needs a single -i file).
    #[arg(long, conflicts_with = "dry_run", help_heading = "Writing")]
    mark: bool,

    /// Skip the confirmation prompt.
    #[arg(short, long, help_heading = "Writing")]
    yes: bool,

    /// Print progress to stderr.
    #[arg(short, long, help_heading = "Output")]
    verbose: bool,
}

#[derive(clap::Args)]
struct TriageUpdatesArgs {
    /// Batch mode: one Bugzilla query for bugs assigned to or
    /// CC'ing EMAIL (default: the configured email), matched
    /// against the inventory locally. Much faster on a large
    /// inventory, but misses bugs where EMAIL is neither
    /// assignee nor CC'd.
    #[arg(
        long,
        value_name = "EMAIL",
        num_args = 0..=1,
        help_heading = "Selection"
    )]
    batch: Option<Option<String>>,

    #[command(flatten, next_help_heading = "Selection")]
    filter: WalkFilterArgs,

    /// Close partially-addressed bugs without asking.
    #[arg(long, conflicts_with = "skip_stale", help_heading = "Staleness")]
    close_stale: bool,

    /// Skip the Bodhi check for already-built updates.
    #[arg(long, help_heading = "Staleness")]
    skip_stale: bool,

    /// Bugzilla API key (or set BUGZILLA_API_KEY env var, or
    /// run `poi-tracker config`).
    #[arg(long, env = "BUGZILLA_API_KEY", help_heading = "Writing")]
    api_key: Option<String>,

    /// Also set `assigned_to` on each closed bug to the
    /// Bugzilla email set via `poi-tracker config`. Interactive
    /// mode prompts; with `-y` this flag is the only way to
    /// claim.
    #[arg(long, help_heading = "Writing")]
    claim: bool,

    /// Preview updates without applying them.
    #[arg(long, help_heading = "Writing")]
    dry_run: bool,

    /// Skip the confirmation prompt.
    #[arg(short, long, help_heading = "Writing")]
    yes: bool,

    /// Print progress to stderr.
    #[arg(short, long, help_heading = "Output")]
    verbose: bool,
}

/// Package filters shared by the inventory-walking commands. The
/// filters compose: a package must match the pattern AND fall
/// inside the `[start-from, end-with]` range.
#[derive(clap::Args, Default)]
struct WalkFilterArgs {
    /// Stop after this package (inclusive). Combine with
    /// `--start-from` to bound a sub-range.
    #[arg(long, value_name = "NAME")]
    end_with: Option<String>,

    /// Only process packages matching this glob (e.g. `rust-*`;
    /// a bare name matches exactly). Comma-separated or
    /// repeated; default: all packages.
    #[arg(long, value_delimiter = ',', value_name = "GLOB,...")]
    pattern: Vec<String>,

    /// Resume from this package onwards (inclusive), in the
    /// inventory's iteration order.
    #[arg(long, value_name = "NAME")]
    start_from: Option<String>,
}

impl WalkFilterArgs {
    /// Whether `name` passes every configured filter.
    fn matches(&self, name: &str) -> bool {
        matches_any_pattern(name, &self.pattern)
            && self.start_from.as_deref().is_none_or(|s| name >= s)
            && self.end_with.as_deref().is_none_or(|e| name <= e)
    }
}

#[derive(clap::Args)]
struct SemverAuditArgs {
    /// Batch mode: one Bugzilla query for bugs assigned to or
    /// CC'ing EMAIL (default: the configured email), matched
    /// against the inventory locally. Much faster on a large
    /// inventory, but misses bugs where EMAIL is neither
    /// assignee nor CC'd.
    #[arg(
        long,
        value_name = "EMAIL",
        num_args = 0..=1,
        help_heading = "Selection"
    )]
    batch: Option<Option<String>>,

    #[command(flatten, next_help_heading = "Selection")]
    filter: WalkFilterArgs,

    /// Output as JSON instead of human-readable text.
    #[arg(long, help_heading = "Output")]
    json: bool,

    /// Show only non-breaking updates.
    #[arg(long, help_heading = "Output")]
    non_breaking: bool,

    /// Print progress to stderr.
    #[arg(short, long, help_heading = "Output")]
    verbose: bool,
}

#[derive(clap::Args)]
struct IntersectArgs {
    /// Output as JSON instead of human-readable.
    #[arg(long)]
    json: bool,

    /// Merge the intersection into this inventory TOML file
    /// (accumulates; existing entries win).
    #[arg(short, long)]
    output: Option<String>,

    /// Inventory file(s) to intersect with: only packages of the
    /// main inventory also found in one of these survive
    /// (repeat the flag per file).
    #[arg(long, required = true)]
    with: Vec<String>,
}

#[derive(clap::Args)]
struct KondoArgs {
    #[command(flatten, next_help_heading = "Selection")]
    filter: WalkFilterArgs,

    /// Essential inventory file(s): packages found in any of these
    /// are never cull candidates (repeat the flag per file).
    #[arg(long, required = true, help_heading = "Triage")]
    essential: Vec<String>,

    /// Default inventory for 'explain': Enter at the explanation
    /// prompt files the package here.
    #[arg(long, value_name = "PATH", help_heading = "Triage")]
    explain_into: Option<String>,

    /// Reason recorded in the -o cull file for packages culled this
    /// run (the access level is always appended). A note typed at
    /// the prompt as `c <note>` overrides it per package.
    #[arg(long, help_heading = "Triage")]
    reason: Option<String>,

    /// Ignore the day-fresh ACL cache and look every level up again.
    #[arg(long, help_heading = "Triage")]
    refresh_acls: bool,

    /// dist-git username whose access level routes each action.
    #[arg(long, help_heading = "Triage")]
    user: String,

    /// Merge the culled set into this inventory TOML file
    /// (accumulates across passes).
    #[arg(short, long, help_heading = "Writing")]
    output: Option<String>,

    /// Keep every candidate without prompting.
    #[arg(short, long, help_heading = "Writing")]
    yes: bool,

    /// Output as JSON instead of human-readable.
    #[arg(long, help_heading = "Output")]
    json: bool,

    /// Print progress to stderr.
    #[arg(short, long, help_heading = "Output")]
    verbose: bool,
}

/// The maintenance loop as one command. Needs a workspace file (`-w`,
/// or `./kondo.toml`). For every closure in it: keeps the graph has
/// never walked are walked (fedrq only for what the graph lacks) and
/// merged in; the derived inventory is recomputed; each package that
/// newly rides in it can be made essential in its own right instead;
/// each keep only devel-only edges carry can be demoted to the derived
/// inventory. Then the owned packages no essential inventory justifies
/// go through kondo's keep/explain/remove triage into the cull file.
/// Every answer is written as it is given, so an interrupted run
/// resumes where it stopped; Enter takes the default (ride, keep),
/// `a` takes it for the rest, `q` stops asking. `--yes` takes every
/// default without asking; `--json` reports and asks nothing.
#[derive(clap::Args)]
struct ReconcileArgs {
    /// Compute and report only: write no file, walk nothing, ask
    /// nothing (new keeps are listed instead of walked).
    #[arg(long)]
    dry_run: bool,

    /// Essential inventory that promoted packages are filed into
    /// (default: the closure's first keeps inventory).
    #[arg(long, value_name = "PATH")]
    into: Option<String>,

    /// Report as JSON; asks and triages nothing (files are still
    /// written unless --dry-run).
    #[arg(long)]
    json: bool,

    /// Ignore the day-fresh ACL cache in the triage.
    #[arg(long)]
    refresh_acls: bool,

    /// Print progress to stderr.
    #[arg(short, long)]
    verbose: bool,

    /// Take every default without asking (ride, keep essential),
    /// and leave the triage candidates as cull candidates.
    #[arg(short, long)]
    yes: bool,
}

/// Where a dependency walk looks and what it collects — shared by
/// `deps` (a full walk) and `keep` (an incremental one).
#[derive(clap::Args)]
struct WalkRepoArgs {
    /// Base-distro repo id prefix(es); their providers end the
    /// walk.
    ///
    /// The default treats CentOS Stream as the given beneath an
    /// EPEL stack. A Fedora walk has no base distro — the default
    /// then never matches, and everything resolves within --from's
    /// repos, which is what you want.
    #[arg(long, value_delimiter = ',', default_value = "fedrq-centos-stream-")]
    base_repo: Vec<String>,

    /// fedrq branch (e.g. hs.el9, epel9).
    #[arg(short, long)]
    branch: String,

    /// Collect providers from these repo ids (CSV or repeated).
    ///
    /// Exact match. The default suits an EPEL walk; for a Fedora
    /// walk pass the branch's own repo id, e.g. `--from rawhide`.
    #[arg(long, value_delimiter = ',', default_value = "epel")]
    from: Vec<String>,

    /// fedrq repo class (e.g. stack).
    #[arg(short, long)]
    repo: Option<String>,

    /// Walk runtime dependencies only, without seeding the
    /// roots' BuildRequires.
    #[arg(long)]
    runtime_only: bool,
}

#[derive(clap::Args)]
struct KeepArgs {
    /// Packages to start keeping.
    #[arg(required = true, value_name = "PACKAGE")]
    names: Vec<String>,

    #[command(flatten, next_help_heading = "Walk")]
    walk: WalkRepoArgs,

    /// Derived inventory to recompute afterwards (optional).
    #[arg(long, value_name = "PATH", help_heading = "Inventories")]
    deps: Option<String>,

    /// Saved dependency graph to extend (from `deps`); the walk
    /// resolves offline whatever it already knows.
    #[arg(long, value_name = "PATH", help_heading = "Inventories")]
    graph: String,

    /// Keep inventory to add them to (default: the first -i).
    #[arg(long, value_name = "PATH", help_heading = "Inventories")]
    into: Option<String>,

    /// Closure inventory (the `deps -o` file) to bring up to date
    /// with the graph afterwards (optional).
    #[arg(short, long, value_name = "PATH", help_heading = "Inventories")]
    output: Option<String>,

    /// Inventory of the packages you own — newly reached owned
    /// packages become fixpoint roots and derived entries.
    #[arg(long, value_name = "PATH", help_heading = "Inventories")]
    owned: String,

    /// Output as JSON instead of human-readable.
    #[arg(long, help_heading = "Output")]
    json: bool,

    /// Print progress to stderr.
    #[arg(short, long, help_heading = "Output")]
    verbose: bool,
}

#[derive(clap::Args)]
struct DepsArgs {
    #[command(flatten, next_help_heading = "Selection")]
    filter: WalkFilterArgs,

    #[command(flatten, next_help_heading = "Walk")]
    walk: WalkRepoArgs,

    /// Iterate to a fixpoint: collected packages found in this
    /// inventory (yours) become roots whose BuildRequires seed
    /// further rounds.
    #[arg(
        long,
        value_name = "PATH",
        conflicts_with = "runtime_only",
        help_heading = "Inventories"
    )]
    fixpoint: Option<String>,

    /// Where to write the walk's full dependency graph (every
    /// requirer/provider edge, not just first attributions) as
    /// JSON. Default: beside -o, as <output>-graph.json.
    #[arg(long, value_name = "PATH", help_heading = "Inventories")]
    graph: Option<String>,

    /// Inventory name for --output
    /// (default: "<input name>-deps-<branch>").
    #[arg(long, help_heading = "Inventories")]
    name: Option<String>,

    /// Write the collected dependencies as an inventory TOML file.
    #[arg(short, long, help_heading = "Inventories")]
    output: Option<String>,

    /// Output as JSON instead of human-readable.
    #[arg(long, help_heading = "Output")]
    json: bool,

    /// Print progress to stderr.
    #[arg(short, long, help_heading = "Output")]
    verbose: bool,
}

#[derive(clap::Args)]
struct ActArgs {
    #[command(flatten, next_help_heading = "Selection")]
    filter: WalkFilterArgs,

    /// Branch(es) for the reverse-dependency probe before an orphan
    /// (CSV or repeated). The default `auto` derives them per package
    /// from its dist-git branches: rawhide plus its own EPEL
    /// branches — an EPEL-only package's dependents are invisible
    /// from rawhide.
    #[arg(
        long,
        value_delimiter = ',',
        default_value = "auto",
        help_heading = "Actions"
    )]
    branch: Vec<String>,

    /// Ignore the day-fresh ACL cache and look every level up again.
    #[arg(long, help_heading = "Actions")]
    refresh_acls: bool,

    /// FAS username whose ACL actions these are.
    #[arg(long, help_heading = "Actions")]
    user: String,

    /// Dist-git API token (or PAGURE_API_TOKEN, or run
    /// `poi-tracker config`).
    #[arg(long, env = "PAGURE_API_TOKEN", help_heading = "Writing")]
    api_token: Option<String>,

    /// Personal inventory to drop enacted packages from.
    #[arg(long, value_name = "PATH", help_heading = "Writing")]
    personal: Option<String>,

    /// Log each access lookup.
    #[arg(short, long, help_heading = "Output")]
    verbose: bool,
}

#[derive(clap::Args)]
struct AnnounceArgs {
    /// Output machine-readable JSON.
    #[arg(long)]
    json: bool,

    /// Ignore the day-fresh ACL cache and look every level up again.
    #[arg(long)]
    refresh_acls: bool,

    /// FAS username whose access level routes each action.
    #[arg(long)]
    user: String,

    /// Log each access lookup.
    #[arg(short, long)]
    verbose: bool,
}

#[derive(clap::Args)]
struct DependentsArgs {
    /// Dependency graph JSON from a `deps --graph` run.
    #[arg(long, value_name = "PATH")]
    graph: String,

    /// Output machine-readable JSON.
    #[arg(long)]
    json: bool,
}

#[derive(clap::Args)]
struct DeriveArgs {
    /// Replace the output file's packages; without it, report only.
    #[arg(long)]
    apply: bool,

    /// Dependency graph JSON from a `deps --graph` run.
    #[arg(long, value_name = "PATH")]
    graph: String,

    /// Output machine-readable JSON.
    #[arg(long)]
    json: bool,

    /// The derived inventory to recompute.
    #[arg(short, long, value_name = "PATH")]
    output: String,

    /// Inventory of the packages you own (e.g. a sync-distgit
    /// output); only owned packages enter the derived inventory.
    #[arg(long, value_name = "PATH")]
    owned: String,
}

#[derive(clap::Args)]
struct UnkeepArgs {
    /// Packages to stop keeping.
    #[arg(required = true, value_name = "PACKAGE")]
    names: Vec<String>,

    /// Edit the inventories; without it, report only.
    #[arg(long)]
    apply: bool,

    /// Derived dependency inventories (a `deps` output merged by
    /// `intersect`, say); freed packages leave these with --apply.
    #[arg(long, value_name = "PATH")]
    deps: Vec<String>,

    /// Dependency graph JSON from a `deps --graph` run.
    #[arg(long, value_name = "PATH")]
    graph: String,

    /// Output machine-readable JSON.
    #[arg(long)]
    json: bool,
}

#[derive(clap::Args)]
struct AddArgs {
    /// Source RPM name.
    name: String,

    /// Binary RPM subpackage(s) to track (comma-separated or repeated).
    #[arg(long, value_delimiter = ',', help_heading = "Tracking")]
    rpm: Vec<String>,

    /// Track branch for hs-relmon (e.g. upstream, fedora-rawhide).
    #[arg(long, help_heading = "Tracking")]
    track: Option<String>,

    /// Workload tag(s) (comma-separated or repeated).
    #[arg(long, value_delimiter = ',', help_heading = "Tracking")]
    workload: Vec<String>,

    /// Point of contact ("Name <email>").
    #[arg(long, help_heading = "Metadata")]
    poc: Option<String>,

    /// Reason for tracking.
    #[arg(long, help_heading = "Metadata")]
    reason: Option<String>,

    /// Internal task/ticket reference.
    #[arg(long, help_heading = "Metadata")]
    task: Option<String>,

    /// Team responsible.
    #[arg(long, help_heading = "Metadata")]
    team: Option<String>,
}

#[derive(clap::Args)]
struct AdoptArgs {
    #[command(flatten, next_help_heading = "Selection")]
    filter: WalkFilterArgs,

    /// Dist-git API token with the `modify_project` ACL (or set
    /// PAGURE_API_TOKEN, or run `poi-tracker config`).
    #[arg(long, env = "PAGURE_API_TOKEN", help_heading = "Writing")]
    api_token: Option<String>,

    /// Preview orphaned packages without adopting them.
    #[arg(long, help_heading = "Writing")]
    dry_run: bool,

    /// Adopt every orphaned match without per-package prompts.
    #[arg(short, long, help_heading = "Writing")]
    yes: bool,

    /// Print progress to stderr.
    #[arg(short, long, help_heading = "Output")]
    verbose: bool,
}

#[derive(clap::Args)]
struct FindArgs {
    /// Source RPM name to search for.
    name: String,
}

#[derive(clap::Args)]
struct RemoveArgs {
    /// Source RPM name to remove.
    name: String,

    /// Remove specific binary RPM(s) instead of the whole package.
    #[arg(long, value_delimiter = ',')]
    rpm: Vec<String>,
}

#[derive(clap::Args)]
struct ShowArgs {
    /// Output as JSON instead of human-readable.
    #[arg(long)]
    json: bool,

    /// Filter by workload.
    #[arg(long)]
    workload: Option<String>,
}

#[derive(clap::Args)]
struct ExportArgs {
    #[command(subcommand)]
    format: ExportFormat,
}

#[derive(Subcommand)]
enum ExportFormat {
    /// Export as content-resolver YAML.
    ContentResolver {
        /// Output file (default: {workload-name}.yaml).
        #[arg(short, long)]
        output: Option<String>,
        /// Export only this workload.
        #[arg(long)]
        workload: Option<String>,
    },
    /// Export as hs-relmon manifest TOML.
    HsRelmon {
        /// Default distros list.
        #[arg(long, default_value = "upstream,fedora,centos,hyperscale")]
        distros: String,

        /// Output file (default: stdout).
        #[arg(short, long)]
        output: Option<String>,

        /// Remove manifest entries not in the inventory.
        #[arg(long)]
        prune: bool,

        /// Default tracking branch.
        #[arg(long, default_value = "upstream")]
        track: String,

        /// Filter by workload.
        #[arg(long)]
        workload: Option<String>,
    },
}

#[derive(clap::Args)]
struct ImportArgs {
    /// Path to legacy JSON inventory file.
    json_file: String,

    /// Output path for TOML inventory.
    #[arg(short, long, default_value = "inventory.toml")]
    output: String,

    /// Fields to mark as private (stripped on export).
    #[arg(long, value_delimiter = ',', value_name = "FIELD,...")]
    private_fields: Vec<String>,

    /// Workload tag(s) to apply to all imported packages.
    #[arg(long, value_delimiter = ',', value_name = "WORKLOAD,...")]
    workload: Vec<String>,
}

#[derive(clap::Args)]
#[command(group(
    clap::ArgGroup::new("source")
        .required(true)
        .args(["user", "group"])
))]
struct SyncDistgitArgs {
    /// Exclude packages by glob (CSV or repeated).
    #[arg(
        long,
        value_delimiter = ',',
        value_name = "GLOB,...",
        help_heading = "Selection"
    )]
    exclude: Vec<String>,

    /// Drop these groups (CSV or repeated).
    #[arg(
        long,
        value_delimiter = ',',
        value_name = "GROUP,...",
        help_heading = "Selection"
    )]
    exclude_group: Vec<String>,

    /// Import packages for this dist-git group.
    #[arg(long, help_heading = "Selection")]
    group: Option<String>,

    /// Keep only these groups (CSV or repeated).
    #[arg(
        long,
        value_delimiter = ',',
        value_name = "GROUP,...",
        conflicts_with = "exclude_group",
        help_heading = "Selection"
    )]
    include_group: Vec<String>,

    /// Exclude group-only access.
    #[arg(
        long,
        conflicts_with_all = ["include_group", "exclude_group"],
        help_heading = "Selection"
    )]
    no_groups: bool,

    /// Import packages for this dist-git user.
    #[arg(long, help_heading = "Selection")]
    user: Option<String>,

    /// Query by a-z/0-9 prefix (--user default).
    #[arg(long, overrides_with = "no_auto_prefix", help_heading = "Queries")]
    auto_prefix: bool,

    /// Stop the prefix scan before this prefix.
    #[arg(long, value_name = "PREFIX", help_heading = "Queries")]
    end_pattern: Option<String>,

    /// One owner-alias request instead of a prefix scan.
    /// Direct owner/admin/commit only: collaborator/ticket
    /// grants are missed (and removed under --prune). Implies
    /// --no-groups.
    #[arg(
        long,
        conflicts_with_all = ["group", "include_group", "exclude_group",
                              "auto_prefix", "no_auto_prefix",
                              "start_pattern", "end_pattern"],
        help_heading = "Queries"
    )]
    fast: bool,

    /// Parallel dist-git queries for --mark-unshipped.
    #[arg(short = 'j', long, default_value = "8", help_heading = "Queries")]
    jobs: usize,

    /// Single query; may 504 for a --user sync.
    #[arg(
        long,
        overrides_with = "auto_prefix",
        conflicts_with_all = ["start_pattern", "end_pattern"],
        help_heading = "Queries"
    )]
    no_auto_prefix: bool,

    /// Name pattern for a single patterned query.
    #[arg(
        long,
        conflicts_with_all = ["auto_prefix", "start_pattern", "end_pattern"],
        help_heading = "Queries"
    )]
    pattern: Option<String>,

    /// Pagure API page size.
    #[arg(long, default_value = "100", help_heading = "Queries")]
    per_page: u32,

    /// Start the prefix scan at this prefix.
    #[arg(long, value_name = "PREFIX", help_heading = "Queries")]
    start_pattern: Option<String>,

    /// Mark packages added by this sync that are already
    /// retired everywhere (like prune-retired).
    #[arg(long, help_heading = "Writing")]
    mark_unshipped: bool,

    /// Inventory name (default: user/group).
    #[arg(long, help_heading = "Writing")]
    name: Option<String>,

    /// Output TOML file.
    #[arg(
        short,
        long,
        default_value = "inventory.toml",
        help_heading = "Writing"
    )]
    output: String,

    /// Remove packages no longer in dist-git results.
    #[arg(long, help_heading = "Writing")]
    prune: bool,

    /// Workload tags (CSV or repeated).
    #[arg(
        long,
        value_delimiter = ',',
        value_name = "WORKLOAD,...",
        help_heading = "Writing"
    )]
    workload: Vec<String>,
}

/// Well-known GitLab RPM group presets.
const GITLAB_PRESETS: &[(&str, &str)] = &[
    ("hyperscale", "https://gitlab.com/CentOS/Hyperscale/rpms"),
    (
        "proposed-updates",
        "https://gitlab.com/CentOS/proposed_updates/rpms",
    ),
    (
        "centos-stream",
        "https://gitlab.com/redhat/centos-stream/rpms",
    ),
];

#[derive(clap::Args)]
#[command(group(
    clap::ArgGroup::new("source")
        .required(true)
        .args(["url", "preset"])
))]
struct SyncGitlabArgs {
    /// Exclude packages by glob (CSV or repeated).
    #[arg(
        long,
        value_delimiter = ',',
        value_name = "GLOB,...",
        help_heading = "Selection"
    )]
    exclude: Vec<String>,

    /// Preset: hyperscale, proposed-updates, centos-stream.
    #[arg(long, help_heading = "Selection")]
    preset: Option<String>,

    /// GitLab group URL.
    #[arg(long, help_heading = "Selection")]
    url: Option<String>,

    /// CentOS releases to count as currently shipped (CSV).
    #[arg(
        long,
        value_delimiter = ',',
        value_name = "REL,...",
        default_value = "9,10",
        help_heading = "Writing"
    )]
    centos_release: Vec<u32>,

    /// Mark archived projects with no released CBS build as
    /// unshipped (Hyperscale: RHEL or Stream; Proposed Updates:
    /// Stream only).
    #[arg(long, help_heading = "Writing")]
    mark_unshipped: bool,

    /// Inventory name (default: derived from group).
    #[arg(long, help_heading = "Writing")]
    name: Option<String>,

    /// Output TOML file.
    #[arg(
        short,
        long,
        default_value = "inventory.toml",
        help_heading = "Writing"
    )]
    output: String,

    /// Remove packages no longer in GitLab results.
    #[arg(long, help_heading = "Writing")]
    prune: bool,

    /// Workload tags (CSV or repeated).
    #[arg(
        long,
        value_delimiter = ',',
        value_name = "WORKLOAD,...",
        help_heading = "Writing"
    )]
    workload: Vec<String>,
}

#[derive(clap::Args)]
struct SyncRpmfusionArgs {
    /// Inventory name (default: rpmfusion).
    #[arg(long)]
    name: Option<String>,

    /// Output TOML file.
    #[arg(short, long, default_value = "inventory.toml")]
    output: String,

    /// Remove packages RPM Fusion ships for no release listed in the
    /// inventory. Scanning a subset never prunes what another
    /// release still ships.
    #[arg(long)]
    prune: bool,

    /// Releases to scan (CSV): f43, f44, el10. Each becomes a
    /// workload, so the inventory can answer per release.
    #[arg(
        short,
        long,
        required = true,
        value_delimiter = ',',
        value_name = "REL,..."
    )]
    release: Vec<String>,

    /// fedrq repo class. The default covers free and nonfree
    /// together, which is what "does RPM Fusion ship this?" asks.
    #[arg(long, value_name = "CLASS")]
    repo: Option<String>,
}

/// Command outcome: hard failures bubble up as an error (printed
/// as `error: {e}` with a FAILURE exit by `main`); soft outcomes
/// already reported inline (e.g. partial failures, "not found")
/// pick their own `ExitCode`.
type CmdResult = Result<ExitCode, Box<dyn std::error::Error>>;

/// Derive a YAML filename for a workload export.
fn workload_export_filename(
    inventory: &sandogasa_inventory::Inventory,
    workload_key: &str,
) -> String {
    let meta = inventory.inventory.workloads.get(workload_key);
    let name = meta
        .and_then(|m| m.name.as_deref())
        .map(|n| n.to_string())
        .unwrap_or_else(|| format!("{}-{workload_key}", inventory.inventory.name));
    format!("{}.yaml", name.replace(' ', "_"))
}

/// Build a workloads map from a list of workload names.
fn workloads_from_names(names: &[String]) -> BTreeMap<String, sandogasa_inventory::WorkloadMeta> {
    names
        .iter()
        .map(|n| (n.clone(), sandogasa_inventory::WorkloadMeta::default()))
        .collect()
}

/// The real Koji tag lookup backing the shipped-build checks in
/// `triage-updates` and `semver-audit`: latest NVR of a package
/// in a tag's inheritance chain. `None` when the koji CLI isn't
/// on PATH — callers warn and degrade (fail-safe: unverifiable
/// builds count as not shipped / not verified).
fn koji_tag_lookup() -> Option<impl Fn(&str, &str) -> Result<Option<String>, String>> {
    sandogasa_koji::is_available().then_some(|tag: &str, package: &str| {
        sandogasa_koji::latest_tagged(tag, package, None).map(|b| b.map(|tb| tb.nvr))
    })
}

/// Collect inventory paths from -i and -I flags.
/// Resolve a `--batch [EMAIL]` flag: an explicit email wins, a
/// bare `--batch` falls back to the configured Bugzilla email.
fn resolve_batch_email(batch: &Option<Option<String>>) -> Result<Option<String>, String> {
    match batch {
        None => Ok(None),
        Some(Some(email)) => Ok(Some(email.clone())),
        Some(None) => config::resolve_email().map(Some).ok_or_else(|| {
            "--batch needs an email: none configured (run `poi-tracker \
             config`) and none passed (--batch <email>)"
                .to_string()
        }),
    }
}

fn resolve_inventory_paths(cli: &Cli) -> Vec<String> {
    let mut paths = cli.inventory.clone();

    for dir in &cli.inventory_dir {
        if let Ok(entries) = std::fs::read_dir(dir) {
            let mut dir_paths: Vec<String> = entries
                .filter_map(|e| e.ok())
                .filter(|e| e.path().extension().is_some_and(|ext| ext == "toml"))
                .map(|e| e.path().to_string_lossy().to_string())
                .collect();
            dir_paths.sort();
            paths.extend(dir_paths);
        } else {
            eprintln!("warning: could not read directory: {dir}");
        }
    }

    paths
}

fn main() -> ExitCode {
    sandogasa_cli::init();
    // `-C DIR` first, before anything looks at a relative path — the
    // way git does it: scanned off argv so the workspace lookup inside
    // the parse already runs from there.
    if let Some(dir) = directory_flag(std::env::args_os())
        && let Err(e) = std::env::set_current_dir(&dir)
    {
        eprintln!("error: cannot change to {}: {e}", dir.to_string_lossy());
        return ExitCode::FAILURE;
    }
    let cli = sandogasa_cli::parse_with_defaults_and::<Cli>(env!("CARGO_PKG_NAME"), |m| {
        let explicit = m.get_one::<String>("workspace").map(String::as_str);
        use workspace::WorkspaceDefaults as _;
        let Some((ws, path)) = workspace::Workspace::find(explicit)? else {
            return Ok(None);
        };
        let Some((sub, _)) = m.subcommand() else {
            return Ok(None);
        };
        let closure = m.get_one::<String>("closure").map(String::as_str);
        Ok(ws
            .defaults_for(sub, closure)?
            .map(|table| (table, format!("workspace {}", path.display()))))
    });

    // Import/sync commands produce new files and don't need existing
    // inventory paths. `Config` doesn't touch inventories at all.
    let needs_paths = !matches!(
        cli.command,
        Command::Config(_)
            | Command::Import(_)
            | Command::Reconcile(_)
            | Command::SyncDistgit(_)
            | Command::SyncGitlab(_)
            | Command::SyncRpmfusion(_)
    );

    let paths = resolve_inventory_paths(&cli);

    if needs_paths && paths.is_empty() {
        eprintln!("error: no inventory files specified. Use -i or -I.");
        return ExitCode::FAILURE;
    }

    let result = match &cli.command {
        Command::Add(args) => cmd_add(&paths, args),
        Command::Act(args) => cmd_act(&paths, args),
        Command::Adopt(args) => cmd_adopt(&paths, args),
        Command::Announce(args) => cmd_announce(&paths, args),
        Command::Config(args) => cmd_config(args),
        Command::Deps(args) => cmd_deps(&paths, args),
        Command::Export(args) => cmd_export(&paths, args),
        Command::Find(args) => cmd_find(&paths, args),
        Command::Import(args) => cmd_import(args),
        Command::Intersect(args) => cmd_intersect(&paths, args),
        Command::Dependents(args) => cmd_dependents(&paths, args),
        Command::Derive(args) => cmd_derive(&paths, args),
        Command::Keep(args) => cmd_keep(&paths, args),
        Command::Kondo(args) => cmd_kondo(&paths, args),
        Command::Reconcile(args) => cmd_reconcile(cli.workspace.as_deref(), args),
        Command::PruneRetired(args) => cmd_prune_retired(&paths, args),
        Command::Remove(args) => cmd_remove(&paths[0], args),
        Command::SemverAudit(args) => cmd_semver_audit(&paths, args),
        Command::Show(args) => cmd_show(&paths, args),
        Command::SyncDistgit(args) => cmd_sync_distgit(args),
        Command::SyncGitlab(args) => cmd_sync_gitlab(args),
        Command::SyncRpmfusion(args) => cmd_sync_rpmfusion(args),
        Command::TriageRetired(args) => cmd_triage_retired(&paths, args),
        Command::TriageUpdates(args) => cmd_triage_updates(&paths, args),
        Command::Unkeep(args) => cmd_unkeep(&paths, args),
        Command::Validate => cmd_validate(&paths),
    };
    match result {
        Ok(code) => code,
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::FAILURE
        }
    }
}

/// Create a Tokio runtime, prefixing the (rare) failure so the
/// boundary's `error: {e}` matches the old inline message.
fn new_runtime() -> Result<tokio::runtime::Runtime, String> {
    tokio::runtime::Runtime::new().map_err(|e| format!("failed to create runtime: {e}"))
}

fn cmd_semver_audit(paths: &[String], args: &SemverAuditArgs) -> CmdResult {
    let inventory = sandogasa_inventory::load_and_merge(paths)?;
    // Read-only: anonymous Bugzilla search + public dist-git.
    let bz = sandogasa_bugzilla::BzClient::new(&config::resolve_url());
    let dg = sandogasa_distgit::DistGitClient::new();
    let rt = new_runtime()?;
    let batch_email = resolve_batch_email(&args.batch)?;
    let koji_lookup = koji_tag_lookup();
    let latest_tagged = match &koji_lookup {
        Some(l) => Some(l as &triage_updates::TagLookup),
        None => {
            eprintln!(
                "warning: koji CLI not found; cannot tell stale bugs from \
                 committed-but-unreleased versions — reporting them all as \
                 up to date. Install koji to enable the check."
            );
            None
        }
    };
    let entries = rt.block_on(semver_audit::run(
        &inventory,
        &bz,
        &dg,
        latest_tagged,
        &args.filter,
        args.non_breaking,
        batch_email.as_deref(),
        args.verbose,
    ))?;
    if args.json {
        println!("{}", serde_json::to_string_pretty(&entries)?);
    } else {
        semver_audit::print_report(&entries);
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_prune_retired(paths: &[String], args: &PruneRetiredArgs) -> CmdResult {
    // Pruning rewrites the inventory, which only makes sense for
    // a single file; --dry-run may preview a merged view.
    if !args.dry_run && paths.len() != 1 {
        return Err(format!(
            "prune-retired modifies the inventory and needs \
             exactly one inventory file (got {}); use --dry-run to \
             preview a merged view",
            paths.len()
        )
        .into());
    }
    let inventory = sandogasa_inventory::load_and_merge(paths)?;
    let dg = sandogasa_distgit::DistGitClient::new();
    let rt = new_runtime()?;

    // The active branch set defines "carried anywhere": explicit
    // --branch wins (keeping the user's order), otherwise ask
    // Bodhi for the active releases, ordered most-likely-live
    // first so per-package checks short-circuit early.
    let active: Vec<String> = if !args.branch.is_empty() {
        args.branch.clone()
    } else {
        rt.block_on(prune_retired::active_branches_from_bodhi())?
    };
    if args.verbose {
        eprintln!("[poi-tracker] active branches: {}", active.join(", "));
    }

    let report = rt.block_on(prune_retired::run(
        &inventory,
        &dg,
        &active,
        &args.filter,
        args.jobs,
        args.verbose,
    ))?;

    if !report.candidates.is_empty() {
        println!("Packages no longer carried on any active branch:");
        for c in &report.candidates {
            println!("- {}: {}", c.package, c.reason.describe());
        }
    }
    if !report.invalid.is_empty() {
        println!(
            "\nInvalid entries — no such dist-git package (fix or \
             remove; often a non-rpms project imported by an older \
             sync, or a binary subpackage name recorded instead of \
             the source package):"
        );
        for name in &report.invalid {
            println!("- {name}");
        }
    }
    eprintln!(
        "\n{} checked, {} prunable, {} invalid",
        report.packages_checked,
        report.candidates.len(),
        report.invalid.len()
    );
    if args.dry_run {
        return Ok(ExitCode::SUCCESS);
    }

    // Apply to the single inventory file. Default: update the
    // `unshipped` markers (both directions — clears marks on
    // revived packages). --remove deletes the entries instead.
    let path = &paths[0];
    let mut inv = sandogasa_inventory::load(path).map_err(|e| format!("reloading {path}: {e}"))?;
    if args.remove {
        if report.candidates.is_empty() {
            eprintln!("nothing to remove");
            return Ok(ExitCode::SUCCESS);
        }
        if !args.yes
            && !triage_updates::confirm(&format!(
                "Remove {} package(s) from {path}?",
                report.candidates.len()
            ))?
        {
            eprintln!("aborted: inventory not modified");
            return Ok(ExitCode::SUCCESS);
        }
        let mut removed = 0usize;
        for c in &report.candidates {
            if inv.remove_package(&c.package) {
                removed += 1;
            }
        }
        sandogasa_inventory::save(&inv, path).map_err(|e| format!("saving {path}: {e}"))?;
        eprintln!("removed {removed} package(s) from {path}");
        return Ok(ExitCode::SUCCESS);
    }

    let changed =
        prune_retired::apply_unshipped_marks(&mut inv, &report.checked, &report.candidates);
    if changed == 0 {
        eprintln!("unshipped markers already up to date");
        return Ok(ExitCode::SUCCESS);
    }
    if !args.yes
        && !triage_updates::confirm(&format!(
            "Update unshipped markers on {changed} package(s) in {path}?"
        ))?
    {
        eprintln!("aborted: inventory not modified");
        return Ok(ExitCode::SUCCESS);
    }
    sandogasa_inventory::save(&inv, path).map_err(|e| format!("saving {path}: {e}"))?;
    eprintln!("updated unshipped markers on {changed} package(s) in {path}");
    Ok(ExitCode::SUCCESS)
}

fn cmd_triage_retired(paths: &[String], args: &TriageRetiredArgs) -> CmdResult {
    // --mark writes results back, which only makes sense for a
    // single inventory file (a merged view has no single home).
    if args.mark && paths.len() != 1 {
        return Err(format!(
            "--mark needs exactly one inventory file (got {})",
            paths.len()
        )
        .into());
    }
    let inventory = sandogasa_inventory::load_and_merge(paths)?;
    let api_key = config::resolve_api_key(args.api_key.as_deref())?;
    let url = config::resolve_url();
    let bz = sandogasa_bugzilla::BzClient::new(&url).with_api_key(api_key)?;
    let dg = sandogasa_distgit::DistGitClient::new();

    let claim_email = config::resolve_email();
    if args.claim && claim_email.is_none() {
        return Err("--claim needs a configured Bugzilla email.\n\
             Set it with: poi-tracker config"
            .into());
    }

    let batch_email = resolve_batch_email(&args.batch)?;
    let rt = new_runtime()?;
    let report = rt.block_on(triage_retired::run(
        &inventory,
        &bz,
        &dg,
        &args.branch,
        args.all_reporters,
        &args.filter,
        batch_email.as_deref(),
        args.claim,
        claim_email.as_deref(),
        args.dry_run,
        args.yes,
        args.verbose,
    ))?;
    eprintln!(
        "\n{} checked, {} retired, {} planned, {} closed, {} failed",
        report.packages_checked,
        report.packages_retired,
        report.closes_planned,
        report.closes_applied,
        report.failures
    );
    // Record the retirement checks in the inventory. The facts
    // were gathered regardless of whether any bug closures were
    // confirmed, so marking is independent of the close outcome.
    if args.mark {
        let path = &paths[0];
        let mut inv = sandogasa_inventory::load(path)
            .map_err(|e| format!("reloading {path} for --mark: {e}"))?;
        let changed = triage_retired::apply_retirement_marks(&mut inv, &report.checks);
        if changed > 0 {
            sandogasa_inventory::save(&inv, path).map_err(|e| format!("saving {path}: {e}"))?;
            eprintln!("marked {changed} package(s) in {path}");
        } else {
            eprintln!("retirement markers already up to date");
        }
    }
    Ok(if report.failures > 0 {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    })
}

fn cmd_intersect(paths: &[String], args: &IntersectArgs) -> CmdResult {
    let base = sandogasa_inventory::load_and_merge(paths)?;
    // Names only — reading the filter files independently avoids
    // load_and_merge's per-package reason-conflict warnings, which
    // are meaningless for a name filter.
    let mut filter: std::collections::BTreeSet<String> = Default::default();
    for path in &args.with {
        filter.extend(
            sandogasa_inventory::load(path)?
                .package
                .into_iter()
                .map(|p| p.name),
        );
    }
    let meta = base.inventory.clone();
    let packages = intersect::intersect(base, &filter);

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "packages": packages.iter().map(|p| &p.name).collect::<Vec<_>>(),
                "count": packages.len(),
                "output": args.output,
            }))?
        );
        if let Some(path) = &args.output {
            intersect::merge_packages(path, packages, &meta)?;
        }
        return Ok(ExitCode::SUCCESS);
    }

    println!("{} package(s) in the intersection", packages.len());
    for pkg in &packages {
        match &pkg.reason {
            Some(reason) => println!("  {} — {}", pkg.name, reason),
            None => println!("  {}", pkg.name),
        }
    }
    if let Some(path) = &args.output {
        let added = intersect::merge_packages(path, packages, &meta)?;
        println!("merged into {path} ({added} new)");
    }
    Ok(ExitCode::SUCCESS)
}

/// Walk the cull inventory's verdicts (`-i`) and enact them one
/// confirmed action at a time. Interactive only — this changes
/// ownership on a server, so there is no bulk mode.
fn cmd_act(paths: &[String], args: &ActArgs) -> CmdResult {
    use std::io::{IsTerminal, Write};

    if !std::io::stdin().is_terminal() {
        return Err("act is interactive-only: each ACL change needs a confirmation".into());
    }
    sandogasa_cli::require_tools(&[("fedrq", "sudo dnf install fedrq", Some("--version"))])?;
    let token = config::resolve_distgit_token(args.api_token.as_deref())?;

    let mut names: Vec<String> = Vec::new();
    for path in paths {
        names.extend(
            sandogasa_inventory::load(path)?
                .package
                .into_iter()
                .map(|p| p.name),
        );
    }
    names.sort();
    names.dedup();
    names.retain(|name| args.filter.matches(name));
    let (culled, warnings) =
        classify_with_cache(&args.user, &names, args.refresh_acls, args.verbose)?;
    for warning in &warnings {
        eprintln!("warning: {warning}");
    }

    let client = DistGitClient::new().with_token(token)?;
    let rt = new_runtime()?;
    // Fail in seconds on a bad token rather than at the first give,
    // deep into the walk. A valid token can still lack the ACL scope
    // for changing ownership; the per-action errors now carry
    // Pagure's own message when that happens.
    match rt.block_on(client.verify_token()) {
        Ok(who) => eprintln!("authenticated as {who}"),
        Err(e) => {
            return Err(format!(
                "dist-git token check failed: {e}\n\
                 orphaning and giving need an account token with the \
                 \"Modify an existing project\" ACL — regenerate one at \
                 https://src.fedoraproject.org/settings#nav-api-tab"
            )
            .into());
        }
    }
    let total = culled.len();
    let mut enacted: Vec<String> = Vec::new();
    let mut skipped = 0usize;
    let mut unculled = 0usize;
    let read_line = || -> Result<String, String> {
        let mut line = String::new();
        std::io::stdin()
            .read_line(&mut line)
            .map_err(|e| format!("reading input: {e}"))?;
        Ok(line)
    };
    'walk: for (i, c) in culled.iter().enumerate() {
        let idx = i + 1;
        let orphanable = matches!(c.action, kondo::Action::Orphan);
        let actionable = orphanable || matches!(c.action, kondo::Action::SelfRemove);
        println!("[{idx}/{total}] {} ({})", c.name, c.level);
        if !actionable {
            println!("  nothing to self-enact — ask to be removed (or uncull)");
        }
        let mut hard_dependents = false;
        if orphanable {
            // Orphaning starts the retirement clock; retiring a
            // package something requires strands its dependents, so
            // look before every leap — features included, on the
            // branches this package actually lives on.
            let branches = match args.branch.as_slice() {
                [auto] if auto == "auto" => match rt.block_on(client.project_branches(&c.name)) {
                    Ok(Some(git)) => {
                        let derived = act::probe_branches(&git);
                        if derived.is_empty() {
                            println!("  no probeable branch (git has: {})", git.join(", "));
                        }
                        derived
                    }
                    Ok(None) => {
                        println!("  no such dist-git project — probing rawhide anyway");
                        vec!["rawhide".to_string()]
                    }
                    Err(e) => {
                        println!("  branch listing failed ({e}) — probing rawhide anyway");
                        vec!["rawhide".to_string()]
                    }
                },
                _ => args.branch.clone(),
            };
            for branch in &branches {
                match act::probe_dependents(branch, &c.name) {
                    Ok(act::Probe::Absent) => {
                        println!("  not present on {branch}");
                    }
                    Ok(act::Probe::Dependents(deps)) if deps.is_empty() => {
                        println!("  no {branch} dependents");
                    }
                    Ok(act::Probe::Dependents(deps)) => {
                        let rendered: Vec<String> = deps
                            .iter()
                            .map(|d| match d.feature_only {
                                true => format!("{} (optional feature)", d.source),
                                false => d.source.clone(),
                            })
                            .collect();
                        if deps.iter().all(|d| d.feature_only) {
                            println!(
                                "  {branch} dependents, all via optional features \
                                 (likely severable): {}",
                                rendered.join(", ")
                            );
                        } else {
                            hard_dependents = true;
                            println!(
                                "  {branch} dependents: {} — orphaning starts the \
                                 retirement clock for them",
                                rendered.join(", ")
                            );
                        }
                    }
                    Err(e) => {
                        hard_dependents = true;
                        println!("  {branch} probe failed ({e}) — assume it has dependents");
                    }
                }
            }
        }
        let choices = act::menu(
            actionable,
            orphanable,
            if orphanable {
                "orphan"
            } else {
                "remove my ACL"
            },
        );
        let menu = sandogasa_review::Menu {
            choices: &choices,
            default: Some('s'),
            all: false,
            quit: false,
            default_arg: None,
        };
        loop {
            let choice = act::from_answer(sandogasa_review::ask("", &menu)?);
            let outcome = match &choice {
                act::Choice::Skip => {
                    skipped += 1;
                    break;
                }
                act::Choice::Quit => break 'walk,
                act::Choice::Uncull(into) => {
                    if let Some(inventory) = into {
                        match kondo::file_into_inventory(inventory, &c.name, &args.user) {
                            Ok(true) => println!(
                                "  filed into {inventory} — not in the dependency graph yet: \
                                 `keep {}` records its edges",
                                c.name
                            ),
                            Ok(false) => println!("  already in {inventory}"),
                            Err(e) => {
                                println!("  could not add to {inventory}: {e} — verdict kept");
                                skipped += 1;
                                break;
                            }
                        }
                    } else {
                        println!("  unculled — returns to candidacy on the next kondo run");
                    }
                    let gone: std::collections::BTreeSet<&str> = [c.name.as_str()].into();
                    for path in paths {
                        unkeep::remove_from_inventory(path, &gone)?;
                    }
                    unculled += 1;
                    break;
                }
                act::Choice::Enact if orphanable => {
                    // A hard dependent means retirement would strand
                    // it; make the operator say so twice.
                    if hard_dependents {
                        print!("  a package still hard-depends on this — orphan anyway? [y/N] ");
                        let _ = std::io::stdout().flush();
                        if !matches!(
                            read_line()?.trim().to_ascii_lowercase().as_str(),
                            "y" | "yes"
                        ) {
                            println!("  kept");
                            skipped += 1;
                            break;
                        }
                    }
                    rt.block_on(client.give_package(&c.name, "orphan"))
                }
                act::Choice::Enact => rt.block_on(client.remove_acl(&c.name, "user", &args.user)),
                act::Choice::Give(fas) => match rt.block_on(client.user_exists(fas)) {
                    Ok(true) => rt.block_on(client.give_package(&c.name, fas)),
                    Ok(false) => {
                        println!("  no such user: {fas}");
                        continue;
                    }
                    // The user endpoint 503s for prolific packagers —
                    // exactly the people who receive packages — so an
                    // unverifiable recipient is not a blocked one:
                    // Pagure validates main_admin on the give itself.
                    Err(e) => {
                        println!(
                            "  could not verify {fas} ({e}); Pagure will reject an unknown user"
                        );
                        rt.block_on(client.give_package(&c.name, fas))
                    }
                },
            };
            match outcome {
                Ok(()) => {
                    let did = match &choice {
                        act::Choice::Give(fas) => format!("gave to {fas}"),
                        _ if orphanable => "orphaned".to_string(),
                        _ => "removed own ACL".to_string(),
                    };
                    println!("  {did}");
                    // Adjust the books immediately, so an interrupted
                    // walk loses nothing already enacted.
                    let gone: std::collections::BTreeSet<&str> = [c.name.as_str()].into();
                    for path in paths {
                        unkeep::remove_from_inventory(path, &gone)?;
                    }
                    if let Some(personal) = &args.personal {
                        unkeep::remove_from_inventory(personal, &gone)?;
                    }
                    enacted.push(c.name.clone());
                    break;
                }
                Err(e) => {
                    println!("  failed: {e} — verdict kept");
                    skipped += 1;
                    break;
                }
            }
        }
    }
    println!(
        "
enacted {} package(s), unculled {}, skipped {}; {} verdict(s) remain in the cull inventory",
        enacted.len(),
        unculled,
        skipped,
        total - enacted.len() - unculled,
    );
    Ok(ExitCode::SUCCESS)
}

/// Render the standing verdicts of a cull inventory (`-i`) as the
/// same grouped report kondo prints for a single run — the artifact
/// the act phase posts to the mailing list. Levels come from
/// re-classification (cache first), never from the reason text,
/// which is user-customizable.
fn cmd_announce(paths: &[String], args: &AnnounceArgs) -> CmdResult {
    let mut names: Vec<String> = Vec::new();
    for path in paths {
        names.extend(
            sandogasa_inventory::load(path)?
                .package
                .into_iter()
                .map(|p| p.name),
        );
    }
    names.sort();
    names.dedup();
    let (culled, warnings) =
        classify_with_cache(&args.user, &names, args.refresh_acls, args.verbose)?;
    let report = kondo::KondoReport {
        candidates: names.len(),
        culled,
        warnings,
        ..Default::default()
    };
    if args.json {
        println!("{}", serde_json::to_string_pretty(&report)?);
        return Ok(ExitCode::SUCCESS);
    }
    print!("{}", kondo::format_report(&report, &args.user));
    for warning in &report.warnings {
        eprintln!("warning: {warning}");
    }
    Ok(ExitCode::SUCCESS)
}

/// Classify `names` by the user's own access level: day-fresh cache
/// answers first, dist-git covers the rest, and successful lookups
/// refresh the cache. Shared by kondo (triage) and announce (render).
fn classify_with_cache(
    user: &str,
    names: &[String],
    refresh_acls: bool,
    verbose: bool,
) -> Result<(Vec<kondo::Culled>, Vec<String>), Box<dyn std::error::Error>> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let mut cache = kondo::AclCache::load(kondo::AclCache::default_path());
    let mut by_name: BTreeMap<String, kondo::Culled> = Default::default();
    let mut to_lookup: Vec<String> = Vec::new();
    for name in names {
        match (!refresh_acls)
            .then(|| cache.fresh(user, name, now))
            .flatten()
        {
            Some(hit) => {
                by_name.insert(name.clone(), kondo::culled_from_level(name, &hit.level));
            }
            None => to_lookup.push(name.clone()),
        }
    }
    eprintln!(
        "checking dist-git access for {} candidate(s) ({} from cache)...",
        to_lookup.len(),
        by_name.len(),
    );
    let dg = sandogasa_distgit::DistGitClient::new();
    let rt = new_runtime()?;
    let (looked_up, warnings) = rt.block_on(kondo::classify(&dg, user, &to_lookup, verbose));
    for c in looked_up {
        if c.level != "unknown" {
            cache.remember(user, &c.name, c.level.clone(), now);
        }
        by_name.insert(c.name.clone(), c);
    }
    if let Some(warning) = cache.save() {
        eprintln!("warning: {warning}");
    }
    let classified = names.iter().filter_map(|n| by_name.remove(n)).collect();
    Ok((classified, warnings))
}

fn cmd_kondo(paths: &[String], args: &KondoArgs) -> CmdResult {
    use std::io::IsTerminal;

    let personal = sandogasa_inventory::load_and_merge(paths)?;
    let (essential_paths, note) =
        kondo::essential_paths_to_load(&args.essential, args.explain_into.as_deref());
    if let Some(note) = &note {
        eprintln!("note: {note}");
    }
    // Only the names matter for a set difference, so the essential
    // files are read independently rather than merged — merging
    // warns per reason conflict, and the same crate legitimately
    // carries different reasons in an el9 deps inventory and a
    // rawhide one. On the first real run those warnings buried the
    // rescue report.
    let mut essential_names: std::collections::BTreeSet<String> = Default::default();
    for path in &essential_paths {
        essential_names.extend(
            sandogasa_inventory::load(path)?
                .package
                .into_iter()
                .map(|p| p.name),
        );
    }

    let mut candidates = kondo::cull_candidates(&personal, &essential_names);
    candidates.retain(|name| args.filter.matches(name));
    candidates.sort();
    // The cull inventory is the accumulated verdict — but essential
    // inputs can improve between passes (deps --build justifying a
    // crate stack), so anything on it that is now essential gets
    // rescued first, then what remains decided is not re-asked.
    let rescued = match &args.output {
        Some(path) => kondo::rescue_culled(path, &essential_names)?,
        None => Vec::new(),
    };
    if !rescued.is_empty() {
        eprintln!(
            "rescued {} package(s) from the cull list (now essential): {}",
            rescued.len(),
            rescued.join(", "),
        );
    }
    let prior = match &args.output {
        Some(path) => kondo::prior_culled(path)?,
        None => Default::default(),
    };
    let before = candidates.len();
    candidates.retain(|name| !prior.contains(name));
    let mut report = kondo::KondoReport {
        candidates: candidates.len(),
        previously_culled: before - candidates.len(),
        rescued,
        ..Default::default()
    };
    if report.previously_culled > 0 {
        eprintln!(
            "skipping {} candidate(s) already culled in {}",
            report.previously_culled,
            args.output.as_deref().unwrap_or_default(),
        );
    }
    if candidates.is_empty() {
        if args.json {
            println!("{}", serde_json::to_string_pretty(&report)?);
        } else if report.previously_culled > 0 {
            println!(
                "Nothing new to triage: every remaining candidate ({}) was \
                 culled in an earlier pass.",
                report.previously_culled
            );
        } else {
            println!("Every package is in an essential inventory; nothing to triage.");
        }
        return Ok(ExitCode::SUCCESS);
    }

    // Access levels first: they contextualize the prompt (a mere
    // committer reads differently from an owner), and the kept
    // candidates come out already classified. Day-fresh answers come
    // from the cache; only the rest go to dist-git.
    let (classified, warnings) =
        classify_with_cache(&args.user, &candidates, args.refresh_acls, args.verbose)?;
    report.warnings.extend(warnings);

    // Prompt only where the house rules allow it; otherwise every
    // candidate stays a candidate, which acts on nothing.
    let interactive = !args.yes && !args.json && std::io::stdin().is_terminal();
    let resolutions = if interactive {
        eprintln!(
            "{} candidate(s). cull = confirm it as a cull candidate; essential = \
             file it into an inventory (`e path.toml` in one line, or `e` then \
             the path); skip = leave it undecided for now (it comes back next run).",
            classified.len()
        );
        sandogasa_review::resolve(
            classified,
            kondo::triage_summary,
            &sandogasa_review::Prompt {
                vocab: kondo::CULL_VOCABULARY,
                default_explanation: args.explain_into.as_deref(),
                notes: true,
            },
        )?
    } else {
        classified
            .into_iter()
            .map(|c| (c, sandogasa_review::Resolution::Keep, None))
            .collect()
    };
    kondo::apply_resolutions(resolutions, &personal.inventory.maintainer, &mut report);

    let written = if let Some(path) = &args.output {
        let added = kondo::merge_culled(
            path,
            &report,
            &format!("{}-cull", personal.inventory.name),
            &personal.inventory.maintainer,
            args.reason.as_deref(),
        )?;
        Some((path.clone(), added))
    } else {
        None
    };

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "report": report,
                "output": written.as_ref().map(|(p, _)| p),
                "output_added": written.as_ref().map(|(_, n)| n),
            }))?
        );
        return Ok(ExitCode::SUCCESS);
    }
    print!("{}", kondo::format_report(&report, &args.user));
    if !report.rescued.is_empty() {
        println!(
            "rescued earlier this run ({} package(s), now essential): {}",
            report.rescued.len(),
            report.rescued.join(", "),
        );
    }
    for (name, inv) in &report.explained {
        println!("filed {name} → {inv}");
    }
    if !report.removed.is_empty() {
        println!(
            "skipped, undecided until next run: {}",
            report.removed.join(", ")
        );
    }
    for warning in &report.warnings {
        eprintln!("warning: {warning}");
    }
    if let Some((path, added)) = written {
        println!("merged into {path} ({added} new)");
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_deps(paths: &[String], args: &DepsArgs) -> CmdResult {
    sandogasa_cli::require_tools(&[("fedrq", "sudo dnf install fedrq", Some("--version"))])?;
    let inventory = sandogasa_inventory::load_and_merge(paths)?;
    let roots: Vec<String> = inventory
        .package
        .iter()
        .filter(|p| !p.is_unshipped() && args.filter.matches(&p.name))
        .map(|p| p.name.clone())
        .collect();
    if roots.is_empty() {
        return Err("no shipped packages match the filters".into());
    }

    let fedrq = sandogasa_fedrq::Fedrq {
        branch: Some(args.walk.branch.clone()),
        repo: args.walk.repo.clone(),
    };
    let from: std::collections::BTreeSet<String> = args.walk.from.iter().cloned().collect();
    let own: Option<std::collections::BTreeSet<String>> = match &args.fixpoint {
        Some(path) => Some(
            sandogasa_inventory::load(path)?
                .package
                .into_iter()
                .map(|p| p.name)
                .collect(),
        ),
        None => None,
    };
    let (report, graph) = deps::walk(
        &fedrq,
        &roots,
        &deps::WalkOpts {
            from: &from,
            base_prefixes: &args.walk.base_repo,
            build: !args.walk.runtime_only,
            fixpoint_own: own.as_ref(),
            verbose: args.verbose,
        },
    )?;
    // A closure without its graph strands the offline commands
    // (unkeep, dependents) a walk behind, so writing an inventory
    // always writes the graph beside it; --graph only moves it.
    let graph_path = args.graph.clone().or_else(|| {
        args.output
            .as_ref()
            .map(|o| format!("{}-graph.json", o.strip_suffix(".toml").unwrap_or(o)))
    });
    if let Some(path) = &graph_path {
        std::fs::write(path, serde_json::to_vec_pretty(&graph)?)
            .map_err(|e| format!("writing {path}: {e}"))?;
    }

    let name = args
        .name
        .clone()
        .unwrap_or_else(|| format!("{}-deps-{}", inventory.inventory.name, args.walk.branch));
    let written = if let Some(path) = &args.output {
        let kind = if args.walk.runtime_only {
            "Runtime dependencies"
        } else {
            "Runtime and build dependencies"
        };
        let description = format!(
            "{kind} of inventory '{}' from repos [{}], \
             resolved with fedrq -b {}{}. Generated by poi-tracker deps.",
            inventory.inventory.name,
            args.walk.from.join(", "),
            args.walk.branch,
            args.walk
                .repo
                .as_deref()
                .map(|r| format!(" -r {r}"))
                .unwrap_or_default(),
        );
        let out = deps::to_inventory(
            &report,
            &name,
            &description,
            &inventory.inventory.maintainer,
        );
        sandogasa_inventory::save(&out, path)?;
        Some(path.clone())
    } else {
        None
    };

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "branch": args.walk.branch,
                "repo": args.walk.repo,
                "from": args.walk.from,
                "report": report,
                "output": written,
                "graph": graph_path,
            }))?
        );
        return Ok(ExitCode::SUCCESS);
    }

    println!(
        "{} runtime dependenc{} from [{}] for {} package(s) on {} \
         ({} binaries, {} wave(s), {:.0}s):",
        report.collected.len(),
        if report.collected.len() == 1 {
            "y"
        } else {
            "ies"
        },
        args.walk.from.join(", "),
        report.roots,
        args.walk.branch,
        report.binaries_walked,
        report.waves,
        report.elapsed_secs,
    );
    for dep in &report.collected {
        if dep.via.is_empty() {
            println!("  {} ({})", dep.source, dep.repoid);
        } else {
            println!(
                "  {} ({}) — {} requires {}",
                dep.source, dep.repoid, dep.required_by, dep.via
            );
        }
    }
    for warning in &report.warnings {
        eprintln!("warning: {warning}");
    }
    if !report.unmatched.is_empty() {
        eprintln!(
            "warning: {} capabilit{} could not be tied to a provider (--json lists them)",
            report.unmatched.len(),
            if report.unmatched.len() == 1 {
                "y"
            } else {
                "ies"
            },
        );
    }
    if let Some(path) = written {
        println!("wrote {path}");
    }
    if let Some(path) = graph_path {
        println!("wrote graph to {path}");
    }
    Ok(ExitCode::SUCCESS)
}

/// Classify the `-i` inventories' packages by their dependents in a
/// saved deps graph — the pruning report for shrinking a keep set.
fn cmd_dependents(paths: &[String], args: &DependentsArgs) -> CmdResult {
    let bytes = std::fs::read(&args.graph).map_err(|e| format!("reading {}: {e}", args.graph))?;
    let graph: deps::DepsGraph =
        serde_json::from_slice(&bytes).map_err(|e| format!("parsing {}: {e}", args.graph))?;
    let mut names: std::collections::BTreeSet<String> = Default::default();
    for path in paths {
        names.extend(
            sandogasa_inventory::load(path)?
                .package
                .into_iter()
                .map(|p| p.name),
        );
    }
    let report = dependents::classify(&graph, &names);
    if args.json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print!("{}", dependents::format_report(&report));
    }
    Ok(ExitCode::SUCCESS)
}

/// Replace `output`'s packages with a derived report's, keeping its
/// header (or borrowing `meta_from`'s when the file is new).
fn apply_derived(
    output: &str,
    meta_from: &str,
    report: &derive::DeriveReport,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut inventory = match std::path::Path::new(output).exists() {
        true => sandogasa_inventory::load(output)?,
        false => sandogasa_inventory::Inventory {
            inventory: sandogasa_inventory::load(meta_from)?.inventory,
            package: Vec::new(),
        },
    };
    inventory.package = report
        .derived
        .iter()
        .map(|d| sandogasa_inventory::Package {
            name: d.name.clone(),
            reason: d.reason.clone(),
            ..Default::default()
        })
        .collect();
    sandogasa_inventory::save(&inventory, output)?;
    Ok(())
}

/// Recompute a derived inventory (owned ∩ reachable-from-keeps) from
/// a saved graph — the global `-i` inventories are the keeps.
fn cmd_derive(paths: &[String], args: &DeriveArgs) -> CmdResult {
    use std::collections::BTreeSet;

    let bytes = std::fs::read(&args.graph).map_err(|e| format!("reading {}: {e}", args.graph))?;
    let graph: deps::DepsGraph =
        serde_json::from_slice(&bytes).map_err(|e| format!("parsing {}: {e}", args.graph))?;
    let names_of = |path: &str| -> Result<BTreeSet<String>, String> {
        Ok(sandogasa_inventory::load(path)?
            .package
            .into_iter()
            .map(|p| p.name)
            .collect())
    };
    let mut keeps: BTreeSet<String> = Default::default();
    for path in paths {
        keeps.extend(names_of(path)?);
    }
    let owned = names_of(&args.owned)?;
    let current = match std::path::Path::new(&args.output).exists() {
        true => names_of(&args.output)?,
        false => Default::default(),
    };

    let report = derive::derive(&graph, &keeps, &owned, &current);
    if args.apply {
        apply_derived(&args.output, &paths[0], &report)?;
    }
    if args.json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print!("{}", derive::format_report(&report, args.apply));
    }
    Ok(ExitCode::SUCCESS)
}

/// Start keeping packages: an incremental walk from the new roots
/// over a graph-backed query (offline for every capability the saved
/// graph knows, fedrq for the frontier), merged into the stored graph,
/// the names filed into a keep inventory, and the derived inventory
/// recomputed — the add half of incremental maintenance.
fn cmd_keep(paths: &[String], args: &KeepArgs) -> CmdResult {
    use std::collections::BTreeSet;
    use std::sync::atomic::Ordering::Relaxed;

    sandogasa_cli::require_tools(&[("fedrq", "sudo dnf install fedrq", Some("--version"))])?;
    let bytes = std::fs::read(&args.graph).map_err(|e| format!("reading {}: {e}", args.graph))?;
    let mut graph: deps::DepsGraph =
        serde_json::from_slice(&bytes).map_err(|e| format!("parsing {}: {e}", args.graph))?;
    let names_of = |path: &str| -> Result<BTreeSet<String>, String> {
        Ok(sandogasa_inventory::load(path)?
            .package
            .into_iter()
            .map(|p| p.name)
            .collect())
    };
    let mut keeps: BTreeSet<String> = Default::default();
    for path in paths {
        keeps.extend(names_of(path)?);
    }
    for name in &args.names {
        if keeps.contains(name) {
            eprintln!(
                "note: {name} is already a keep; walking it to record its edges, not re-filing"
            );
        }
    }
    let owned = names_of(&args.owned)?;

    let fedrq = sandogasa_fedrq::Fedrq {
        branch: Some(args.walk.branch.clone()),
        repo: args.walk.repo.clone(),
    };
    let query = deps::GraphBackedQuery::new(&fedrq, &graph);
    let from: BTreeSet<String> = args.walk.from.iter().cloned().collect();
    let (report, new_graph) = deps::walk(
        &query,
        &args.names,
        &deps::WalkOpts {
            from: &from,
            base_prefixes: &args.walk.base_repo,
            build: !args.walk.runtime_only,
            fixpoint_own: Some(&owned),
            verbose: args.verbose,
        },
    )?;
    let (offline, online) = (query.offline.load(Relaxed), query.online.load(Relaxed));
    graph.merge(new_graph);
    std::fs::write(&args.graph, serde_json::to_vec_pretty(&graph)?)
        .map_err(|e| format!("writing {}: {e}", args.graph))?;

    let into = args.into.clone().unwrap_or_else(|| paths[0].clone());
    let maintainer = sandogasa_inventory::load(&paths[0])?.inventory.maintainer;
    let mut filed = 0usize;
    for name in args.names.iter().filter(|n| !keeps.contains(*n)) {
        // A keep already held by another -i inventory must not be
        // duplicated into --into: the keep set is their union.
        if kondo::file_into_inventory(&into, name, &maintainer)? {
            filed += 1;
        }
    }
    keeps.extend(args.names.iter().cloned());

    let derived = match &args.deps {
        Some(path) => {
            let current = match std::path::Path::new(path).exists() {
                true => names_of(path)?,
                false => Default::default(),
            };
            let d = derive::derive(&graph, &keeps, &owned, &current);
            apply_derived(path, &paths[0], &d)?;
            Some(d)
        }
        None => None,
    };
    // The closure inventory is the same view for the packages that
    // are not owned; recomputed here too, so a kondo run before the
    // next reconcile sees what this walk taught the graph.
    let closure = match &args.output {
        Some(path) => {
            let current = match std::path::Path::new(path).exists() {
                true => names_of(path)?,
                false => Default::default(),
            };
            let from: BTreeSet<String> = args.walk.from.iter().cloned().collect();
            let owned_elsewhere = args.deps.is_some().then_some(&owned);
            let cl = derive::closure(
                &graph,
                &keeps,
                owned_elsewhere,
                &current,
                &from,
                &args.walk.base_repo,
            );
            derive::apply_merge(path, &paths[0], &cl)?;
            Some(cl)
        }
        None => None,
    };

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "report": report,
                "graph": args.graph,
                "resolved_offline": offline,
                "resolved_online": online,
                "filed_into": into,
                "derived": derived,
                "closure": closure,
            }))?
        );
        return Ok(ExitCode::SUCCESS);
    }
    println!(
        "kept {} package(s): {} collected dependenc{}, {} wave(s), {:.0}s — \
         {} capabilit{} answered from the graph, {} resolved live",
        args.names.len(),
        report.collected.len(),
        if report.collected.len() == 1 {
            "y"
        } else {
            "ies"
        },
        report.waves,
        report.elapsed_secs,
        offline,
        if offline == 1 { "y" } else { "ies" },
        online,
    );
    println!("filed {filed} into {into}; graph updated at {}", args.graph);
    if let Some(d) = &derived {
        print!("{}", derive::format_report(d, true));
    }
    if let Some(cl) = &closure {
        print!(
            "{}",
            derive::format_report_of("closure inventory", cl, true)
        );
    }
    for warning in &report.warnings {
        eprintln!("warning: {warning}");
    }
    Ok(ExitCode::SUCCESS)
}

/// The `-C DIR` / `--directory DIR` value in `argv`, if given (also
/// `--directory=DIR`); the first occurrence wins.
fn directory_flag(
    argv: impl IntoIterator<Item = std::ffi::OsString>,
) -> Option<std::ffi::OsString> {
    let mut it = argv.into_iter().skip(1);
    while let Some(arg) = it.next() {
        let s = arg.to_string_lossy();
        if s == "-C" || s == "--directory" {
            return it.next();
        }
        if let Some(rest) = s.strip_prefix("--directory=") {
            return Some(rest.to_string().into());
        }
        if let Some(rest) = s.strip_prefix("-C").filter(|r| !r.is_empty()) {
            return Some(rest.to_string().into());
        }
    }
    None
}

/// The maintenance loop over the workspace: see [`reconcile`].
fn cmd_reconcile(workspace: Option<&str>, args: &ReconcileArgs) -> CmdResult {
    use std::io::IsTerminal;

    let Some((ws, path)) = workspace::Workspace::find(workspace)? else {
        return Err(
            "reconcile needs a workspace file: pass -w PATH or run where ./kondo.toml is".into(),
        );
    };
    let resolve = |p: &str| ws.dir.join(p).to_string_lossy().into_owned();
    let opts = reconcile::Options {
        ws: &ws,
        into: args.into.clone(),
        yes: args.yes || args.dry_run,
        json: args.json,
        verbose: args.verbose,
        dry_run: args.dry_run,
    };
    if !args.json {
        println!("reconciling workspace {}", path.display());
    }
    let report = reconcile::run(&opts)?;
    if args.json {
        println!("{}", serde_json::to_string_pretty(&report)?);
        return Ok(ExitCode::SUCCESS);
    }
    if args.dry_run {
        println!(
            "dry run: {} owned package(s) would go to the triage",
            report.triage_candidates.len()
        );
        return Ok(ExitCode::SUCCESS);
    }
    if report.triage_candidates.is_empty() {
        println!("nothing left to triage: every owned package is justified or already culled");
        return Ok(ExitCode::SUCCESS);
    }
    let (Some(owned), Some(user)) = (ws.owned.as_deref().map(resolve), ws.user.clone()) else {
        println!(
            "{} package(s) to triage, but the workspace names no `user`: run `poi-tracker kondo --user NAME`",
            report.triage_candidates.len()
        );
        return Ok(ExitCode::SUCCESS);
    };
    println!(
        "
{} owned package(s) no essential inventory justifies — triaging with kondo",
        report.triage_candidates.len()
    );
    let kondo_args = KondoArgs {
        filter: WalkFilterArgs::default(),
        essential: ws.essential().iter().map(|p| resolve(p)).collect(),
        user,
        explain_into: None,
        yes: args.yes || !std::io::stdin().is_terminal(),
        refresh_acls: args.refresh_acls,
        reason: None,
        output: ws.cull.as_deref().map(resolve),
        json: false,
        verbose: args.verbose,
    };
    cmd_kondo(&[owned], &kondo_args)
}

/// Report (and with `--apply`, enact) what unkeeping packages frees,
/// over a saved deps graph instead of a fresh walk. The global `-i`
/// inventories are the keeps; `--deps` names the derived inventories
/// freed packages leave.
fn cmd_unkeep(paths: &[String], args: &UnkeepArgs) -> CmdResult {
    use std::collections::BTreeSet;

    let bytes = std::fs::read(&args.graph).map_err(|e| format!("reading {}: {e}", args.graph))?;
    let graph: deps::DepsGraph =
        serde_json::from_slice(&bytes).map_err(|e| format!("parsing {}: {e}", args.graph))?;
    let load_names = |path: &String| -> Result<(String, BTreeSet<String>), String> {
        Ok((
            path.clone(),
            sandogasa_inventory::load(path)?
                .package
                .into_iter()
                .map(|p| p.name)
                .collect(),
        ))
    };
    let keeps: BTreeMap<String, BTreeSet<String>> =
        paths.iter().map(&load_names).collect::<Result<_, _>>()?;
    let deps_files: BTreeMap<String, BTreeSet<String>> = args
        .deps
        .iter()
        .map(&load_names)
        .collect::<Result<_, _>>()?;

    let report = unkeep::plan(&graph, &args.names, &keeps, &deps_files);
    if args.apply {
        let unkept: BTreeSet<&str> = args.names.iter().map(String::as_str).collect();
        for (file, pkgs) in &keeps {
            if args.names.iter().any(|n| pkgs.contains(n)) {
                unkeep::remove_from_inventory(file, &unkept)?;
            }
        }
        let freed: BTreeSet<&str> = report.freed.iter().map(|f| f.name.as_str()).collect();
        for (file, pkgs) in &deps_files {
            if report.freed.iter().any(|f| pkgs.contains(&f.name)) {
                unkeep::remove_from_inventory(file, &freed)?;
            }
        }
        // Still-reached keeps are provably in the closure, so they
        // move into the derived inventory right away — the reason
        // chain comes from the graph, no fresh walk needed.
        if !report.moved.is_empty() {
            match args.deps.first() {
                Some(dest) => {
                    let packages: Vec<sandogasa_inventory::Package> = report
                        .moved
                        .iter()
                        .map(|(name, reason)| sandogasa_inventory::Package {
                            name: name.clone(),
                            reason: Some(reason.clone()),
                            ..Default::default()
                        })
                        .collect();
                    let meta = sandogasa_inventory::load(&paths[0])?.inventory;
                    intersect::merge_packages(dest, packages, &meta)?;
                }
                None => eprintln!(
                    "warning: {} still-reached package(s) have no --deps \
                     inventory to move into; the next deps walk will \
                     re-derive them",
                    report.moved.len()
                ),
            }
        }
    }
    if args.json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print!("{}", unkeep::format_report(&report, args.apply));
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_config(args: &sandogasa_cli::ConfigArgs) -> CmdResult {
    let rt = new_runtime()?;
    rt.block_on(config::cmd_config(args))?;
    Ok(ExitCode::SUCCESS)
}

fn cmd_triage_updates(paths: &[String], args: &TriageUpdatesArgs) -> CmdResult {
    let inventory = sandogasa_inventory::load_and_merge(paths)?;
    let api_key = config::resolve_api_key(args.api_key.as_deref())?;
    let url = config::resolve_url();
    let client = sandogasa_bugzilla::BzClient::new(&url).with_api_key(api_key)?;

    let rt = new_runtime()?;
    let claim_email = config::resolve_email();
    if args.claim && claim_email.is_none() {
        return Err("--claim needs a configured Bugzilla email.\n\
             Set it with: poi-tracker config"
            .into());
    }
    let batch_email = resolve_batch_email(&args.batch)?;
    let dg = sandogasa_distgit::DistGitClient::new();
    let bodhi = sandogasa_bodhi::BodhiClient::new();
    let koji_lookup = koji_tag_lookup();
    let latest_tagged = match (&koji_lookup, args.skip_stale) {
        (Some(l), false) => Some(l as &triage_updates::TagLookup),
        (None, false) => {
            eprintln!(
                "warning: koji CLI not found; cannot verify builds Bodhi \
                 has no update for — such bugs will be left open. \
                 Install koji to enable the check."
            );
            None
        }
        (_, true) => None,
    };
    let report = rt.block_on(triage_updates::run(
        &inventory,
        &client,
        &dg,
        &bodhi,
        latest_tagged,
        &args.filter,
        batch_email.as_deref(),
        args.skip_stale,
        args.close_stale,
        args.claim,
        claim_email.as_deref(),
        args.dry_run,
        args.yes,
        args.verbose,
    ))?;
    eprintln!(
        "\n{} package(s) with managed priority, {} priority update(s) \
         planned, {} applied; {} stale-bug action(s) planned, {} \
         applied, {} failed",
        report.packages_with_priority,
        report.updates_planned,
        report.updates_applied,
        report.stale_planned,
        report.stale_applied,
        report.failures
    );
    Ok(if report.failures > 0 {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    })
}

fn cmd_show(paths: &[String], args: &ShowArgs) -> CmdResult {
    let inventory = sandogasa_inventory::load_and_merge(paths)?;

    let packages = inventory.packages_for_workload(args.workload.as_deref());

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&packages).expect("JSON serialization failed")
        );
    } else {
        println!(
            "Inventory: {} ({} package(s))\n",
            inventory.inventory.name,
            packages.len()
        );
        for pkg in &packages {
            print!("  {}", pkg.name);
            let wls = inventory.workloads_for_package(&pkg.name);
            if !wls.is_empty() {
                print!(" [{}]", wls.join(", "));
            }
            println!();

            if let Some(ref poc) = pkg.poc {
                println!("    poc: {poc}");
            }
            if let Some(ref reason) = pkg.reason {
                println!("    reason: {reason}");
            }
            if let Some(ref rpms) = pkg.rpms {
                println!("    rpms: {}", rpms.join(", "));
            }
            if let Some(ref track) = pkg.track {
                println!("    track: {track}");
            }
        }
    }

    Ok(ExitCode::SUCCESS)
}

fn cmd_validate(paths: &[String]) -> CmdResult {
    let inventory = sandogasa_inventory::load_and_merge(paths)?;

    let mut errors = 0;

    // Check for duplicate package names.
    let mut seen = std::collections::HashSet::new();
    for pkg in &inventory.package {
        if !seen.insert(&pkg.name) {
            eprintln!("error: duplicate package: {}", pkg.name);
            errors += 1;
        }
    }

    // Check packages are sorted.
    for window in inventory.package.windows(2) {
        if window[0].name > window[1].name {
            eprintln!(
                "warning: packages not sorted: {} before {}",
                window[0].name, window[1].name
            );
        }
    }

    // Check private_fields reference valid field names.
    let valid_fields = ["poc", "reason", "team", "task"];
    for field in &inventory.inventory.private_fields {
        if !valid_fields.contains(&field.as_str()) {
            eprintln!("warning: unknown private field: {field}");
        }
    }

    if errors > 0 {
        eprintln!("\n{errors} error(s) found.");
        Ok(ExitCode::FAILURE)
    } else {
        println!("Inventory OK: {} package(s).", inventory.package.len());
        Ok(ExitCode::SUCCESS)
    }
}

/// Write an export file, labelling the path in the error the way
/// every export site does.
fn write_export(path: &str, content: &str) -> Result<(), String> {
    std::fs::write(path, content).map_err(|e| format!("failed to write {path}: {e}"))
}

fn cmd_export(paths: &[String], args: &ExportArgs) -> CmdResult {
    let inventory = sandogasa_inventory::load_and_merge(paths)?;

    match &args.format {
        ExportFormat::ContentResolver { workload, output } => {
            // Determine which workloads to export.
            let workload_keys: Vec<&str> = match workload {
                Some(w) => vec![w.as_str()],
                None => {
                    let names = inventory.workload_names();
                    if names.is_empty() {
                        // No workloads defined: single-file export.
                        vec![]
                    } else {
                        names
                    }
                }
            };

            if workload_keys.is_empty() {
                // Single-file export (no workloads or --workload).
                let yaml =
                    sandogasa_inventory::content_resolver::export(&inventory, workload.as_deref());
                let default_filename =
                    format!("{}.yaml", inventory.inventory.name.replace(' ', "_"));
                let path = output.as_deref().unwrap_or(&default_filename);
                write_export(path, &yaml)?;
                eprintln!("Wrote {path}");
            } else if workload_keys.len() == 1 {
                // Single workload: respect -o if given.
                let yaml = sandogasa_inventory::content_resolver::export(
                    &inventory,
                    Some(workload_keys[0]),
                );
                let wl_name = workload_export_filename(&inventory, workload_keys[0]);
                let path = output.as_deref().unwrap_or(&wl_name);
                write_export(path, &yaml)?;
                eprintln!("Wrote {path}");
            } else {
                // Multi-workload: one file per workload.
                if output.is_some() {
                    return Err("-o/--output cannot be used when \
                         exporting multiple workloads"
                        .into());
                }
                for key in &workload_keys {
                    let yaml = sandogasa_inventory::content_resolver::export(&inventory, Some(key));
                    let path = workload_export_filename(&inventory, key);
                    write_export(&path, &yaml)?;
                    eprintln!("Wrote {path}");
                }
            }
        }
        ExportFormat::HsRelmon {
            workload,
            distros,
            track,
            output,
            prune,
        } => {
            let defaults = sandogasa_inventory::hs_relmon::RelmonDefaults {
                distros: distros.clone(),
                track: track.clone(),
                file_issue: true,
            };

            if let Some(path) = output
                && std::path::Path::new(path).exists()
            {
                let result = sandogasa_inventory::hs_relmon::merge_into_manifest(
                    path,
                    &inventory,
                    workload.as_deref(),
                    &defaults,
                    *prune,
                )?;

                if !result.stale.is_empty() && !prune {
                    eprintln!(
                        "warning: {} manifest entry/entries not in \
                         inventory (use --prune to remove):",
                        result.stale.len()
                    );
                    for name in &result.stale {
                        eprintln!("  {name}");
                    }
                }

                write_export(path, &result.content)?;

                if !result.unshipped_removed.is_empty() {
                    eprintln!(
                        "removed {} unshipped package(s) from {path}: {}",
                        result.unshipped_removed.len(),
                        result.unshipped_removed.join(", ")
                    );
                }
                let pruned_msg = if result.pruned > 0 {
                    format!(", {} pruned", result.pruned)
                } else {
                    String::new()
                };
                eprintln!(
                    "Merged into {path}: {} new{pruned_msg}, {} total",
                    result.added, result.total
                );
            } else {
                // Fresh export.
                let toml = sandogasa_inventory::hs_relmon::export(
                    &inventory,
                    workload.as_deref(),
                    &defaults,
                );
                if let Some(path) = output {
                    write_export(path, &toml)?;
                    eprintln!("Wrote {path}");
                } else {
                    print!("{toml}");
                }
            }
        }
    }

    Ok(ExitCode::SUCCESS)
}

fn cmd_find(paths: &[String], args: &FindArgs) -> CmdResult {
    let mut found = false;
    for path in paths {
        let inventory = match sandogasa_inventory::load(path) {
            Ok(inv) => inv,
            Err(e) => {
                eprintln!("warning: {path}: {e}");
                continue;
            }
        };
        if let Some(pkg) = inventory.find_package(&args.name) {
            found = true;
            println!("{path}: {}", pkg.name);
            if let Some(ref poc) = pkg.poc {
                println!("  poc: {poc}");
            }
            if let Some(ref reason) = pkg.reason {
                println!("  reason: {reason}");
            }
            if let Some(ref rpms) = pkg.rpms {
                println!("  rpms: {}", rpms.join(", "));
            }
            let wls = inventory.workloads_for_package(&pkg.name);
            if !wls.is_empty() {
                println!("  workloads: {}", wls.join(", "));
            }
            if let Some(ref track) = pkg.track {
                println!("  track: {track}");
            }
        }
    }
    if !found {
        eprintln!("{} not found in any inventory.", args.name);
        return Ok(ExitCode::FAILURE);
    }
    Ok(ExitCode::SUCCESS)
}

/// Merge new fields into an existing package without overwriting.
fn merge_into_package(existing: &mut sandogasa_inventory::Package, args: &AddArgs) {
    // Append RPMs (don't replace).
    if !args.rpm.is_empty() {
        let rpms = existing.rpms.get_or_insert_with(Vec::new);
        for rpm in &args.rpm {
            if !rpms.contains(rpm) {
                rpms.push(rpm.clone());
            }
        }
        rpms.sort();
    }
    // Workload membership is handled at the inventory level by the
    // caller (cmd_add) via add_to_workload.

    // Only set metadata if not already present.
    if existing.poc.is_none() {
        existing.poc.clone_from(&args.poc);
    }
    if existing.reason.is_none() {
        existing.reason.clone_from(&args.reason);
    }
    if existing.team.is_none() {
        existing.team.clone_from(&args.team);
    }
    if existing.task.is_none() {
        existing.task.clone_from(&args.task);
    }
    if existing.track.is_none() {
        existing.track.clone_from(&args.track);
    }
}

fn cmd_adopt(paths: &[String], args: &AdoptArgs) -> CmdResult {
    let inventory = sandogasa_inventory::load_and_merge(paths)?;
    // Detection is unauthenticated GETs, so --dry-run works
    // without a token; only actual adoption needs one.
    let token = if args.dry_run {
        None
    } else {
        Some(config::resolve_distgit_token(args.api_token.as_deref())?)
    };
    let mut dg = sandogasa_distgit::DistGitClient::new();
    if let Some(token) = token {
        dg = dg.with_token(token)?;
    }
    let rt = new_runtime()?;
    // Cheap precondition: a bad token should fail in seconds, not
    // after walking the whole inventory. Also tells us who the
    // new point of contact will be.
    let username = if args.dry_run {
        String::new()
    } else {
        rt.block_on(dg.verify_token()).map_err(|e| {
            format!(
                "dist-git token validation failed: {e}\n\
                 The token needs the \"Modify an existing project\" ACL; \
                 generate one at\n  \
                 https://src.fedoraproject.org/settings/token/new"
            )
        })?
    };
    let report = rt.block_on(adopt::run(
        &inventory,
        &dg,
        &username,
        &args.filter,
        args.dry_run,
        args.yes,
        args.verbose,
    ))?;
    eprintln!(
        "\n{} checked, {} orphaned, {} adopted, {} failed",
        report.packages_checked, report.orphaned_found, report.adopted, report.failures
    );
    Ok(if report.failures > 0 {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    })
}

fn cmd_add(paths: &[String], args: &AddArgs) -> CmdResult {
    // Search all inventories for the package.
    let mut target_path = None;
    for path in paths {
        if let Ok(inv) = sandogasa_inventory::load(path)
            && inv.find_package(&args.name).is_some()
        {
            target_path = Some(path.clone());
            break;
        }
    }

    // Fall back to first inventory file.
    let target_path = target_path.unwrap_or_else(|| paths[0].clone());

    let mut inventory = sandogasa_inventory::load(&target_path)?;

    if let Some(existing) = inventory.find_package_mut(&args.name) {
        // Merge into existing package.
        merge_into_package(existing, args);
        eprintln!("Updated {} in {target_path}", args.name);
    } else {
        // Add new package.
        let pkg = sandogasa_inventory::Package {
            name: args.name.clone(),
            poc: args.poc.clone(),
            reason: args.reason.clone(),
            team: args.team.clone(),
            task: args.task.clone(),
            rpms: (!args.rpm.is_empty()).then(|| args.rpm.clone()),
            track: args.track.clone(),
            ..Default::default()
        };
        inventory.add_package(pkg);
        eprintln!("Added {} to {target_path}", args.name);
    }

    // Add to workloads at the inventory level.
    for wl in &args.workload {
        inventory.add_to_workload(wl, &args.name);
    }

    sandogasa_inventory::save(&inventory, &target_path)?;

    Ok(ExitCode::SUCCESS)
}

fn cmd_remove(path: &str, args: &RemoveArgs) -> CmdResult {
    let mut inventory = sandogasa_inventory::load(path)?;

    if args.rpm.is_empty() {
        // Remove the whole package.
        if !inventory.remove_package(&args.name) {
            return Err(format!("package '{}' not found", args.name).into());
        }
        eprintln!("Removed {} from {path}", args.name);
    } else {
        // Remove specific RPMs from the package.
        let pkg = inventory
            .find_package_mut(&args.name)
            .ok_or_else(|| format!("package '{}' not found", args.name))?;
        if let Some(ref mut rpms) = pkg.rpms {
            for rpm in &args.rpm {
                rpms.retain(|r| r != rpm);
            }
            eprintln!("Removed RPM(s) {} from {}", args.rpm.join(", "), args.name);
        } else {
            return Err(format!("package '{}' has no RPM list", args.name).into());
        }
    }

    sandogasa_inventory::save(&inventory, path)?;

    Ok(ExitCode::SUCCESS)
}

fn cmd_import(args: &ImportArgs) -> CmdResult {
    let mut inventory = sandogasa_inventory::import_json::import_file(&args.json_file)?;

    if !args.private_fields.is_empty() {
        inventory.inventory.private_fields = args.private_fields.clone();
    }

    if !args.workload.is_empty() {
        let pkg_names: Vec<String> = inventory.package.iter().map(|p| p.name.clone()).collect();
        for wl in &args.workload {
            for name in &pkg_names {
                inventory.add_to_workload(wl, name);
            }
        }
    }

    sandogasa_inventory::save(&inventory, &args.output)?;

    eprintln!(
        "Imported {} package(s) from {} to {}",
        inventory.package.len(),
        args.json_file,
        args.output
    );
    Ok(ExitCode::SUCCESS)
}

/// Check if a package name matches any of the Pagure patterns.
/// An empty pattern list (no --pattern / no --auto-prefix) matches everything.
/// Case-insensitive to match Pagure's ILIKE behavior.
fn matches_any_pattern(name: &str, patterns: &[String]) -> bool {
    // No pattern means "all packages" — everything matches.
    if patterns.is_empty() || (patterns.len() == 1 && patterns[0].is_empty()) {
        return true;
    }
    let lower = name.to_ascii_lowercase();
    patterns.iter().any(|pat| {
        if let Some(prefix) = pat.strip_suffix('*') {
            lower.starts_with(&prefix.to_ascii_lowercase())
        } else {
            lower == pat.to_ascii_lowercase()
        }
    })
}

/// Filter projects based on the user's group-access preferences.
fn filter_projects<'a>(
    projects: &'a [sandogasa_distgit::ProjectInfo],
    args: &SyncDistgitArgs,
) -> Vec<&'a sandogasa_distgit::ProjectInfo> {
    let Some(ref username) = args.user else {
        // Group mode: no filtering, return all.
        return projects.iter().collect();
    };

    projects
        .iter()
        .filter(|p| {
            let u = username.as_str();
            let has_direct = p.access_users.owner.iter().any(|x| x == u)
                || p.access_users.admin.iter().any(|x| x == u)
                || p.access_users.commit.iter().any(|x| x == u)
                || p.access_users.collaborator.iter().any(|x| x == u)
                || p.access_users.ticket.iter().any(|x| x == u);

            // Packages with direct access are always included.
            if has_direct {
                return true;
            }

            // User has only group-based access. Apply filters.
            if args.no_groups {
                return false;
            }

            if !args.include_group.is_empty() {
                return args
                    .include_group
                    .iter()
                    .any(|g| p.access_groups.contains_group(g));
            }

            if !args.exclude_group.is_empty() {
                return !args
                    .exclude_group
                    .iter()
                    .any(|g| p.access_groups.contains_group(g));
            }

            // Default: include all.
            true
        })
        .collect()
}

/// Build the list of Pagure name patterns to query.
///
/// User syncs default to per-prefix queries (a-z, 0-9): Pagure's
/// unfiltered username filter scans every project's ACLs and
/// routinely exceeds the gateway timeout (504). An explicit
/// --pattern restricts the query enough to run in one shot.
/// --start-pattern / --end-pattern bound the prefix scan (e.g.
/// to resume an interrupted sync) and imply it, as does
/// --auto-prefix; --no-auto-prefix forces a single unfiltered
/// query. An empty string in the result means "query without a
/// pattern".
fn build_patterns(args: &SyncDistgitArgs) -> Vec<String> {
    // Collapse the flags (clap rejects contradictory combinations)
    // and the mode-dependent default into one scan/no-scan choice.
    let scan = !args.no_auto_prefix
        && (args.auto_prefix
            || args.start_pattern.is_some()
            || args.end_pattern.is_some()
            || (args.user.is_some() && args.pattern.is_none()));
    if !scan {
        return vec![args.pattern.clone().unwrap_or_default()];
    }
    let all_prefixes = ('a'..='z').chain('0'..='9').map(|c| format!("{c}*"));
    let start = args
        .start_pattern
        .as_deref()
        .map(|p| p.trim_end_matches('*'))
        .unwrap_or("");
    let end = args
        .end_pattern
        .as_deref()
        .map(|p| p.trim_end_matches('*'))
        .unwrap_or("");
    let iter: Box<dyn Iterator<Item = String>> = if start.is_empty() {
        Box::new(all_prefixes)
    } else {
        Box::new(all_prefixes.skip_while(move |p| !p.starts_with(start)))
    };
    if end.is_empty() {
        iter.collect()
    } else {
        iter.take_while(|p| !p.starts_with(end)).collect()
    }
}

/// Trim the pattern list for a resumed run: fetching restarts at
/// the recorded failed pattern. A recorded pattern that's no
/// longer in the list (the flags changed between runs) keeps the
/// full list — safe, since re-fetching merges idempotently.
fn resume_patterns(patterns: Vec<String>, failed: &str) -> Vec<String> {
    match patterns.iter().position(|p| p == failed) {
        Some(idx) => patterns[idx..].to_vec(),
        None => patterns,
    }
}

/// Load an existing inventory file as a sync's base, or build a
/// fresh one described by the source when the file doesn't exist
/// yet. `default_name` names the fresh inventory (`--name` or a
/// source-derived default); it's ignored for an existing file.
fn load_or_create_inventory(
    path: &str,
    source_kind: &str,
    source_label: &str,
    default_name: &str,
    workloads: &[String],
) -> Result<sandogasa_inventory::Inventory, String> {
    if std::path::Path::new(path).exists() {
        return sandogasa_inventory::load(path).map_err(|e| format!("{path}: {e}"));
    }
    Ok(sandogasa_inventory::Inventory {
        inventory: sandogasa_inventory::InventoryMeta {
            name: default_name.to_string(),
            description: format!("Packages synced from {source_kind} ({source_label})"),
            maintainer: source_label.to_string(),
            labels: vec![],
            workloads: workloads_from_names(workloads),
            private_fields: vec![],
            synced: None,
        },
        package: vec![],
    })
}

/// Add every remote name missing from the inventory, tagging each
/// with the sync's workloads. Returns the names added, which the
/// callers reuse for counts and retirement checks.
fn add_new_packages<'a>(
    inventory: &mut sandogasa_inventory::Inventory,
    names: impl IntoIterator<Item = &'a str>,
    workloads: &[String],
) -> Vec<String> {
    let mut added: Vec<String> = Vec::new();
    for name in names {
        if inventory.find_package(name).is_some() {
            continue;
        }
        inventory.add_package(sandogasa_inventory::Package {
            name: name.to_string(),
            ..Default::default()
        });
        for wl in workloads {
            inventory.add_to_workload(wl, name);
        }
        added.push(name.to_string());
    }
    added
}

/// Inventory packages the remote listing no longer has, scoped to
/// the patterns the run actually queried (an empty pattern list
/// means everything was in scope, so `--prune --pattern 'a*'`
/// won't drop non-`a*` packages). Packages marked unshipped are
/// preserved: a gone project is absent from the remote listing by
/// definition, and the tombstone is what keeps triage-retired
/// processing it.
fn stale_packages(
    inventory: &sandogasa_inventory::Inventory,
    remote_names: &std::collections::HashSet<&str>,
    patterns: &[String],
) -> Vec<String> {
    inventory
        .package
        .iter()
        .filter(|p| !p.is_unshipped())
        .filter(|p| !remote_names.contains(p.name.as_str()))
        .filter(|p| matches_any_pattern(&p.name, patterns))
        .map(|p| p.name.clone())
        .collect()
}

/// Remove the stale packages under `--prune`, or list them as a
/// warning so the user can decide.
fn prune_or_warn_stale(
    inventory: &mut sandogasa_inventory::Inventory,
    stale: &[String],
    prune: bool,
) {
    if stale.is_empty() {
        return;
    }
    if prune {
        for name in stale {
            inventory.remove_package(name);
        }
    } else {
        eprintln!(
            "warning: {} package(s) not in sync scope \
             (use --prune to remove):",
            stale.len()
        );
        for name in stale {
            eprintln!("  {name}");
        }
    }
}

/// The closing line every sync prints once the inventory is saved.
fn print_sync_summary(
    source_label: &str,
    added: usize,
    pruned: usize,
    prune: bool,
    inventory: &sandogasa_inventory::Inventory,
    output: &str,
) {
    let pruned_msg = if prune && pruned > 0 {
        format!(", {pruned} pruned")
    } else {
        String::new()
    };
    eprintln!(
        "Synced {source_label}: {added} new{pruned_msg}, \
         {} total in {output}",
        inventory.package.len()
    );
}

async fn sync_distgit_async(args: &SyncDistgitArgs) -> Result<(), Box<dyn std::error::Error>> {
    let client = DistGitClient::new();

    // Validate group filters against actual membership.
    if let Some(ref user) = args.user {
        for group in &args.include_group {
            let members = client.get_group_members(group).await?;
            if !members.iter().any(|m| m == user) {
                return Err(format!("user '{user}' is not a member of group '{group}'").into());
            }
        }
        for group in &args.exclude_group {
            let members = client.get_group_members(group).await?;
            if !members.iter().any(|m| m == user) {
                eprintln!("warning: user '{user}' is not a member of group '{group}'");
            }
        }
    }

    let mut patterns = build_patterns(args);

    // Resume support: a failed run leaves `<output>.partial` (the
    // inventory as of the failure) and `<output>.partial.state`
    // (the pattern that failed). When both exist, pick up from the
    // failed pattern instead of re-fetching completed ones; the
    // partial replaces the output as the base inventory below.
    let partial_path = format!("{}.partial", args.output);
    let state_path = format!("{partial_path}.state");
    let resuming = !args.fast && std::path::Path::new(&partial_path).exists();
    if resuming {
        if let Ok(state) = std::fs::read_to_string(&state_path) {
            patterns = resume_patterns(patterns, state.trim());
            eprintln!(
                "resuming from pattern '{}' using {partial_path}",
                patterns.first().map(String::as_str).unwrap_or("")
            );
        } else {
            eprintln!("found {partial_path} but no state file; re-fetching all patterns");
        }
    }

    let source_label = if let Some(ref user) = args.user {
        format!("user:{user}")
    } else {
        format!("group:{}", args.group.as_deref().unwrap())
    };

    let mut all_projects = Vec::new();
    let mut fetch_error = None;
    let mut failed_pattern: Option<String> = None;
    if args.fast {
        // One request against the owner-alias dump. Entries are
        // synthesized as direct access, so the group filters below
        // pass them through; --pattern applies client-side. The
        // prune scope collapses to that single pattern.
        let user = args.user.as_ref().unwrap();
        all_projects = client.user_packages_fast(user).await?;
        if let Some(ref pat) = args.pattern {
            all_projects.retain(|p| matches_any_pattern(&p.name, std::slice::from_ref(pat)));
        }
        patterns = vec![args.pattern.clone().unwrap_or_default()];
    }
    let scan_patterns: &[String] = if args.fast { &[] } else { &patterns };
    for pat in scan_patterns {
        let result = if pat.is_empty() {
            if let Some(ref user) = args.user {
                client.user_projects(user, args.per_page, None).await
            } else {
                client
                    .group_projects(args.group.as_ref().unwrap(), args.per_page, None)
                    .await
            }
        } else {
            eprintln!("  pattern: {pat}");
            if let Some(ref user) = args.user {
                client.user_projects(user, args.per_page, Some(pat)).await
            } else {
                client
                    .group_projects(args.group.as_ref().unwrap(), args.per_page, Some(pat))
                    .await
            }
        };
        match result {
            Ok(p) => all_projects.extend(p),
            Err(e) => {
                eprintln!("error: {e}");
                if pat.is_empty() && e.to_string().contains("504") {
                    eprintln!(
                        "hint: Pagure's unfiltered project query often \
                         exceeds the gateway timeout; retry with \
                         --auto-prefix (or restrict with --pattern)"
                    );
                }
                fetch_error = Some(e);
                failed_pattern = Some(pat.clone());
                break;
            }
        }
    }
    sandogasa_distgit::client::dedup_projects(&mut all_projects);

    let total_fetched = all_projects.len();
    let mut filtered = filter_projects(&all_projects, args);
    let group_excluded = total_fetched - filtered.len();

    // Apply --exclude globs.
    if !args.exclude.is_empty() {
        filtered.retain(|p| !matches_any_pattern(&p.name, &args.exclude));
    }
    let pkg_excluded = total_fetched - group_excluded - filtered.len();

    if group_excluded > 0 || pkg_excluded > 0 {
        let mut parts = vec![format!("{total_fetched} unique")];
        if group_excluded > 0 {
            parts.push(format!("{group_excluded} excluded by group filter"));
        }
        if pkg_excluded > 0 {
            parts.push(format!("{pkg_excluded} excluded by --exclude"));
        }
        eprintln!("  {}", parts.join(", "));
    }

    // Load the base inventory: the partial when resuming (it was
    // derived from the output plus everything fetched before the
    // failure), the existing output otherwise, or a fresh one.
    let mut inventory = if resuming {
        sandogasa_inventory::load(&partial_path).map_err(|e| format!("{partial_path}: {e}"))?
    } else {
        let default_name = args
            .name
            .clone()
            .unwrap_or_else(|| source_label.replace(':', "-"));
        load_or_create_inventory(
            &args.output,
            "dist-git",
            &source_label,
            &default_name,
            &args.workload,
        )?
    };

    // Update inventory name if explicitly provided.
    if let Some(ref name) = args.name {
        inventory.inventory.name.clone_from(name);
    }

    let remote_names: std::collections::HashSet<&str> =
        filtered.iter().map(|p| p.name.as_str()).collect();

    // Add new packages, remembering which ones for
    // --mark-unshipped.
    let added_names = add_new_packages(
        &mut inventory,
        filtered.iter().map(|p| p.name.as_str()),
        &args.workload,
    );
    let added = added_names.len();

    // On fetch error, save partial results plus the failed
    // pattern, so the next run with the same -o resumes there.
    if let Some(e) = fetch_error {
        sandogasa_inventory::save(&inventory, &partial_path)?;
        if let Some(pat) = failed_pattern {
            std::fs::write(&state_path, format!("{pat}\n"))?;
        }
        eprintln!(
            "Saved {} package(s) to {partial_path} (incomplete); \
             re-run the same command to resume",
            inventory.package.len()
        );
        return Err(e);
    }

    // Detect packages in the inventory but not in the filtered
    // results, scoped to the active pattern(s). Excluded packages
    // naturally fall out of remote_names since they were filtered
    // above.
    let stale = stale_packages(&inventory, &remote_names, &patterns);
    let pruned = stale.len();
    prune_or_warn_stale(&mut inventory, &stale, args.prune);

    // Check the packages this run added against the active
    // branches, so a fresh inventory starts with `unshipped`
    // markers instead of needing a follow-up prune-retired run.
    // Best-effort: a failure here loses the markers, not the
    // sync (prune-retired can backfill them).
    if args.mark_unshipped && !added_names.is_empty() {
        eprintln!(
            "checking {} newly added package(s) for retirement...",
            added_names.len()
        );
        let marked = match prune_retired::active_branches_from_bodhi().await {
            Ok(active) => {
                let scanned = prune_retired::scan_packages(
                    &client,
                    added_names.clone(),
                    &active,
                    args.jobs,
                    false,
                )
                .await;
                match scanned {
                    Ok(findings) => {
                        let (candidates, invalid) = prune_retired::split_invalid(findings);
                        let n = prune_retired::apply_unshipped_marks(
                            &mut inventory,
                            &added_names,
                            &candidates,
                        );
                        for c in &candidates {
                            eprintln!("  {}: {}", c.package, c.reason.describe());
                        }
                        for name in &invalid {
                            eprintln!(
                                "  {name}: no such dist-git project — fix or remove the entry"
                            );
                        }
                        Some(n)
                    }
                    Err(e) => {
                        eprintln!(
                            "warning: retirement check failed ({e}); \
                             run prune-retired to mark unshipped packages"
                        );
                        None
                    }
                }
            }
            Err(e) => {
                eprintln!(
                    "warning: {e}; \
                     run prune-retired to mark unshipped packages"
                );
                None
            }
        };
        if let Some(n) = marked {
            eprintln!("marked {n} package(s) unshipped");
        }
    }

    sandogasa_inventory::save(&inventory, &args.output)?;
    // A completed run supersedes any leftover resume state.
    if resuming {
        let _ = std::fs::remove_file(&partial_path);
        let _ = std::fs::remove_file(&state_path);
    }

    print_sync_summary(
        &source_label,
        added,
        pruned,
        args.prune,
        &inventory,
        &args.output,
    );
    Ok(())
}

fn cmd_sync_distgit(args: &SyncDistgitArgs) -> CmdResult {
    // Group filters only apply to user mode.
    if args.user.is_none()
        && (args.no_groups || !args.include_group.is_empty() || !args.exclude_group.is_empty())
    {
        return Err("--no-groups, --include-group, and \
             --exclude-group only apply with --user"
            .into());
    }

    let rt = new_runtime()?;
    rt.block_on(sync_distgit_async(args))?;
    Ok(ExitCode::SUCCESS)
}

fn resolve_gitlab_url(args: &SyncGitlabArgs) -> Result<String, String> {
    if let Some(ref url) = args.url {
        return Ok(url.clone());
    }
    if let Some(ref preset) = args.preset {
        for &(name, url) in GITLAB_PRESETS {
            if name == preset.as_str() {
                return Ok(url.to_string());
            }
        }
        let valid: Vec<&str> = GITLAB_PRESETS.iter().map(|(n, _)| *n).collect();
        return Err(format!(
            "unknown preset '{preset}'. Valid: {}",
            valid.join(", ")
        ));
    }
    Err("specify --url or --preset".to_string())
}

/// The fedrq branch a release name queries: `f43` → `rpmfusion-f43`,
/// `el10` → `rpmfusion-el10`, matching the two release definitions in
/// `configs/fedrq/rpmfusion.toml`. A name already carrying the prefix
/// is left alone, so `--release rpmfusion-f43` works too.
fn rpmfusion_branch(release: &str) -> String {
    match release.starts_with("rpmfusion-") {
        true => release.to_string(),
        false => format!("rpmfusion-{release}"),
    }
}

/// Which Fedora release rawhide currently is, as the **highest**
/// dist tag across the repository (`1.fc46` → `f46`).
///
/// Recorded as a label on the rawhide workload, because RPM Fusion
/// says "rawhide" everywhere a number would go — in their repo ids
/// (`free-fedora-rawhide`) and in their Bugzilla's version list
/// alike — while the Fedora update being checked says `f46`. Nothing
/// at either end carries that correspondence, so the inventory does.
///
/// It has to be the maximum, not any one package and not the most
/// common one: a rawhide repository keeps whatever was last built, so
/// a package nobody has rebuilt this cycle still carries an older
/// tag. On 2026-10-12 it held 292 `fc45` against 131 `fc46` with
/// stragglers back to `fc37` — so the first package said f45, the
/// mode said f45, and only the maximum said f46. Stragglers are
/// always behind, never ahead, which is what makes the max safe.
fn rawhide_label(fedrq: &sandogasa_fedrq::Fedrq, names: &[String]) -> Option<String> {
    let refs: Vec<&str> = names.iter().map(String::as_str).collect();
    let newest = fedrq
        .pkgs_source_vr(&refs)
        .ok()?
        .into_iter()
        .filter_map(|(_, vr)| {
            vr.rsplit_once(".fc")?
                .1
                .chars()
                .take_while(char::is_ascii_digit)
                .collect::<String>()
                .parse::<u32>()
                .ok()
        })
        .max()?;
    Some(format!("f{newest}"))
}

fn cmd_sync_rpmfusion(args: &SyncRpmfusionArgs) -> CmdResult {
    sandogasa_cli::require_tools(&[("fedrq", "sudo dnf install fedrq", Some("--version"))])?;

    let default_name = args.name.clone().unwrap_or_else(|| "rpmfusion".to_string());
    let mut inventory = load_or_create_inventory(
        &args.output,
        "RPM Fusion",
        "rpmfusion",
        &default_name,
        &args.release,
    )?;
    if let Some(ref name) = args.name {
        inventory.inventory.name.clone_from(name);
    }

    // Query each release separately: a package can ship in RPM Fusion
    // for one Fedora release and not another, and the submit-time
    // check is per release, so the answer has to be kept per release
    // rather than unioned away.
    let mut added = 0usize;
    for release in &args.release {
        let branch = rpmfusion_branch(release);
        let fedrq = sandogasa_fedrq::Fedrq {
            branch: Some(branch.clone()),
            repo: args.repo.clone(),
        };
        let names = fedrq
            .all_sources()
            .map_err(|e| format!("querying {branch}: {e}"))?;
        if names.is_empty() {
            return Err(format!(
                "{branch} returned no packages — is configs/fedrq/rpmfusion.toml \
                 installed where fedrq looks (/etc/fedrq/ or ~/.config/fedrq/, \
                 with repos/ beside it)?"
            )
            .into());
        }
        eprintln!("  {branch}: {} package(s)", names.len());

        added += add_new_packages(&mut inventory, names.iter().map(String::as_str), &[]).len();
        // Membership is rebuilt, not added to: a package RPM Fusion
        // dropped for this release has to leave this release's
        // workload while staying in the inventory for the releases
        // that still ship it. add_new_packages only ever adds.
        let meta = inventory
            .inventory
            .workloads
            .entry(release.clone())
            .or_default();
        meta.description
            .get_or_insert_with(|| format!("RPM Fusion packages for {release}"));
        if release == "rawhide"
            && let Some(label) = rawhide_label(&fedrq, &names)
        {
            eprintln!("    rawhide is currently {label}");
            meta.labels = Some(vec![label]);
        }
        meta.packages = names;
    }

    // Stale means "no release we know of ships it", which is the
    // union of *every* workload once the scanned ones are rebuilt —
    // not the union of what this run queried. Syncing one release
    // must not prune a package that another release still ships, and
    // scoping to the scanned releases would do exactly that: `--prune
    // --release f43` dropped 13 packages that ship for f44 and el10.
    // An unscanned release's workload is untouched above, so its
    // packages are still listed and survive.
    let everywhere: std::collections::HashSet<&str> = inventory
        .inventory
        .workloads
        .values()
        .flat_map(|w| w.packages.iter().map(String::as_str))
        .collect();
    let stale = stale_packages(&inventory, &everywhere, &[]);
    let pruned = stale.len();
    prune_or_warn_stale(&mut inventory, &stale, args.prune);

    // Stamp the day it was read. A copy of this shipped in a package
    // is a snapshot of somebody else's repositories and goes stale
    // without anything looking wrong, so the reader -- and ebranch,
    // which may be using the packaged copy -- can see its age.
    inventory.inventory.synced = Some(chrono::Local::now().date_naive().to_string());

    sandogasa_inventory::save(&inventory, &args.output)?;
    print_sync_summary(
        "RPM Fusion",
        added,
        pruned,
        args.prune,
        &inventory,
        &args.output,
    );
    Ok(ExitCode::SUCCESS)
}

fn cmd_sync_gitlab(args: &SyncGitlabArgs) -> CmdResult {
    let group_url = resolve_gitlab_url(args)?;

    let source_label = args.preset.clone().unwrap_or_else(|| group_url.clone());

    // Validate the cheap --mark-unshipped preconditions before the
    // long GitLab/CBS fetches: the source must map to a known CBS
    // SIG, and koji (cbs profile) must be available.
    let sig = if args.mark_unshipped {
        let Some(sig) = gitlab_unshipped::Sig::from_source(args.preset.as_deref(), &group_url)
        else {
            return Err(format!(
                "--mark-unshipped supports the hyperscale and \
                 proposed-updates sources only (no CBS release \
                 lifecycle for {source_label})"
            )
            .into());
        };
        sandogasa_cli::require_tools(&[("koji", "sudo dnf install koji", Some("version"))])?;
        Some(sig)
    } else {
        None
    };

    let projects = sandogasa_gitlab::list_group_projects(&group_url)?;

    let total_fetched = projects.len();

    // Apply --exclude globs.
    let names: Vec<&str> = if args.exclude.is_empty() {
        projects.iter().map(|p| p.name.as_str()).collect()
    } else {
        projects
            .iter()
            .map(|p| p.name.as_str())
            .filter(|n| !matches_any_pattern(n, &args.exclude))
            .collect()
    };

    let pkg_excluded = total_fetched - names.len();
    if pkg_excluded > 0 {
        eprintln!("  {total_fetched} fetched, {pkg_excluded} excluded");
    }

    // Load existing inventory or create a new one.
    let default_name = args.name.clone().unwrap_or_else(|| source_label.clone());
    let mut inventory = load_or_create_inventory(
        &args.output,
        "GitLab",
        &source_label,
        &default_name,
        &args.workload,
    )?;

    if let Some(ref name) = args.name {
        inventory.inventory.name.clone_from(name);
    }

    let remote_names: std::collections::HashSet<&str> = names.iter().copied().collect();

    let added = add_new_packages(&mut inventory, names.iter().copied(), &args.workload).len();

    // Detect stale packages. Every synced name is in scope here
    // (GitLab syncs have no pattern flag).
    let stale = stale_packages(&inventory, &remote_names, &[]);
    let pruned = stale.len();
    prune_or_warn_stale(&mut inventory, &stale, args.prune);

    // Mark archived projects with no released CBS build as
    // unshipped. Best-effort: a CBS/GitLab failure warns but the
    // sync still saves (re-run --mark-unshipped to backfill).
    if let Some(sig) = sig {
        let synced: Vec<String> = names.iter().map(|n| n.to_string()).collect();
        eprintln!(
            "checking {} package(s) for CBS release status...",
            synced.len()
        );
        match gitlab_unshipped::shipped_packages(sig, &args.centos_release, false) {
            Ok(shipped) => match sandogasa_gitlab::list_archived_project_names(&group_url) {
                Ok(archived) => {
                    let outcome =
                        gitlab_unshipped::mark(&mut inventory, &synced, &archived, &shipped);
                    eprintln!(
                        "{} unshipped, {} archived-with-builds; {} marker(s) updated",
                        outcome.unshipped.len(),
                        outcome.archived_builds.len(),
                        outcome.changed
                    );
                    if !outcome.unshipped.is_empty() {
                        eprintln!(
                            "  unshipped (archived, no CBS build): {}",
                            outcome.unshipped.join(", ")
                        );
                    }
                    if !outcome.archived_builds.is_empty() {
                        eprintln!(
                            "  archived but still have CBS builds (run hs-relmon \
                             to prune): {}",
                            outcome.archived_builds.join(", ")
                        );
                    }
                }
                Err(e) => eprintln!(
                    "warning: fetching archived projects failed ({e}); \
                     re-run --mark-unshipped to mark unshipped packages"
                ),
            },
            Err(e) => eprintln!(
                "warning: CBS release scan failed ({e}); \
                 re-run --mark-unshipped to mark unshipped packages"
            ),
        }
    }

    sandogasa_inventory::save(&inventory, &args.output)?;

    print_sync_summary(
        &source_label,
        added,
        pruned,
        args.prune,
        &inventory,
        &args.output,
    );
    Ok(ExitCode::SUCCESS)
}

#[cfg(test)]
mod tests {
    #[test]
    fn an_rpm_fusion_release_names_its_fedrq_branch() {
        // The two release definitions in configs/fedrq/rpmfusion.toml:
        // Fedora by number, EL by major (they publish one branch per
        // major, not per RHEL minor).
        assert_eq!(rpmfusion_branch("f43"), "rpmfusion-f43");
        assert_eq!(rpmfusion_branch("el10"), "rpmfusion-el10");
        // Already-qualified names pass through, so --release can be
        // spelled either way without silently querying rpmfusion-rpmfusion-f43.
        assert_eq!(rpmfusion_branch("rpmfusion-f43"), "rpmfusion-f43");
    }

    /// The committed man page is generated from this CLI; see
    /// `sandogasa_cli::man` and `scripts/gen-man.sh`.
    #[test]
    fn man_page_matches_cli() {
        sandogasa_cli::man::check::<super::Cli>(
            concat!(env!("CARGO_MANIFEST_DIR"), "/man/poi-tracker.1"),
            env!("CARGO_PKG_VERSION"),
        );
    }

    use super::*;

    #[test]
    fn directory_flag_reads_the_git_style_forms() {
        let argv = |v: &[&str]| v.iter().map(std::ffi::OsString::from).collect::<Vec<_>>();
        assert_eq!(
            directory_flag(argv(&["poi-tracker", "-C", "/data", "reconcile"])),
            Some("/data".into())
        );
        assert_eq!(
            directory_flag(argv(&["poi-tracker", "reconcile", "--directory=/d"])),
            Some("/d".into())
        );
        assert_eq!(
            directory_flag(argv(&["poi-tracker", "-C/x", "show"])),
            Some("/x".into())
        );
        assert_eq!(
            directory_flag(argv(&["poi-tracker", "show", "-i", "a.toml"])),
            None
        );
    }
    use sandogasa_distgit::ProjectInfo;

    fn make_project(name: &str, owner: &str, groups: &[&str]) -> ProjectInfo {
        let json = serde_json::json!({
            "name": name,
            "access_users": {
                "owner": [owner],
                "admin": [],
                "commit": [],
                "collaborator": [],
                "ticket": []
            },
            "access_groups": {
                "admin": [],
                "commit": groups,
                "collaborator": [],
                "ticket": []
            }
        });
        serde_json::from_value(json).unwrap()
    }

    fn make_project_with_commit(
        name: &str,
        owner: &str,
        commit_users: &[&str],
        groups: &[&str],
    ) -> ProjectInfo {
        let json = serde_json::json!({
            "name": name,
            "access_users": {
                "owner": [owner],
                "admin": [],
                "commit": commit_users,
                "collaborator": [],
                "ticket": []
            },
            "access_groups": {
                "admin": [],
                "commit": groups,
                "collaborator": [],
                "ticket": []
            }
        });
        serde_json::from_value(json).unwrap()
    }

    fn default_args() -> SyncDistgitArgs {
        SyncDistgitArgs {
            user: Some("alice".to_string()),
            group: None,
            output: "out.toml".to_string(),
            fast: false,
            no_groups: false,
            include_group: vec![],
            exclude_group: vec![],
            exclude: vec![],
            pattern: None,
            start_pattern: None,
            end_pattern: None,
            auto_prefix: false,
            no_auto_prefix: false,
            prune: false,
            mark_unshipped: false,
            jobs: 8,
            per_page: 100,
            workload: vec![],
            name: None,
        }
    }

    #[test]
    fn filter_group_mode_returns_all() {
        let projects = vec![
            make_project("aaa", "bob", &["rust-sig"]),
            make_project("bbb", "carol", &[]),
        ];
        let args = SyncDistgitArgs {
            user: None,
            group: Some("rust-sig".to_string()),
            ..default_args()
        };
        let result = filter_projects(&projects, &args);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn filter_direct_access_always_included() {
        let projects = vec![make_project("pkg", "alice", &["rust-sig"])];
        let mut args = default_args();
        args.no_groups = true;
        let result = filter_projects(&projects, &args);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn filter_default_includes_group_only() {
        // alice has no direct access, only via rust-sig
        let projects = vec![make_project_with_commit("pkg", "bob", &[], &["rust-sig"])];
        let args = default_args();
        let result = filter_projects(&projects, &args);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn filter_no_groups_excludes_group_only() {
        let projects = vec![make_project_with_commit("pkg", "bob", &[], &["rust-sig"])];
        let mut args = default_args();
        args.no_groups = true;
        let result = filter_projects(&projects, &args);
        assert!(result.is_empty());
    }

    #[test]
    fn filter_no_groups_keeps_direct() {
        // alice is owner (direct) and also has access via group
        let projects = vec![make_project("pkg", "alice", &["rust-sig"])];
        let mut args = default_args();
        args.no_groups = true;
        let result = filter_projects(&projects, &args);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn filter_include_group_matches() {
        let projects = vec![
            make_project_with_commit("a", "bob", &[], &["rust-sig"]),
            make_project_with_commit("b", "bob", &[], &["python-packagers-sig"]),
        ];
        let mut args = default_args();
        args.include_group = vec!["rust-sig".to_string()];
        let result = filter_projects(&projects, &args);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "a");
    }

    #[test]
    fn filter_include_group_still_keeps_direct() {
        let projects = vec![
            make_project("owned", "alice", &[]),
            make_project_with_commit("group-only", "bob", &[], &["python-packagers-sig"]),
        ];
        let mut args = default_args();
        args.include_group = vec!["rust-sig".to_string()];
        let result = filter_projects(&projects, &args);
        // owned (direct) is kept, group-only (python-packagers-sig != rust-sig) is excluded
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "owned");
    }

    #[test]
    fn filter_exclude_group_removes_matching() {
        let projects = vec![
            make_project_with_commit("a", "bob", &[], &["rust-sig"]),
            make_project_with_commit("b", "bob", &[], &["python-packagers-sig"]),
        ];
        let mut args = default_args();
        args.exclude_group = vec!["rust-sig".to_string()];
        let result = filter_projects(&projects, &args);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "b");
    }

    #[test]
    fn filter_exclude_group_keeps_direct() {
        let projects = vec![
            make_project("owned", "alice", &["rust-sig"]),
            make_project_with_commit("group-only", "bob", &[], &["rust-sig"]),
        ];
        let mut args = default_args();
        args.exclude_group = vec!["rust-sig".to_string()];
        let result = filter_projects(&projects, &args);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "owned");
    }

    #[test]
    fn filter_include_multiple_groups() {
        let projects = vec![
            make_project_with_commit("a", "bob", &[], &["rust-sig"]),
            make_project_with_commit("b", "bob", &[], &["python-packagers-sig"]),
            make_project_with_commit("c", "bob", &[], &["kde-sig"]),
        ];
        let mut args = default_args();
        args.include_group = vec!["rust-sig".to_string(), "python-packagers-sig".to_string()];
        let result = filter_projects(&projects, &args);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name, "a");
        assert_eq!(result[1].name, "b");
    }

    // ---- build_patterns ----

    #[test]
    fn build_patterns_user_defaults_to_auto_prefix() {
        // No --pattern: user syncs scan a-z then 0-9 by default,
        // since the unfiltered Pagure query times out (504).
        let args = default_args();
        let patterns = build_patterns(&args);
        assert_eq!(patterns.len(), 36);
        assert_eq!(patterns.first().unwrap(), "a*");
        assert_eq!(patterns[25], "z*");
        assert_eq!(patterns[26], "0*");
        assert_eq!(patterns.last().unwrap(), "9*");
    }

    #[test]
    fn build_patterns_user_explicit_pattern_is_single_query() {
        let mut args = default_args();
        args.pattern = Some("rust-*".to_string());
        assert_eq!(build_patterns(&args), vec!["rust-*".to_string()]);
    }

    #[test]
    fn build_patterns_no_auto_prefix_forces_single_query() {
        let mut args = default_args();
        args.no_auto_prefix = true;
        assert_eq!(build_patterns(&args), vec![String::new()]);
    }

    #[test]
    fn build_patterns_group_defaults_to_single_query() {
        let args = SyncDistgitArgs {
            user: None,
            group: Some("rust-sig".to_string()),
            ..default_args()
        };
        assert_eq!(build_patterns(&args), vec![String::new()]);
    }

    #[test]
    fn build_patterns_group_auto_prefix_opt_in() {
        let args = SyncDistgitArgs {
            user: None,
            group: Some("rust-sig".to_string()),
            auto_prefix: true,
            ..default_args()
        };
        assert_eq!(build_patterns(&args).len(), 36);
    }

    #[test]
    fn build_patterns_start_pattern_bounds_scan() {
        let mut args = default_args();
        args.start_pattern = Some("x".to_string());
        let patterns = build_patterns(&args);
        // x*, y*, z*, then 0*-9*
        assert_eq!(patterns.len(), 13);
        assert_eq!(patterns.first().unwrap(), "x*");
        assert_eq!(patterns[2], "z*");
        assert_eq!(patterns.last().unwrap(), "9*");
    }

    #[test]
    fn build_patterns_end_pattern_stops_scan() {
        let mut args = default_args();
        args.start_pattern = Some("b*".to_string());
        args.end_pattern = Some("e".to_string());
        assert_eq!(build_patterns(&args), vec!["b*", "c*", "d*"]);
    }

    #[test]
    fn build_patterns_group_scan_implied_by_bounds() {
        // Scan bounds imply prefix mode without --auto-prefix,
        // also for group syncs.
        let args = SyncDistgitArgs {
            user: None,
            group: Some("rust-sig".to_string()),
            end_pattern: Some("c".to_string()),
            ..default_args()
        };
        assert_eq!(build_patterns(&args), vec!["a*", "b*"]);
    }

    // ---- matches_any_pattern ----

    #[test]
    fn pattern_empty_matches_all() {
        assert!(matches_any_pattern("anything", &[]));
        assert!(matches_any_pattern("anything", &[String::new()]));
    }

    #[test]
    fn pattern_prefix_matches() {
        let pats = vec!["python-*".to_string()];
        assert!(matches_any_pattern("python-psutil", &pats));
        assert!(!matches_any_pattern("rust-libc", &pats));
    }

    #[test]
    fn pattern_exact_matches() {
        let pats = vec!["systemd".to_string()];
        assert!(matches_any_pattern("systemd", &pats));
        assert!(!matches_any_pattern("systemd-networkd", &pats));
    }

    #[test]
    fn resume_patterns_restarts_at_failed_pattern() {
        let pats = vec!["a*".to_string(), "b*".to_string(), "c*".to_string()];
        assert_eq!(resume_patterns(pats.clone(), "b*"), vec!["b*", "c*"]);
        // Failed on the first pattern: nothing was completed.
        assert_eq!(resume_patterns(pats.clone(), "a*"), pats);
    }

    #[test]
    fn resume_patterns_unknown_state_keeps_all() {
        // Flags changed between runs: re-fetch everything (safe,
        // merging is idempotent).
        let pats = vec!["a*".to_string(), "b*".to_string()];
        assert_eq!(resume_patterns(pats.clone(), "x*"), pats);
    }

    #[test]
    fn walk_filter_defaults_match_everything() {
        let f = WalkFilterArgs::default();
        assert!(f.matches("anything"));
    }

    #[test]
    fn walk_filter_range_is_inclusive_both_ends() {
        let f = WalkFilterArgs {
            pattern: vec![],
            start_from: Some("rust-nu-cli".to_string()),
            end_with: Some("rust-nu-engine".to_string()),
        };
        assert!(!f.matches("rust-itertools"));
        assert!(f.matches("rust-nu-cli"));
        assert!(f.matches("rust-nu-cmd-base"));
        assert!(f.matches("rust-nu-engine"));
        assert!(!f.matches("rust-nu-utils"));
    }

    #[test]
    fn walk_filter_pattern_and_range_compose() {
        let f = WalkFilterArgs {
            pattern: vec!["rust-*".to_string()],
            start_from: Some("rust-nu".to_string()),
            end_with: None,
        };
        // In range but wrong pattern:
        assert!(!f.matches("systemd"));
        // Matches pattern but before the range:
        assert!(!f.matches("rust-libc"));
        assert!(f.matches("rust-nu-cli"));
    }

    #[test]
    fn walk_filter_bare_pattern_is_exact() {
        // A bare name (no glob) replaces the old --package flag.
        let f = WalkFilterArgs {
            pattern: vec!["python-django3".to_string()],
            start_from: None,
            end_with: None,
        };
        assert!(f.matches("python-django3"));
        assert!(!f.matches("python-django30"));
    }

    #[test]
    fn pattern_multiple_any_matches() {
        let pats = vec!["a*".to_string(), "b*".to_string()];
        assert!(matches_any_pattern("autoconf", &pats));
        assert!(matches_any_pattern("btrfs-progs", &pats));
        assert!(!matches_any_pattern("cmake", &pats));
    }

    #[test]
    fn pattern_case_insensitive() {
        let pats = vec!["p*".to_string()];
        assert!(matches_any_pattern("python-psutil", &pats));
        assert!(matches_any_pattern("PackageKit", &pats));
        assert!(!matches_any_pattern("systemd", &pats));
    }
}