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
//! pma: portfolio maintenance across many repositories.
//!
//! Design: `docs/dev/design.md`.
use pma_core::{
api, class, config, dates, dispatch, jobs, next, pass, progress, projects, publish, rank,
report, report_runs, route, scan, script, store, sync, todo, watch, worker, workflow,
};
use pma_tui::{choose, tui};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Instant;
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
use api::{Action, Query, Selection, View, has_run, select, whoami};
use config::Config;
use store::{Result, RunState, Session, Store};
use todo::Priority;
/// The commands, in the order someone reaching for one would look. Generated
/// against clap's own list, so a command missing from here is a test failure
/// rather than a command missing from the help.
const GROUPS: [(&str, &[&str]); 6] = [
(
"The loop",
&["next", "scan", "matrix", "dispatch", "review", "pr", "push"],
),
("Tasks", &["lint", "prune", "stale", "sync", "note"]),
("Reading", &["status", "report", "tui", "web", "watch"]),
("Setup", &["root", "project", "config", "verify"]),
("Agents", &["agent", "preset", "route"]),
("Many at once", &["campaign", "workflow", "job"]),
];
/// The template that leaves the command list to `grouped_commands`.
const HELP: &str = "\
{about-with-newline}
{usage-heading} {usage}{after-help}
Options:
{options}";
/// One section per group, each command with the first line of its own help, so
/// there is one place a description is written.
fn grouped_commands(cmd: &clap::Command) -> String {
let width = cmd
.get_subcommands()
.map(|s| s.get_name().len())
.max()
.unwrap_or(0);
let mut out = String::new();
for (heading, names) in GROUPS {
if !out.is_empty() {
out.push('\n');
}
out.push_str(heading);
out.push('\n');
for name in names {
let Some(sub) = cmd.get_subcommands().find(|s| s.get_name() == *name) else {
continue;
};
let about = sub
.get_about()
.map(|a| a.to_string())
.unwrap_or_default()
.lines()
.next()
.unwrap_or_default()
.to_string();
out.push_str(&format!(" {name:width$} {about}\n"));
}
}
out.push_str("\n`pma help <command>` explains one.\n");
out
}
#[derive(Parser)]
#[command(name = "pma", version, about = "Maintain many projects from one place")]
struct Cli {
/// With no command, `pma next`.
#[command(subcommand)]
command: Option<Command>,
}
#[derive(Subcommand)]
enum Command {
/// Check TODO.md files against the format.
///
/// Each path is a TODO.md file or a directory containing one. A directory's
/// subdirectories are not searched: a project's task file is its root
/// TODO.md. Exits 1 when any file has errors or cannot be read; warnings
/// alone exit 0.
Lint {
/// Files or directories; defaults to the current directory.
paths: Vec<PathBuf>,
/// List the open items with no id, which keeps an item's identity
/// when its text changes. With --apply, write one at the end of each,
/// as `- [ ] text ^k3f9q`.
#[arg(long)]
ids: bool,
/// With --ids, write the ids. Edits stay uncommitted.
#[arg(long, requires = "ids")]
apply: bool,
},
/// Remove finished items and `Done` sections.
///
/// Each path is a TODO.md file or a directory containing one, whose
/// subdirectories are not searched. A file with lint errors is skipped. Edits stay uncommitted. Dry run unless --apply.
Prune {
/// Files or directories; defaults to the current directory.
paths: Vec<PathBuf>,
/// Remove them instead of listing them.
#[arg(long)]
apply: bool,
},
/// Directories whose git repos are projects.
Root {
#[command(subcommand)]
action: Option<RootAction>,
},
/// A project's record: its tier, its tags, or its removal.
Project {
#[command(subcommand)]
action: Option<ProjectAction>,
},
/// List a setting, show one, or set one, in `settings.toml`.
Config {
/// A setting such as `tiers.2` or `signals.ci`; omit to list all.
key: Option<String>,
/// The new value; omit to show the current one.
value: Option<String>,
/// Restore the default for KEY.
#[arg(long, requires = "key", conflicts_with = "value")]
reset: bool,
},
/// Read TODO.md, git state and CI into the database.
///
/// Only the TODO.md at a repository's root is read; one in a subdirectory
/// is not a task file. With no names, scans every project and marks those no longer found as
/// absent, keeping their records.
Scan {
/// Project names; defaults to every project.
projects: Vec<String>,
/// Also select every project carrying this tag; repeatable.
#[arg(long = "tag", value_name = "TAG")]
tags: Vec<String>,
/// Skip GitHub; CI is recorded as unknown.
#[arg(long)]
offline: bool,
/// Also measure outdated dependencies (cargo, uv, go); seconds per
/// project. Without it, the last measurement is kept.
#[arg(long, conflicts_with = "offline")]
deps: bool,
},
/// Tasks for agents, and what waits on you. The default.
///
/// Agents' tasks are listed in the order `pma dispatch --auto` takes
/// them. Yours are runs to review, publish or merge, then critical or urgent
/// tasks no agent may take. `pma` alone runs this.
Next {
/// Limit to these projects.
projects: Vec<String>,
/// Also select every project carrying this tag; repeatable.
#[arg(long = "tag", value_name = "TAG")]
tags: Vec<String>,
/// Show every row instead of the top `quadrant_limit` of each list.
#[arg(long)]
all: bool,
},
/// Every tiered project's tasks, ranked, in one view.
Matrix {
/// Limit to these projects.
projects: Vec<String>,
/// Also select every project carrying this tag; repeatable.
#[arg(long = "tag", value_name = "TAG")]
tags: Vec<String>,
/// Show one quadrant: q1, q2, q3 or q4.
#[arg(short, long, value_parser = parse_quadrant)]
quadrant: Option<rank::Quadrant>,
/// Show every task instead of the top `quadrant_limit`.
#[arg(long)]
all: bool,
},
/// Projects worst first, by what needs attention.
///
/// Each tiered project is placed by the worst state it is in: failing CI,
/// broken TODO.md or scan, unpublished work, critical items, stale deps,
/// then idle. Tier breaks ties.
Status {
/// Limit to these projects.
projects: Vec<String>,
/// Also select every project carrying this tag; repeatable.
#[arg(long = "tag", value_name = "TAG")]
tags: Vec<String>,
/// Name every state each project is in, and what put it there.
#[arg(long)]
explain: bool,
/// Include untiered projects, ranked as tier 5.
#[arg(long)]
all: bool,
},
/// Run an agent on tasks, each in its own worktree.
///
/// A target is `project:line`, a TODO.md line from the last scan,
/// `project:ci` for failing CI, `project:deps` for outdated dependencies,
/// `project:critical` and the other headings, or `project:q1` to
/// `project:q4`. A bare `project` opens its tasks in a list. Blocks until
/// every agent has finished.
Dispatch {
/// Targets; with --auto, projects to draw from.
targets: Vec<String>,
/// The agent to run; defaults to `pma config agent`.
#[arg(short = 'a', long)]
agent: Option<String>,
/// The model to ask it for; defaults to the agent's own.
#[arg(short = 'm', long)]
model: Option<String>,
/// A named preset; `-a` or `-m` beside it wins.
#[arg(short = 'p', long)]
preset: Option<String>,
/// With --auto, also draw from every project carrying this tag;
/// repeatable.
#[arg(long = "tag", value_name = "TAG", requires = "auto")]
tags: Vec<String>,
/// Draw eligible tasks in matrix order: the ci and deps signals,
/// and items tagged #agent.
#[arg(long)]
auto: bool,
/// With --auto, how many tasks; defaults to `max_parallel`.
#[arg(short = 'n', long, requires = "auto")]
count: Option<usize>,
/// Clear the named target's consumed attempts and dispatch it again.
#[arg(long, conflicts_with = "auto")]
retry: bool,
/// Queue the command and return at once; `pma job` follows it.
#[arg(long)]
detach: bool,
},
/// Runs awaiting a decision; show one, or act on it.
Review {
/// Run ids; omit to list runs. Several are allowed with --approve.
ids: Vec<i64>,
/// Mark ready runs for `pma pr` or `pma push`.
#[arg(long, requires = "ids", conflicts_with_all = ["reject", "rework"])]
approve: bool,
/// Remove the run's worktree and branch.
#[arg(long, requires = "ids", conflicts_with = "rework")]
reject: bool,
/// With --reject, accept hooks or git settings the run found changed
/// as your own. Without it, such a run is rejected once they are
/// restored.
#[arg(long, requires = "reject")]
keep_git_changes: bool,
/// With --reject, the check or the machine failed, not the agent. The
/// run is left out of the accepted share and uses no attempt.
#[arg(long, requires = "reject")]
infra: bool,
/// Run the agent again in the same worktree with this feedback.
#[arg(long, requires = "ids", value_name = "FEEDBACK")]
rework: Option<String>,
/// Minutes spent reviewing this run, added to the run's total.
#[arg(long, requires = "ids", value_name = "N")]
minutes: Option<u32>,
},
/// Open items by age, oldest first.
Stale {
/// Limit to these projects.
projects: Vec<String>,
/// Also select every project carrying this tag; repeatable.
#[arg(long = "tag", value_name = "TAG")]
tags: Vec<String>,
/// How many to show; defaults to `quadrant_limit`.
#[arg(short = 'n', long)]
count: Option<usize>,
},
/// One task across many repositories.
Campaign {
#[command(subcommand)]
action: Option<CampaignAction>,
},
/// Which worker and how much autonomy, per kind of task.
///
/// Propose a revision, put one into effect, or replay a candidate over the
/// runs already recorded.
Route {
#[command(subcommand)]
action: Option<RouteAction>,
},
/// A graph of agents over a project.
///
/// Read a document, store a revision, or put one into effect.
Workflow {
#[command(subcommand)]
action: Option<WorkflowAction>,
},
/// A named worker, model and configuration.
///
/// List them, name one, or make one the default.
Preset {
#[command(subcommand)]
action: Option<PresetAction>,
},
/// The workers `pma dispatch` can run.
Agent {
#[command(subcommand)]
action: Option<AgentAction>,
},
/// What dispatching produced: outcomes, cost, time.
Report {
/// Group by `project`, `class` or `agent`. Default: class.
#[arg(long, value_name = "DIMENSION")]
by: Option<String>,
},
/// Run each project's check where a dispatch would.
///
/// Checks out the head of the remote default branch in a fresh worktree
/// and runs the verify command there, under the agent's environment. The
/// result is what the next dispatch at that commit reads as its base.
Verify {
/// Project names.
projects: Vec<String>,
/// Also select every project carrying this tag; repeatable.
#[arg(long = "tag", value_name = "TAG")]
tags: Vec<String>,
},
/// Open a pull request for each approved run named.
///
/// Commits the run, pushes its `pma/` branch and opens a pull request
/// against the default branch. The run stays `pr-open`, holding its task,
/// until the pull request is merged (`merged`) or closed without merging
/// (`closed`); `pma review` and `pma dispatch` read that from GitHub.
Pr {
/// Run ids, as `pma review` lists them.
#[arg(required_unless_present = "all_approved")]
ids: Vec<i64>,
/// Every approved run instead of named ones.
#[arg(long, conflicts_with = "ids")]
all_approved: bool,
},
/// Push each approved run named to the default branch.
///
/// Commits the run, rebases it onto the remote default branch and pushes
/// it there, with no pull request. The run becomes `pushed`.
Push {
/// Run ids, as `pma review` lists them.
#[arg(required_unless_present = "all_approved")]
ids: Vec<i64>,
/// Every approved run instead of named ones.
#[arg(long, conflicts_with = "ids")]
all_approved: bool,
},
/// Portfolio notes, which belong to no one project.
Note {
#[command(subcommand)]
action: Option<NoteAction>,
},
/// Every view and action, in the terminal.
Tui,
/// The same views and actions, in a local browser.
///
/// Listens on 127.0.0.1 at a random port behind a token made for this
/// launch, and opens the page. Runs until Ctrl-C.
#[cfg(feature = "web")]
Web {
/// Print the address rather than opening a browser.
#[arg(long)]
no_open: bool,
/// Open the page as an app window in Chrome or Chromium, with no
/// browser controls.
#[arg(long, conflicts_with = "no_open")]
app: bool,
/// Listen on this port rather than one the kernel picks, so an SSH
/// forward can name it: `ssh -L 9000:127.0.0.1:9000 host`.
#[arg(long, default_value_t = 0)]
port: u16,
},
/// Commands queued with `--detach`, newest first.
///
/// `pma job log <id>` prints one's output, `pma job stop <id>` ends one,
/// and `pma job approve <id>` runs the plan a job stopped at.
Job {
#[command(subcommand)]
action: Option<JobAction>,
},
/// What running agents are doing, read from their logs.
///
/// Redraws every 2 seconds until no job or agent is left running, or
/// prints once with --once.
Watch {
#[arg(long)]
once: bool,
},
/// Run queued jobs until none is left. `--detach` starts it.
#[command(hide = true)]
Runner,
/// Mirror `Critical` items to GitHub Issues.
///
/// Opens an issue per Critical item and writes `gh:N` into its line,
/// marks items done when their issue is closed, keeps issue titles and
/// the `pma:critical` label in line with TODO.md, and lists open issues
/// by other people that no item links. TODO.md edits stay uncommitted.
Sync {
/// Limit to these projects; defaults to every scanned project.
projects: Vec<String>,
/// Also select every project carrying this tag; repeatable.
#[arg(long = "tag", value_name = "TAG")]
tags: Vec<String>,
/// Make the changes instead of listing them.
#[arg(long)]
apply: bool,
},
}
#[derive(Subcommand)]
enum JobAction {
/// Print a job's output so far.
Log { id: i64 },
/// Stop a queued job, or kill a running one and its agents.
Stop { id: i64 },
/// Queue the approval of the plan a job stopped at.
Approve { id: i64 },
}
#[derive(Subcommand)]
enum ProjectAction {
/// One project: its state, its open tasks and its runs.
Show { name: String },
/// Set the tier of one project or many: 1 (most important) to 5, or `none`.
///
/// `pma project` lists every project's tier.
Tier {
/// 1 to 5, or `none`.
tier: String,
/// Project directory names under a root.
#[arg(required = true)]
projects: Vec<String>,
},
/// Write every project's tier and tags to a file to edit in bulk.
///
/// The extension picks the format: `.csv` holds one project per line as
/// `name,tier,tag,tag`; `.json` holds a list of objects.
Export {
/// The file to write, ending `.csv` or `.json`.
file: PathBuf,
},
/// Read tiers and tags back from an edited `export` file.
///
/// A project the file leaves out keeps the tier and tags it has; a
/// project it names gets exactly the tags in its row. Dry run unless
/// --apply.
Import {
/// The file to read, ending `.csv` or `.json`.
file: PathBuf,
/// Make the changes instead of listing them.
#[arg(long)]
apply: bool,
},
/// Group projects with private tags. A project may carry several.
///
/// Tags are kept in `settings.toml` and are never read from or written to
/// GitHub. Commands that take project names also take `--tag`.
Tag {
#[command(subcommand)]
action: Option<TagAction>,
},
/// Delete an absent project's record: its tasks, tags, attempt counters
/// and campaign memberships.
///
/// Only a project that no full scan can find is forgotten, since one that
/// is still under a root returns on the next scan. Its runs are kept:
/// their worktrees may still exist. Dry run unless --apply.
Forget {
/// The project's name, as `pma status` shows it.
project: String,
/// Delete it instead of reporting what would go.
#[arg(long)]
apply: bool,
},
/// Check out projects whose record exists but whose working tree does
/// not, from the GitHub `owner/name` the last scan recorded, with
/// `gh repo clone`. Dry run unless --apply.
Clone {
/// Project names.
projects: Vec<String>,
/// Every project with this tag; may repeat.
#[arg(long = "tag", value_name = "TAG")]
tags: Vec<String>,
/// The root to clone into; needed when several are registered.
#[arg(long)]
root: Option<PathBuf>,
/// Clone instead of reporting what would be cloned.
#[arg(long)]
apply: bool,
},
}
#[derive(Subcommand)]
enum TagAction {
/// Give projects a tag.
Add {
tag: String,
#[arg(required = true)]
projects: Vec<String>,
},
/// Take a tag off projects.
Rm {
tag: String,
#[arg(required = true)]
projects: Vec<String>,
},
/// List the projects carrying a tag.
Show { tag: String },
}
#[derive(Subcommand)]
enum NoteAction {
/// Add a note; the words are joined by spaces.
Add {
#[arg(required = true)]
text: Vec<String>,
},
/// Replace a note's text.
Edit {
id: i64,
#[arg(required = true)]
text: Vec<String>,
},
/// Remove a note.
Rm { id: i64 },
}
#[derive(Subcommand)]
enum RootAction {
/// Add a directory: the git repos directly under it, or the directory
/// itself if it is one, become projects.
Add { dir: PathBuf },
/// Remove a directory; the next full scan marks its projects absent.
Rm { dir: PathBuf },
}
fn parse_quadrant(s: &str) -> std::result::Result<rank::Quadrant, String> {
rank::Quadrant::ALL
.into_iter()
.find(|q| format!("{q:?}").eq_ignore_ascii_case(s))
.ok_or_else(|| "expected q1, q2, q3 or q4".into())
}
#[derive(Subcommand)]
enum CampaignAction {
/// Define a campaign over a fixed set of projects.
Add {
name: String,
/// The task, as every repository's agent will read it.
text: String,
/// The projects to apply it to.
#[arg(long, value_delimiter = ',', required = true)]
projects: Vec<String>,
/// Extra prompt lines: acceptance, constraints, an example.
#[arg(long, value_name = "TEXT")]
describe: Option<String>,
/// Maintenance class; default B. A- for `.github/**` work.
#[arg(long)]
class: Option<String>,
},
/// Show a campaign's members and what took them.
Show { name: String },
/// Dispatch the members that have no run.
Run {
name: String,
/// How many to start; defaults to every remaining member.
#[arg(short = 'n', long)]
count: Option<usize>,
},
/// Remove a campaign. Its runs are untouched.
Rm { name: String },
}
#[derive(Subcommand)]
enum RouteAction {
/// Store a policy document as a draft revision.
Propose {
/// A JSON policy file, or `-` for stdin.
file: String,
/// Who proposed it; defaults to the local user.
#[arg(long)]
by: Option<String>,
},
/// Put a revision into effect.
Activate {
revision: i64,
/// Compute and record the route without applying it.
#[arg(long)]
shadow: bool,
/// Who approved it; defaults to the local user.
#[arg(long)]
by: Option<String>,
},
/// Show what a candidate would have routed differently.
Replay {
/// A JSON policy file, `-` for stdin, or a stored revision number.
file: String,
},
/// Print a revision's document.
Show { revision: Option<i64> },
}
#[derive(Subcommand)]
enum PresetAction {
/// Name a worker, a model and the arguments that configure it, replacing
/// one of that name. An empty model leaves the worker its own.
Set {
name: String,
agent: String,
model: Option<String>,
/// Arguments the worker's `{extra}` stands in for, such as
/// `--thinking high`. Leading dashes are taken literally.
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Make a preset the default, as `pma config preset` does.
Use { name: String },
/// Forget a preset. The worker it named is untouched.
Rm { name: String },
}
#[derive(Subcommand)]
enum WorkflowAction {
/// Store a document as a draft revision, printing its worst case.
Propose {
/// A workflow file: JSON, or a Rhai script (`.rhai`) that builds one.
file: String,
/// Who proposed it; defaults to the local user.
#[arg(long)]
by: Option<String>,
},
/// Put a revision into effect, unless its worst case exceeds
/// `workflow_budget`.
Activate {
revision: i64,
/// Who approved it; defaults to the local user.
#[arg(long)]
by: Option<String>,
},
/// Print a revision's document, as `pma` read it.
Show { revision: Option<i64> },
/// Advance one pass of a workflow over a target, then exit. Nodes a rule
/// decides run; nodes an agent decides are planned, priced and left for
/// you to approve by the plan's id.
///
/// An instance is frozen at the revision it started under, so activating
/// another does not change a pass already under way. A node runs once
/// every node before it has finished, so it sees its whole bag.
Run {
/// A workflow named by the revision in effect.
name: String,
/// What to run it over, in `pma dispatch`'s target syntax: `cynn`,
/// `cynn:31`, `cynn:critical`, `cynn:ci`. The element type must be
/// the one the workflow reads.
projects: Vec<String>,
/// Add every project carrying this tag.
#[arg(long)]
tag: Option<String>,
/// Resume an instance instead of starting one.
#[arg(long, value_name = "ID")]
instance: Option<i64>,
/// Set a declared parameter: `--set severity=high`. Repeatable. An
/// instance records what it was given, so a replay reads the same.
#[arg(long = "set", value_name = "NAME=VALUE")]
set: Vec<String>,
/// Plan and price the pass without running anything at all.
#[arg(long)]
dry_run: bool,
/// Run the plan with this id, as the last pass or `--dry-run` printed
/// it. A plan that has changed since is refused.
#[arg(long, value_name = "PLAN")]
approve: Option<String>,
/// Approve each plan as it is reached and run until the instance
/// finishes. `batch_budget` sizes each plan; the caps still hold.
#[arg(long, conflicts_with_all = ["approve", "dry_run"])]
unattended: bool,
/// Work from each clone's `HEAD`, never the remote, and write each
/// edit that passes verify into the clone as unstaged changes; one
/// that fails is discarded. Recorded on the instance.
#[arg(long, conflicts_with = "instance")]
local: bool,
/// Queue the command and return at once; `pma job` follows it.
#[arg(long, conflicts_with = "dry_run")]
detach: bool,
/// Raise a cap of a capped instance and resume it: `--cap
/// max_units=80`. Repeatable; recorded on the instance.
#[arg(long = "cap", value_name = "NAME=N", requires = "instance")]
cap: Vec<String>,
/// Run agent nodes with this worker, whatever a route names.
#[arg(short = 'a', long)]
agent: Option<String>,
/// And this model. A cheap one is how to try a workflow out.
#[arg(short = 'm', long)]
model: Option<String>,
/// A named preset; `-a` or `-m` beside it wins.
#[arg(short = 'p', long)]
preset: Option<String>,
},
/// Stop an instance: no further node runs. Runs it already made stand.
Stop {
/// The instance, as `pma workflow` lists it.
instance: i64,
},
/// Read a document and print the worst case each workflow can cost.
/// Nothing is stored and nothing runs.
Check {
/// A workflow file: JSON, or a Rhai script (`.rhai`) that builds one.
/// `-` reads stdin as JSON.
file: String,
/// Size of the argument bag the estimate assumes.
#[arg(long, default_value_t = 1, value_name = "N")]
units: i64,
/// Print the document a script built, instead of the estimate.
#[arg(long)]
emit_json: bool,
},
}
#[derive(Subcommand)]
enum AgentAction {
/// Set one field, creating the worker when `command` is set first.
Set {
name: String,
/// One of: command, args, allow, parse, reports-cost,
/// enforces-budget, sandbox, resumes.
field: String,
/// The value; for `args`, a JSON array such as `["-p","{prompt}"]`.
value: String,
},
/// Print every field of one worker.
Show { name: String },
/// Remove a worker.
Rm { name: String },
}
fn main() -> ExitCode {
// The command list is grouped rather than alphabetical, which needs the
// template and the list built before parsing.
let command = Cli::command();
let help = grouped_commands(&command);
let matches = command.help_template(HELP).after_help(help).get_matches();
let cli = match Cli::from_arg_matches(&matches) {
Ok(cli) => cli,
Err(e) => e.exit(),
};
let command = cli.command.unwrap_or(Command::Next {
projects: Vec::new(),
tags: Vec::new(),
all: false,
});
let result = match command {
Command::Next {
projects,
tags,
all,
} => show_next(&projects, &tags, all),
Command::Lint { paths, ids, apply } => {
return match ids {
true => add_ids(&paths, apply),
false => lint(&paths),
};
}
Command::Prune { paths, apply } => return prune(&paths, apply),
Command::Root { action } => root(action),
Command::Project { action } => project_command(action),
Command::Config { key, value, reset } => configure(key.as_deref(), value.as_deref(), reset),
Command::Scan {
projects,
tags,
offline,
deps,
} => run_scan(&projects, &tags, offline, deps),
Command::Matrix {
projects,
tags,
quadrant,
all,
} => show_matrix(&projects, &tags, quadrant, all),
Command::Status {
projects,
tags,
explain,
all,
} => show_status(&projects, &tags, explain, all),
Command::Dispatch { detach: true, .. } => {
Store::open_default().and_then(|store| jobs::enqueue(&store))
}
Command::Dispatch {
targets,
agent,
model,
preset,
tags,
auto,
count,
retry,
detach: false,
} => overrides(agent, model, preset)
.and_then(|over| run_dispatch(&targets, &tags, auto, count, retry, &over)),
Command::Review {
ids,
approve,
reject,
keep_git_changes,
infra,
rework,
minutes,
} => run_review(
&ids,
approve,
reject,
keep_git_changes,
infra,
rework.as_deref(),
minutes,
),
Command::Stale {
projects,
tags,
count,
} => show_stale(&projects, &tags, count),
Command::Campaign { action } => campaign_command(action),
Command::Route { action } => route_command(action),
Command::Workflow { action } => workflow_command(action),
Command::Preset { action } => preset_command(action),
Command::Agent { action } => agent_command(action),
Command::Report { by } => run_report(by.as_deref()),
Command::Pr { ids, all_approved } => run_publish(&ids, all_approved, publish::Target::Pr),
Command::Push { ids, all_approved } => {
run_publish(&ids, all_approved, publish::Target::Push)
}
Command::Verify { projects, tags } => run_verify(&projects, &tags),
Command::Sync {
projects,
tags,
apply,
} => run_sync(&projects, &tags, apply),
Command::Note { action } => note(action),
Command::Tui => run_tui(),
#[cfg(feature = "web")]
Command::Web { no_open, app, port } => run_web(no_open, app, port),
Command::Job { action } => run_job(action),
Command::Runner => jobs::run(),
Command::Watch { once } => run_watch(once),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("pma: {e}");
ExitCode::FAILURE
}
}
}
/// The TODO.md each path names: the file itself, or the one in a directory.
/// The flag says the path was a directory, where a missing file is skipped: a
/// glob over a root names every repository, and not every one keeps a list.
fn todo_files(paths: &[PathBuf]) -> Vec<(PathBuf, bool)> {
if paths.is_empty() {
return vec![(PathBuf::from("./TODO.md"), false)];
}
paths
.iter()
.map(|p| match p.is_dir() {
true => (p.join("TODO.md"), true),
false => (p.clone(), false),
})
.collect()
}
/// Reads a TODO.md. `Ok(None)` for one a directory argument does not hold.
fn read_todo(file: &Path, from_dir: bool) -> std::io::Result<Option<String>> {
match std::fs::read_to_string(file) {
Ok(text) => Ok(Some(text)),
Err(e) if from_dir && e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}
fn lint(paths: &[PathBuf]) -> ExitCode {
let (mut errors, mut warnings, mut failed) = (0, 0, false);
for (file, from_dir) in todo_files(paths) {
let text = match read_todo(&file, from_dir) {
Ok(Some(text)) => text,
Ok(None) => {
println!("{}: skipped: no TODO.md", file.display());
continue;
}
Err(err) => {
println!("{}: error: {err}", file.display());
errors += 1;
failed = true;
continue;
}
};
let mut parsed = todo::parse(&text);
parsed.diagnostics.sort_by_key(|d| d.line);
for d in &parsed.diagnostics {
println!(
"{}:{}: {}: {}",
file.display(),
d.line,
d.severity,
d.message
);
match d.severity {
todo::Severity::Error => errors += 1,
todo::Severity::Warning => warnings += 1,
}
}
failed |= parsed.has_errors();
}
if errors + warnings > 0 {
eprintln!("{errors} errors, {warnings} warnings");
}
if failed {
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
}
/// Writes an id, a trailing `^k3f9q`, into each open item that has none, so the item keeps its
/// age and its open run when its text is reworded later. A file with lint
/// errors is skipped: an item there cannot be told from its duplicate. Runs
/// still open on an item move to its id, so the run check keeps finding them.
fn add_ids(paths: &[PathBuf], apply: bool) -> ExitCode {
let store = Store::open_default().ok();
let projects = store
.as_ref()
.and_then(|s| s.projects().ok())
.unwrap_or_default();
let (mut count, mut failed) = (0, false);
for (file, from_dir) in todo_files(paths) {
let text = match read_todo(&file, from_dir) {
Ok(Some(text)) => text,
Ok(None) => {
println!("{}: skipped: no TODO.md", file.display());
continue;
}
Err(err) => {
println!("{}: error: {err}", file.display());
failed = true;
continue;
}
};
let parsed = todo::parse(&text);
if parsed.has_errors() {
println!("{}: skipped: lint errors; see `pma lint`", file.display());
continue;
}
let mut edited = text.clone();
let mut minted = Vec::new();
for item in parsed.items.iter().filter(|i| !i.done && i.id.is_none()) {
let key = item.key();
let Some((next, id)) = todo::mint_id(&edited, &key, &item.text) else {
continue;
};
println!("{}:{}: ^{id} {}", file.display(), item.line, item.text);
minted.push((key, item.text.clone(), format!("id:{id}")));
edited = next;
}
count += minted.len();
if !apply || minted.is_empty() {
continue;
}
if let Err(err) = todo::save(&file, &edited) {
println!("{}: error: {err}", file.display());
failed = true;
continue;
}
let here = file.canonicalize().ok();
let project = projects
.iter()
.find(|p| p.path.join("TODO.md").canonicalize().ok() == here);
if let (Some(store), Some(project)) = (&store, project) {
for (old, text, new) in &minted {
if let Err(e) = store.rekey_runs(&project.name, old, text, new) {
println!("{}: error: {e}", file.display());
failed = true;
}
}
}
}
match (count, apply) {
(0, _) => println!("every open item has an id"),
(n, true) => println!("{n} ids written; TODO.md edits are uncommitted"),
(n, false) => println!("{n} items without an id; `pma lint --ids --apply` writes them"),
}
match failed {
true => ExitCode::FAILURE,
false => ExitCode::SUCCESS,
}
}
fn prune(paths: &[PathBuf], apply: bool) -> ExitCode {
let (mut count, mut failed) = (0, false);
for (file, from_dir) in todo_files(paths) {
let fail = |why: String| println!("{}: error: {why}", file.display());
let text = match read_todo(&file, from_dir) {
Ok(Some(text)) => text,
Ok(None) => {
println!("{}: skipped: no TODO.md", file.display());
continue;
}
Err(err) => {
fail(err.to_string());
failed = true;
continue;
}
};
if todo::parse(&text).has_errors() {
println!("{}: skipped: lint errors; see `pma lint`", file.display());
continue;
}
let pruned = todo::prune(&text);
for done in &pruned.done_sections {
println!(
"{}:{}: remove `## Done`, lines {}-{}",
file.display(),
done.first,
done.first,
done.last
);
for (n, line) in &done.open {
println!(
"{}:{n}: remove open item with `## Done`: `{line}`",
file.display()
);
}
}
for item in &pruned.items {
println!("{}:{}: remove `{}`", file.display(), item.line, item.text);
}
let removals = pruned.done_sections.len() + pruned.items.len();
if apply
&& removals > 0
&& let Err(err) = todo::save(&file, &pruned.text)
{
fail(err.to_string());
failed = true;
continue;
}
count += removals;
}
if count == 0 {
println!("nothing to prune");
} else if apply {
println!("{count} removals made; TODO.md edits are uncommitted");
} else {
println!("{count} removals; run `pma prune --apply` to make them");
}
if failed {
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
}
fn root(action: Option<RootAction>) -> Result<()> {
let store = Store::open_default()?;
match action {
None => {
for r in store.roots()? {
println!("{}", r.display());
}
}
Some(RootAction::Add { dir }) => {
let dir = dir
.canonicalize()
.map_err(|e| format!("{}: {e}", dir.display()))?;
if !dir.is_dir() {
return Err(format!("{} is not a directory", dir.display()).into());
}
if !store.add_root(&dir)? {
println!("{} is already a root", dir.display());
}
}
Some(RootAction::Rm { dir }) => {
let canonical = dir.canonicalize().unwrap_or_else(|_| dir.clone());
if !store.remove_root(&canonical)? && !store.remove_root(&dir)? {
return Err(format!("{} is not a root", dir.display()).into());
}
}
}
Ok(())
}
fn forget(name: &str, apply: bool) -> Result<()> {
let mut store = Store::open_default()?;
let row = store
.project(name)?
.ok_or_else(|| format!("unknown project `{name}`"))?;
if row.absent_since.is_none() {
return Err(format!(
"{name} is still under a root at {}; `pma root rm` its root or delete the \
checkout, run `pma scan`, then forget it",
row.path.display()
)
.into());
}
let f = store.project_footprint(name)?;
if !f.open_runs.is_empty() {
let ids: Vec<String> = f.open_runs.iter().map(|id| format!("#{id}")).collect();
return Err(format!(
"{name} has runs still open: {}. Each may own a worktree; \
settle them with `pma review` first",
ids.join(" ")
)
.into());
}
println!(
"{name}: {} tasks, {} tags, {} campaign memberships",
f.tasks, f.tags, f.campaigns
);
if f.runs > 0 {
println!("{name}: {} finished runs are kept", f.runs);
}
if !apply {
println!("run `pma project forget {name} --apply` to delete the record");
return Ok(());
}
store.forget_project(name)?;
println!("{name} is forgotten");
Ok(())
}
fn clone_projects(
names: &[String],
tags: &[String],
root: Option<&Path>,
apply: bool,
) -> Result<()> {
let store = Store::open_default()?;
let names = select(&store, names, tags)?;
if names.is_empty() {
return Err("name a project, or --tag".into());
}
let roots = store.roots()?;
let root = match (root, roots.as_slice()) {
(Some(r), _) => {
let r = std::fs::canonicalize(r).map_err(|e| format!("{}: {e}", r.display()))?;
if !roots.contains(&r) {
return Err(
format!("{} is not a root; `pma root add` it first", r.display()).into(),
);
}
r
}
(None, [only]) => only.clone(),
(None, []) => return Err("no root registered; `pma root add <dir>`".into()),
(None, _) => return Err("several roots are registered; name one with --root".into()),
};
let mut planned = 0;
for name in &names {
let row = store
.project(name)?
.ok_or_else(|| format!("unknown project `{name}`"))?;
if row.absent_since.is_none() && row.path.exists() {
println!("{name}: already checked out at {}", row.path.display());
continue;
}
let Some(slug) = row.slug.as_deref() else {
println!("{name}: no GitHub owner/name recorded; not cloned");
continue;
};
// A directory of that name may be another project's, or anything.
let target = root.join(name);
if target.exists() {
println!("{name}: {} already exists; not cloned", target.display());
continue;
}
planned += 1;
if !apply {
println!("{name}: would clone {slug} into {}", target.display());
continue;
}
let out = std::process::Command::new("gh")
.args(["repo", "clone", slug])
.arg(&target)
.args(["--", "-q"])
.output()
.map_err(|e| format!("gh: {e}"))?;
if !out.status.success() {
return Err(format!(
"{name}: gh repo clone {slug} failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
)
.into());
}
println!("{name}: cloned {slug} into {}", target.display());
}
match (planned, apply) {
(0, _) => {}
(_, false) => println!("run again with --apply to clone"),
(_, true) => println!("run `pma scan` to read them"),
}
Ok(())
}
fn tag(action: Option<TagAction>) -> Result<()> {
let store = Store::open_default()?;
let known = |names: &[String]| -> Result<()> {
let rows = store.projects()?;
for n in names {
if !rows.iter().any(|r| &r.name == n) {
return Err(format!("unknown project `{n}`; run `pma scan`").into());
}
}
Ok(())
};
match action {
None => {
let pairs = store.project_tags()?;
if pairs.is_empty() {
println!("no tags; add one with `pma project tag add <tag> <project>...`");
return Ok(());
}
let mut counts: Vec<(String, usize)> = Vec::new();
for (_, t) in pairs {
match counts.iter_mut().find(|(name, _)| name == &t) {
Some((_, n)) => *n += 1,
None => counts.push((t, 1)),
}
}
counts.sort();
for (t, n) in counts {
println!("{t} {n}");
}
}
Some(TagAction::Add { tag, projects }) => {
let tag = projects::normal_tag(&tag)?;
known(&projects)?;
for p in &projects {
if !store.add_project_tag(p, &tag)? {
println!("{p} already carries `{tag}`");
}
}
}
Some(TagAction::Rm { tag, projects }) => {
let tag = projects::normal_tag(&tag)?;
for p in &projects {
if !store.remove_project_tag(p, &tag)? {
println!("{p} does not carry `{tag}`");
}
}
}
Some(TagAction::Show { tag }) => {
let tag = projects::normal_tag(&tag)?;
for p in store.projects_tagged(&[tag])? {
println!("{p}");
}
}
}
Ok(())
}
/// Tags are matched exactly, so they are lowercased once here rather than
/// leaving `ai` and `AI` as two groups.
fn set_tier(tier: &str, names: &[String]) -> Result<()> {
let store = Store::open_default()?;
let tier = match tier {
"none" => None,
t => Some(
t.parse::<u8>()
.ok()
.filter(|t| (1..=5).contains(t))
.ok_or("tier must be 1 to 5, or none")?,
),
};
// Every project is resolved before any is written, so a name typed wrong
// does not leave half the list retiered.
let mut paths = Vec::with_capacity(names.len());
for name in names {
paths.push(match store.project(name)? {
Some(row) => row.path,
None => find_project(&store, name)?,
});
}
for (name, path) in names.iter().zip(paths) {
store.set_tier(name, &path, tier)?;
}
Ok(())
}
fn export_projects(file: &Path) -> Result<()> {
let store = Store::open_default()?;
let format = projects::Format::of(file)?;
let tags = store.project_tags()?;
let entries: Vec<projects::Entry> = store
.projects()?
.into_iter()
.map(|p| projects::Entry {
tier: p.tier,
tags: tags
.iter()
.filter(|(project, _)| *project == p.name)
.map(|(_, tag)| tag.clone())
.collect(),
name: p.name,
})
.collect();
if entries.is_empty() {
return Err("no projects; `pma root add <dir>` then `pma scan`".into());
}
std::fs::write(file, projects::write(&entries, format)?)
.map_err(|e| format!("{}: {e}", file.display()))?;
println!(
"{} projects to {}; edit it, then `pma project import {} --apply`",
entries.len(),
file.display(),
file.display()
);
Ok(())
}
fn import_projects(file: &Path, apply: bool) -> Result<()> {
let store = Store::open_default()?;
let format = projects::Format::of(file)?;
let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?;
let entries = projects::read(&text, format)?;
let rows = store.projects()?;
let tags = store.project_tags()?;
// The whole file is checked first: a name that is not a project usually
// means the wrong file, and half of it applied is worse than none.
let unknown: Vec<&str> = entries
.iter()
.map(|e| e.name.as_str())
.filter(|n| !rows.iter().any(|r| r.name == *n))
.collect();
if !unknown.is_empty() {
return Err(format!(
"not projects: {}; `pma project` lists them, `pma scan` finds new ones",
unknown.join(", ")
)
.into());
}
let mut changes = 0;
for entry in &entries {
let row = rows.iter().find(|r| r.name == entry.name).expect("checked");
let was: Vec<String> = tags
.iter()
.filter(|(project, _)| *project == entry.name)
.map(|(_, tag)| tag.clone())
.collect();
if row.tier != entry.tier {
changes += 1;
println!(
"{}: tier {} -> {}",
entry.name,
show_tier(row.tier),
show_tier(entry.tier)
);
if apply {
store.set_tier(&entry.name, &row.path, entry.tier)?;
}
}
let gone: Vec<&String> = was.iter().filter(|t| !entry.tags.contains(t)).collect();
let new: Vec<&String> = entry.tags.iter().filter(|t| !was.contains(t)).collect();
if !gone.is_empty() || !new.is_empty() {
changes += 1;
println!(
"{}: tags {} -> {}",
entry.name,
show_tags(&was),
show_tags(&entry.tags)
);
if apply {
for tag in gone {
store.remove_project_tag(&entry.name, tag)?;
}
for tag in new {
store.add_project_tag(&entry.name, tag)?;
}
}
}
}
let absent = rows.len() - entries.len();
let kept = match absent {
0 => String::new(),
n => format!("; {n} projects the file leaves out keep what they have"),
};
println!(
"{}",
match (changes, apply) {
(0, _) => format!("{} projects, nothing to change{kept}", entries.len()),
(n, true) => format!("{n} changes applied{kept}"),
(n, false) => format!("{n} changes; --apply to make them{kept}"),
}
);
Ok(())
}
fn show_tier(tier: Option<u8>) -> String {
tier.map_or("none".into(), |t| t.to_string())
}
fn show_tags<T: std::fmt::Display>(tags: &[T]) -> String {
match tags.is_empty() {
true => "none".into(),
false => tags
.iter()
.map(|t| t.to_string())
.collect::<Vec<String>>()
.join(","),
}
}
fn find_project(store: &Store, name: &str) -> Result<PathBuf> {
let (found, _) = scan::discover(&store.roots()?);
found
.into_iter()
.find(|(n, _)| n == name)
.map(|(_, p)| p)
.ok_or_else(|| format!("no project `{name}` under the roots (pma root)").into())
}
fn configure(key: Option<&str>, value: Option<&str>, reset: bool) -> Result<()> {
let store = Store::open_default()?;
let rows = store.config_rows()?;
match (key, value) {
(None, _) => {
let cfg = Config::with_overrides(rows.iter().map(|(k, v)| (k.as_str(), v.as_str())))?;
for key in Config::keys() {
let set = rows.iter().any(|(k, _)| *k == key);
println!(
"{key} = {}{}",
cfg.get(&key).unwrap_or_default(),
if set { " (set)" } else { "" }
);
}
for (k, v) in rows.iter().filter(|(k, _)| k.starts_with("projects.")) {
println!("{k} = {v} (set)");
}
for (k, v) in rows
.iter()
.filter(|(k, _)| Config::default().get(k).is_none())
{
println!("{k} = {v} (unknown; pma config {k} --reset)");
}
}
(Some(key), _) if reset => {
if !store.reset_config(key)? {
println!("{key} was not set");
}
}
(Some(key), None) => {
let cfg = Config::with_overrides(rows.iter().map(|(k, v)| (k.as_str(), v.as_str())))?;
println!(
"{}",
cfg.get(key)
.ok_or_else(|| format!("unknown setting `{key}`"))?
);
}
(Some(key), Some(value)) => {
Config::default()
.set(key, value)
.map_err(|e| format!("{key}: {e}"))?;
store.set_config(key, value.trim())?;
}
}
Ok(())
}
fn run_scan(names: &[String], tags: &[String], offline: bool, deps: bool) -> Result<()> {
let mut store = Store::open_default()?;
let cfg = api::config(&store)?;
let names = &select(&store, names, tags)?;
let roots = store.roots()?;
if roots.is_empty() {
return Err("no roots; add one with `pma root add <dir>`".into());
}
let (found, warnings) = scan::discover(&roots);
for w in warnings {
eprintln!("warning: {w}");
}
let selected: Vec<(String, PathBuf)> = if names.is_empty() {
found
} else {
names
.iter()
.map(|n| {
found
.iter()
.find(|(f, _)| f == n)
.cloned()
.ok_or_else(|| format!("no project `{n}` under the roots"))
})
.collect::<std::result::Result<_, _>>()?
};
// `git status` in a clone holding a setting a failed run found would
// run it, so such a clone is not read.
let runs = store.runs()?;
let mut held = Vec::new();
let mut free = Vec::new();
for (name, path) in selected {
match dispatch::clone_held(&runs, &path) {
Ok(()) => free.push((name, path)),
Err(e) => held.push(scan::Facts::held(&name, &path, e.to_string())),
}
}
let started = Instant::now();
let bar = progress::Bar::new(free.len());
let mut facts = scan::scan_all(&free, &cfg.activity_ignore, offline, deps, &|name| {
bar.done(name)
});
bar.finish();
facts.extend(held);
for f in facts.iter().filter(|f| f.error.is_some()) {
eprintln!(
"warning: {}: {}",
f.name,
f.error.as_deref().unwrap_or_default()
);
}
for name in store.save_scan(&facts, names.is_empty(), dates::now())? {
eprintln!("absent: {name} is no longer under a root; its record is kept");
}
let with_todo = facts.iter().filter(|f| f.todo.is_some()).count();
let items: usize = facts
.iter()
.filter_map(|f| f.todo.as_ref())
.map(|t| t.items.len())
.sum();
let failing = facts
.iter()
.filter(|f| matches!(f.ci, scan::Ci::Failing(_)))
.count();
let mut summary = format!(
"scanned {} projects in {:.1}s: {with_todo} with TODO.md, {items} open items",
facts.len(),
started.elapsed().as_secs_f64()
);
if !offline {
let unknown = facts
.iter()
.filter(|f| matches!(f.ci, scan::Ci::Unknown(_)))
.count();
summary.push_str(&format!(", CI failing in {failing}, unknown in {unknown}"));
}
if deps {
let outdated = facts
.iter()
.filter(|f| f.deps.as_ref().is_some_and(|d| d.outdated > Some(0)))
.count();
summary.push_str(&format!(", outdated dependencies in {outdated}"));
}
println!("{summary}");
Ok(())
}
fn show_matrix(
names: &[String],
tags: &[String],
quadrant: Option<rank::Quadrant>,
all: bool,
) -> Result<()> {
show(Query::Matrix {
of: selection(names, tags),
quadrant,
all,
})
}
fn show_next(names: &[String], tags: &[String], all: bool) -> Result<()> {
show(Query::Next {
of: selection(names, tags),
all,
})
}
fn show_status(names: &[String], tags: &[String], explain: bool, all: bool) -> Result<()> {
show(Query::Status {
of: selection(names, tags),
explain,
all,
})
}
fn run_dispatch(
targets: &[String],
tags: &[String],
auto: bool,
count: Option<usize>,
retry: bool,
over: &dispatch::Overrides,
) -> Result<()> {
let store = Store::open_default()?;
let home = store::state_home()?;
if let Some(name) = &over.agent {
let known = store.agents()?;
if !known.iter().any(|w| &w.name == name) {
return Err(format!(
"unknown agent `{name}`; `pma agent` lists {}",
known
.iter()
.map(|w| w.name.as_str())
.collect::<Vec<_>>()
.join(", ")
)
.into());
}
}
let session = Session::acquire(&store::home()?)?;
store.fail_interrupted_runs(&session)?;
say(api::act(&store, Action::SettlePrs)?);
let active = store.runs()?;
let rows = store.projects()?;
let p = api::portfolio(
&store,
&Selection {
projects: if auto { targets.to_vec() } else { Vec::new() },
tags: if auto { tags.to_vec() } else { Vec::new() },
},
false,
)?;
let placed = rank::place(&p.cfg, p.tasks, p.today);
let quadrant = |project: &str, key: &str| {
placed
.iter()
.find(|x| x.task.project == project && x.task.key.as_deref() == Some(key))
.map(|x| format!("{:?}", x.quadrant))
};
let row = |project: &str| {
rows.iter()
.find(|r| r.name == project)
.ok_or_else(|| format!("unknown project `{project}`").into())
.map_err(|e: Box<dyn std::error::Error>| e)
};
// With --auto, every candidate in matrix order; `wanted` of them are
// queued, so a refused candidate gives its place to the next.
let mut picks = Vec::new();
// Whether any target named a task at all, which decides whether running
// nothing is a quiet result or a failure.
let mut named_any = auto;
let wanted = match auto {
true => count.unwrap_or(p.cfg.max_parallel as usize),
false => targets.len(),
};
if auto {
// Importance orders the queue; eligibility decides what is taken from
// it. A quadrant is a view, not a dispatch policy: `Medium` and `Low`
// are never important at any tier, so quadrant gating hid the
// maintenance work agents are best at.
for x in placed.iter().filter(|x| x.task.eligible) {
let Some(key) = &x.task.key else { continue };
let taken = picks
.iter()
.any(|q: &dispatch::Pick| q.project == x.task.project && &q.key == key);
if taken || has_run(&active, &x.task.project, key, &x.task.text) {
continue;
}
let spent =
store.consumed_attempts(&x.task.project, &dispatch::revision(&x.task.text))?;
if spent >= dispatch::ATTEMPT_LIMIT {
continue;
}
let r = row(&x.task.project)?;
if r.absent_since.is_some() {
continue;
}
picks.push(dispatch::Pick {
workflow: None,
project: x.task.project.clone(),
repo: r.path.clone(),
key: key.clone(),
text: x.task.text.clone(),
gh: None,
tier: r.tier,
class: None,
details: None,
quadrant: Some(format!("{:?}", x.quadrant)),
local: false,
});
}
let tasks = store.tasks()?;
for pick in &mut picks {
pick.gh = tasks
.iter()
.find(|t| t.project == pick.project && t.key == pick.key)
.and_then(|t| t.gh);
}
} else {
if targets.is_empty() {
return Err(
"name a project such as `cynn`, a target such as `cynn:31`, \
or use --auto"
.into(),
);
}
let tasks = store.tasks()?;
for target in targets {
let (project, what) = dispatch::target(target)?;
let row = rows
.iter()
.find(|r| r.name == project)
.ok_or_else(|| format!("unknown project `{project}`"))?;
if row.absent_since.is_some() {
return Err(format!(
"{project} is not under a root; it was last seen at {}. \
Clone it back and run `pma scan`",
row.path.display()
)
.into());
}
let named = match &what {
dispatch::Target::Project => {
let mut all = task_rows(&tasks, project, None);
all.extend(signal_rows(row));
// `#manual` is already on the row, from the last scan.
// The list is a view: it does not fetch to confirm it.
for r in &mut all {
if r.blocked.is_none() {
r.blocked = blocked(&store, &active, project, r, retry)?;
}
}
match chosen(project, all)? {
Some(rows) => rows,
// Cancelled: the other targets are left alone too.
None => return Ok(()),
}
}
dispatch::Target::Line(line) => {
let t = tasks
.iter()
.find(|t| t.project == project && t.line == *line)
.ok_or_else(|| {
format!("{project}:{line} is not an open item at the last scan")
})?;
vec![task_row(t)]
}
dispatch::Target::Signal(which) => {
let found = signal_rows(row).into_iter().find(|r| &r.key == which);
match (found, which.as_str()) {
(Some(r), _) => vec![r],
(None, "ci") => {
return Err(
format!("{project}: CI was not failing at the last scan").into()
);
}
(None, _) => {
return Err(format!(
"{project}: no outdated dependencies at the last \
`pma scan --deps`"
)
.into());
}
}
}
dispatch::Target::Priority(want) => {
let named = task_rows(&tasks, project, Some(*want));
if named.is_empty() {
return Err(format!(
"{project}: no open {} items at the last scan",
want.name()
)
.into());
}
named
}
// Quadrants are a ranking of tiered projects, so an untiered
// one has none rather than an empty one.
dispatch::Target::Quadrant(want) => {
if row.tier.is_none() && p.cfg.default_tier.is_none() {
return Err(format!(
"{project} has no tier, so it is in no quadrant; \
`pma project tier <1-5> {project}`, or name the tasks"
)
.into());
}
let named: Vec<choose::Row> = placed
.iter()
.filter(|x| x.task.project == project && x.quadrant == *want)
.filter_map(placed_row)
.collect();
if named.is_empty() {
return Err(format!(
"{project}: no tasks in {want:?} at the last scan; `pma matrix`"
)
.into());
}
named
}
};
named_any |= !named.is_empty();
// One named task that cannot run is an error; one of many is
// passed over, so a selector is not held up by a single task.
let one = what.is_one();
for candidate in named {
let choose::Row { key, text, gh, .. } = candidate.clone();
if let Some(why) = blocked(&store, &active, project, &candidate, retry)? {
let at = at(project, &candidate);
if one {
return Err(format!("{at}: {why}").into());
}
eprintln!("warning: {at}: {why}");
continue;
}
if retry {
store.reset_attempts(project, &dispatch::revision(&text))?;
}
picks.push(dispatch::Pick {
workflow: None,
project: project.into(),
repo: row.path.clone(),
tier: row.tier,
class: None,
details: None,
quadrant: quadrant(project, &key),
key,
text,
gh,
local: false,
});
}
}
}
// A selector expands to as many tasks as it names; `max_parallel` and
// `batch_budget` bound what runs at once, not what is queued.
let wanted = match auto {
true => wanted,
false => picks.len(),
};
if picks.is_empty() || wanted == 0 {
// A draw that finds nothing is a quiet day, and so is a list nothing
// was checked in. A target that named tasks and ran none of them did
// not do what was asked, and the warnings above say why.
if !named_any {
println!("nothing to dispatch");
return Ok(());
}
return Err("nothing to dispatch: every task named was passed over".into());
}
run_picks(&store, &home, &p.cfg, over, &picks, wanted).map(|_| ())
}
/// The project's open items from the last scan, one priority or all of them.
fn task_rows(tasks: &[store::TaskRow], project: &str, want: Option<Priority>) -> Vec<choose::Row> {
tasks
.iter()
.filter(|t| t.project == project && want.is_none_or(|p| t.priority == p))
.map(task_row)
.collect()
}
fn task_row(t: &store::TaskRow) -> choose::Row {
choose::Row {
key: t.key.clone(),
text: t.text.clone(),
line: Some(t.line),
gh: t.gh,
priority: t.priority.name().into(),
blocked: t
.tags
.iter()
.any(|g| g == "manual")
.then(|| "tagged #manual, which is class D and never dispatched".to_string()),
}
}
/// A placed task, dropped when it is a signal no agent can act on.
fn placed_row(x: &rank::Placed) -> Option<choose::Row> {
Some(choose::Row {
key: x.task.key.clone()?,
text: x.task.text.clone(),
line: x.task.line,
gh: None,
priority: x.task.priority.name().into(),
blocked: None,
})
}
/// The `ci` and `deps` signals the last scan left on a project. The text is
/// the task an agent is given, so it is built in one place only.
fn signal_rows(row: &store::ProjectRow) -> Vec<choose::Row> {
let signal = |key: &str, text: String| choose::Row {
key: key.into(),
text,
line: None,
gh: None,
priority: "signal".into(),
blocked: None,
};
let mut rows = Vec::new();
if let scan::Ci::Failing(w) = &row.ci {
rows.push(signal("ci", format!("fix CI: {}", w.join(", "))));
}
if let Some(n) = row.deps.filter(|n| *n > 0) {
rows.push(signal("deps", format!("update dependencies: {n} outdated")));
}
rows
}
/// Where a task is named on the command line: `project:line`, or
/// `project:ci` and the other signals.
fn at(project: &str, row: &choose::Row) -> String {
match row.line {
Some(line) => format!("{project}:{line}"),
None => format!("{project}:{}", row.key),
}
}
/// Why a task cannot be dispatched now, as the store knows it. `#manual` is
/// not here: the tags that decide a class are read from origin at dispatch,
/// not from the last local scan.
fn blocked(
store: &Store,
active: &[store::Run],
project: &str,
row: &choose::Row,
retry: bool,
) -> Result<Option<String>> {
if has_run(active, project, &row.key, &row.text) {
return Ok(Some("already has a run; see `pma review`".into()));
}
let spent = store.consumed_attempts(project, &dispatch::revision(&row.text))?;
if !retry && spent >= dispatch::ATTEMPT_LIMIT {
let at = at(project, row);
return Ok(Some(format!(
"{spent} attempts on `{}` were used without an accepted result; \
reword the task, or `pma dispatch {at} --retry`. Any worktree it \
left is removed by `pma review <id> --reject`",
row.text
)));
}
Ok(None)
}
/// Opens the project's tasks in a list. `None` when the list was cancelled.
fn chosen(project: &str, rows: Vec<choose::Row>) -> Result<Option<Vec<choose::Row>>> {
use std::io::IsTerminal;
if rows.is_empty() {
return Err(format!("{project}: nothing open at the last scan; run `pma scan`").into());
}
if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
return Err(format!(
"`pma dispatch {project}` opens a list, which needs a terminal; \
name tasks such as `{project}:31`, or `{project}:critical`"
)
.into());
}
let mut app = choose::App::new(project.to_string(), rows);
Ok(choose::run(&mut app)?)
}
/// Prepares up to `wanted` picks and runs them, reporting each. Returns the
/// finished runs, so a caller that owns a set of tasks can record them.
fn run_picks(
store: &Store,
home: &std::path::Path,
cfg: &config::Config,
over: &dispatch::Overrides,
picks: &[dispatch::Pick],
wanted: usize,
) -> Result<Vec<store::Run>> {
let mut queued = Vec::new();
// A project-level failure, such as a failed fetch, skips the project.
let mut unreachable: Vec<&str> = Vec::new();
for pick in picks {
if queued.len() == wanted {
break;
}
if unreachable.contains(&pick.project.as_str()) {
continue;
}
match dispatch::prepare(store, home, cfg, over, pick) {
Ok(dispatch::Prepared::Queued(run)) => {
println!("#{} {}: {}", run.id, run.project, run.text);
queued.push(*run);
}
Ok(dispatch::Prepared::Refused(why)) => eprintln!("warning: {why}"),
Err(e) => {
eprintln!("warning: {}: {e}", pick.project);
unreachable.push(&pick.project);
}
}
}
if queued.is_empty() {
return Err("no run started".into());
}
let finished = dispatch::execute(store, home, cfg, over, queued, |run| {
println!("{}", report::run_line(run));
})?;
let ready = finished
.iter()
.filter(|r| r.state == RunState::Ready)
.count();
let spent = finished
.iter()
.filter_map(|r| r.cost_usd)
.fold(0.0, |a, c| a + c);
println!(
"{ready} ready, {} failed, ${spent:.2} spent; see `pma review`",
finished.len() - ready
);
Ok(finished)
}
fn run_review(
ids: &[i64],
approve: bool,
reject: bool,
keep_git_changes: bool,
infra: bool,
rework: Option<&str>,
minutes: Option<u32>,
) -> Result<()> {
let store = Store::open_default()?;
if ids.is_empty() {
say(api::act(&store, Action::SettlePrs)?);
return show_with(&store, Query::Runs);
}
if ids.len() > 1 {
if !approve {
return Err("name one run, or several ids with --approve".into());
}
say(api::act(&store, Action::ApproveRuns { ids: ids.to_vec() })?);
return Ok(());
}
let id = ids[0];
// Added before the action, so a rework's own review time is not lost when
// the run is reviewed again.
if let Some(minutes) = minutes {
say(api::act(&store, Action::AddReviewTime { id, minutes })?);
}
if approve {
say(api::act(&store, Action::ApproveRun { id, seen: None })?);
} else if reject {
say(api::act(
&store,
Action::RejectRun {
id,
keep_git_changes,
infra,
seen: None,
},
)?);
} else if let Some(feedback) = rework {
// In the foreground: a front end queues this command as a job.
let session = Session::acquire(&store::home()?)?;
store.fail_interrupted_runs(&session)?;
let cfg = api::config(&store)?;
let mut run = store.run(id)?;
dispatch::rework(&store, &store::state_home()?, &cfg, &mut run, feedback)?;
println!("{}", report::run_line(&run));
} else {
api::settle_interrupted(&store)?;
show_with(&store, Query::Run { id })?;
}
Ok(())
}
fn show_stale(names: &[String], tags: &[String], count: Option<usize>) -> Result<()> {
show(Query::Stale {
of: selection(names, tags),
count,
})
}
fn campaign_command(action: Option<CampaignAction>) -> Result<()> {
let store = Store::open_default()?;
let Some(action) = action else {
return show_with(&store, Query::Campaigns);
};
match action {
CampaignAction::Add {
name,
text,
projects,
describe,
class,
} => {
let known = store.projects()?;
for p in &projects {
if !known.iter().any(|r| &r.name == p) {
return Err(format!("unknown project `{p}`; run `pma scan`").into());
}
}
let class = match class.as_deref() {
None => class::Class::Specified,
Some(c) => class::Class::parse(c)
.ok_or_else(|| format!("unknown class `{c}`; expected A, A-, B, C or D"))?,
};
if !class.dispatchable() {
return Err(format!("class {} is never dispatched", class.name()).into());
}
let mut members: Vec<(String, Option<i64>)> =
projects.iter().map(|p| (p.clone(), None)).collect();
members.sort();
members.dedup();
store.add_campaign(&store::Campaign {
name: name.clone(),
text,
description: describe.unwrap_or_default(),
class,
created_at: dates::now(),
members,
})?;
println!("campaign `{name}` defined; `pma campaign run {name}` starts it");
}
CampaignAction::Rm { name } => {
if !store.remove_campaign(&name)? {
return Err(format!("unknown campaign `{name}`").into());
}
}
CampaignAction::Show { name } => show_with(&store, Query::Campaign { name })?,
CampaignAction::Run { name, count } => return run_campaign(&name, count),
}
Ok(())
}
/// Dispatches the members that have no live run. Repeating it is safe: a
/// member whose run is still open is passed over, so a restart after a
/// failure does not open a second pull request for it.
fn run_campaign(name: &str, count: Option<usize>) -> Result<()> {
let store = Store::open_default()?;
let home = store::state_home()?;
let session = Session::acquire(&store::home()?)?;
store.fail_interrupted_runs(&session)?;
let cfg = api::config(&store)?;
let campaign = store.campaign(name)?;
let rows = store.projects()?;
let active = store.runs()?;
let mut picks = Vec::new();
for (project, run) in &campaign.members {
// A member with a run that is not final is left alone, whatever its
// state. Dispatching over a failed run would leave its worktree
// behind and could open a second pull request for the same work;
// rejecting or reworking it is the reviewer's call, not this one.
if let Some(open) = run
.and_then(|id| active.iter().find(|r| r.id == id))
.filter(|r| !r.state.is_final())
{
println!(
"{project}: #{} is {}; reject or rework it to dispatch again",
open.id,
open.state.name()
);
continue;
}
let Some(row) = rows
.iter()
.find(|r| &r.name == project && r.absent_since.is_none())
else {
eprintln!("warning: {project} is not under a root; skipped");
continue;
};
picks.push(dispatch::Pick {
workflow: None,
project: project.clone(),
repo: row.path.clone(),
key: format!("campaign:{name}"),
text: campaign.text.clone(),
gh: None,
tier: row.tier,
class: Some(campaign.class),
details: (!campaign.description.trim().is_empty())
.then(|| format!("{}\n", campaign.description.trim_end())),
quadrant: None,
local: false,
});
}
if picks.is_empty() {
println!("every member of `{name}` has a run; see `pma campaign show {name}`");
return Ok(());
}
let wanted = count.unwrap_or(picks.len());
let finished = run_picks(&store, &home, &cfg, &Default::default(), &picks, wanted)?;
for run in &finished {
store.set_campaign_run(name, &run.project, run.id)?;
}
println!("`pma campaign show {name}` lists what each repository did");
Ok(())
}
/// A policy document from a file, stdin, or a stored revision number.
/// A document from a file: a script builds one, JSON is read as one. Both end
/// up as the same `Document`, so everything downstream is one path.
/// The flags, with a named preset read. A flag beside one wins: it is the more
/// specific statement of intent.
fn overrides(
agent: Option<String>,
model: Option<String>,
preset: Option<String>,
) -> Result<dispatch::Overrides> {
let preset = match preset {
None => None,
Some(name) => Some(Store::open_default()?.preset(&name)?),
};
Ok(dispatch::Overrides {
agent,
model,
preset,
})
}
/// A project's record. Bare, it lists the projects: what each is called, its
/// tier, its tags and when it was last scanned.
fn project_command(action: Option<ProjectAction>) -> Result<()> {
let Some(action) = action else {
let store = Store::open_default()?;
let projects = store.projects()?;
if projects.is_empty() {
println!("no projects; `pma root add <dir>` then `pma scan`");
return Ok(());
}
let tags = store.project_tags()?;
let rows: Vec<Vec<String>> = projects
.iter()
.map(|p| {
let mine: Vec<&str> = tags
.iter()
.filter(|(project, _)| *project == p.name)
.map(|(_, tag)| tag.as_str())
.collect();
vec![
p.name.clone(),
match p.tier {
Some(t) => format!("tier {t}"),
None => "untiered".into(),
},
mine.join(","),
match p.absent_since {
Some(_) => "absent".into(),
None => String::new(),
},
match p.scanned_at {
Some(at) => report::ago(dates::now() - at),
None => "never scanned".into(),
},
]
})
.collect();
print!("{}", report::table(&rows, ""));
println!(
"\n`pma project tier <1-5> <project>...` sets tiers; \
`pma project export\n <file.csv>` writes them all to edit at \
once, `import` reads it back."
);
return Ok(());
};
match action {
ProjectAction::Show { name } => show(Query::Project { name }),
ProjectAction::Tier { tier, projects } => set_tier(&tier, &projects),
ProjectAction::Export { file } => export_projects(&file),
ProjectAction::Import { file, apply } => import_projects(&file, apply),
ProjectAction::Tag { action } => tag(action),
ProjectAction::Forget { project, apply } => forget(&project, apply),
ProjectAction::Clone {
projects,
tags,
root,
apply,
} => clone_projects(&projects, &tags, root.as_deref(), apply),
}
}
fn preset_command(action: Option<PresetAction>) -> Result<()> {
let store = Store::open_default()?;
let cfg = api::config(&store)?;
let Some(action) = action else {
let presets = store.presets()?;
if presets.is_empty() {
println!(
"no presets. `pma preset set <name> <agent> [model] [args...]` names one, \n\
and `pma agent` lists each worker and its own default model."
);
return Ok(());
}
let rows: Vec<Vec<String>> = presets
.iter()
.map(|p| {
vec![
format!(
"{} {}",
if cfg.preset.as_deref() == Some(&p.name) {
"*"
} else {
" "
},
p.name
),
p.agent.clone(),
p.model.clone().unwrap_or_else(|| "its own default".into()),
p.args.join(" "),
match store.agent(&p.agent) {
Ok(_) => String::new(),
Err(_) => "no such worker".into(),
},
]
})
.collect();
print!("{}", report::table(&rows, ""));
println!(
"\n* is `pma config preset`. `-p <name>` uses one for a command; \
`pma preset use <name>`\n makes it the default, and `-a` or `-m` beside \
either one wins."
);
return Ok(());
};
match action {
PresetAction::Set {
name,
agent,
model,
args,
} => {
let p = store::Preset {
name: name.clone(),
agent: agent.clone(),
model: model.clone().filter(|m| !m.is_empty()),
args,
};
store.set_preset(&p)?;
println!(
"preset `{name}`: {agent}{}{}",
p.model.map(|m| format!(" at {m}")).unwrap_or_default(),
if p.args.is_empty() {
String::new()
} else {
format!(" with {}", p.args.join(" "))
}
);
}
PresetAction::Use { name } => {
// Read first, so naming one that does not exist changes nothing.
store.preset(&name)?;
store.set_config("preset", &name)?;
println!("`{name}` is the default preset");
}
PresetAction::Rm { name } => {
if !store.remove_preset(&name)? {
return Err(format!("no preset `{name}`").into());
}
if cfg.preset.as_deref() == Some(name.as_str()) {
store.set_config("preset", "")?;
}
}
}
Ok(())
}
fn workflow_document(file: &str) -> Result<(workflow::Document, Option<String>)> {
let text = if file == "-" {
let mut text = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut text)?;
text
} else {
std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?
};
if file.ends_with(".rhai") {
Ok((workflow::Document::from_script(&text, file)?, Some(text)))
} else {
Ok((workflow::Document::parse(&text)?, None))
}
}
/// Per node, and the total. `units` is the argument bag the estimate assumes.
fn workflow_estimate(
doc: &workflow::Document,
w: &workflow::Workflow,
units: i64,
budget: f64,
) -> Result<workflow::Estimate> {
let estimate = doc.estimate(&w.name, units, budget)?;
// The rows are the flat graph's nodes, so the op each one applies is read
// from there rather than from the call site the document wrote.
let flat = doc.flatten(&w.name)?;
let effects = match w.effects.names().as_slice() {
[] => "pure".to_string(),
names => names.join(" "),
};
println!(
"{}(in: [{}]{}) -> [{}] {effects}",
w.name,
w.input,
w.params
.iter()
.map(|(k, p)| format!(", {k} = {}", p.default))
.collect::<String>(),
w.output.as_deref().unwrap_or("")
);
let mut rows = vec![
["node", "op", "in", "out", "runs", "agent runs"]
.iter()
.map(|s| (*s).to_string())
.collect::<Vec<_>>(),
];
for b in &estimate.per_node {
let op = match flat.node(&b.node).map(|n| &n.op) {
Some(workflow::Op::Map(m)) => format!("map {}", m.out.name()),
Some(op) => op.name().to_string(),
None => String::new(),
};
rows.push(vec![
b.node.clone(),
op,
b.units_in.to_string(),
b.units_out.to_string(),
b.runs.to_string(),
b.agent_runs.to_string(),
]);
}
print!("{}", report::table(&rows, " "));
println!(
" worst case: {} agent runs, {} edits, ${:.2} at ${:.2} per run\n",
estimate.agent_runs, estimate.edits, estimate.cost, budget
);
Ok(estimate)
}
fn workflow_command(action: Option<WorkflowAction>) -> Result<()> {
let Some(action) = action else {
return show(Query::Workflows);
};
match action {
WorkflowAction::Check {
file,
units,
emit_json,
} => {
if emit_json {
if !file.ends_with(".rhai") {
return Err(
"--emit-json prints what a script built; this is already JSON".into(),
);
}
let text = std::fs::read_to_string(&file).map_err(|e| format!("{file}: {e}"))?;
println!(
"{}",
serde_json::to_string_pretty(&script::script_json(&text, &file)?)?
);
return Ok(());
}
let (doc, _) = workflow_document(&file)?;
// A document is read without a store when there is none; the
// budget only scales the estimate.
let budget = Store::open_default()
.and_then(|s| api::config(&s))
.map_or(Config::default().agent_budget, |c| c.agent_budget);
for w in &doc.workflows {
workflow_estimate(&doc, w, units, budget)?;
}
if let Ok(store) = Store::open_default() {
for w in &doc.workflows {
warn_unrouted(&store, &doc.flatten(&w.name)?)?;
}
}
let unbuilt = doc.unbuilt();
if !unbuilt.is_empty() {
println!("not runnable yet, so `propose` refuses it:");
for u in &unbuilt {
println!(" {u}");
}
}
Ok(())
}
WorkflowAction::Propose { file, by } => {
let store = Store::open_default()?;
let cfg = api::config(&store)?;
let (doc, source) = workflow_document(&file)?;
// A revision is what runs. One that states a construct the
// runtime does not take would run as something other than its
// text, so it is refused here rather than ignored there.
let unbuilt = doc.unbuilt();
if !unbuilt.is_empty() {
return Err(format!(
"not runnable yet:\n {}\n`pma workflow check` still prices it",
unbuilt.join("\n ")
)
.into());
}
// Over one unit of input: the argument bag is not known until a
// pass names its target, so the stored figure is per unit and a
// pass multiplies it.
let mut runs = 0;
let mut cost = 0.0f64;
for w in &doc.workflows {
let estimate = workflow_estimate(&doc, w, 1, cfg.agent_budget)?;
runs = runs.max(estimate.agent_runs);
cost = cost.max(estimate.cost);
}
let n = store.add_workflow_revision(
&doc,
source.as_deref(),
&by.unwrap_or_else(whoami),
runs,
cost,
)?;
println!(
"revision {n} stored as a draft: at most ${cost:.2} per unit of input.\n\
`pma workflow activate {n}` puts it in effect."
);
Ok(())
}
WorkflowAction::Activate { revision, by } => {
let store = Store::open_default()?;
let cfg = api::config(&store)?;
let found = store
.workflow_revisions()?
.into_iter()
.find(|r| r.revision == revision)
.ok_or_else(|| format!("no workflow revision {revision}"))?;
// The ceiling is per unit of input, and it is checked here rather
// than at parse: the document is not wrong, the budget is a
// setting.
if let Some(cost) = found.worst_case_cost
&& cost > cfg.workflow_budget
{
return Err(format!(
"revision {revision} could cost ${cost:.2} per unit of input, over \
workflow_budget of ${:.2}. Lower a cap, or raise the budget with \
`pma config workflow_budget <n>`.",
cfg.workflow_budget
)
.into());
}
store.activate_workflow(revision, &by.unwrap_or_else(whoami))?;
println!("revision {revision} is in effect");
let doc = found.document()?;
for w in &doc.workflows {
warn_unrouted(&store, &doc.flatten(&w.name)?)?;
}
Ok(())
}
WorkflowAction::Run {
name,
projects,
tag,
instance,
set,
dry_run,
approve,
unattended,
local,
detach,
cap,
agent,
model,
preset,
} => {
if detach {
return jobs::enqueue(&Store::open_default()?);
}
let store = Store::open_default()?;
// A pass runs agents and edits worktrees, so it holds the session
// lock for its whole run, as `pma dispatch` does.
let session = Session::acquire(&store::home()?)?;
store.fail_interrupted_runs(&session)?;
let cfg = api::config(&store)?;
// The flags cover the whole pass and are not stored: a pass
// resolves its worker exactly as a dispatch does.
// Kept for a job that stops at a plan: its approval must resolve
// the same worker, or the plan id differs.
let flags: Vec<String> = [("-a", &agent), ("-m", &model), ("-p", &preset)]
.into_iter()
.filter_map(|(f, v)| v.as_ref().map(|v| [f.to_string(), v.clone()]))
.flatten()
.collect();
let over = overrides(agent, model, preset)?;
// An instance is frozen at the revision it started under. Reading
// the active revision instead would walk units one graph wrote
// with another graph's edge indexes.
let revision = match instance {
Some(id) => {
let found = store.workflow_instance(id)?.ok_or_else(|| {
format!("no workflow instance {id}; `pma workflow` lists them")
})?;
if found.workflow != name {
return Err(format!(
"instance {id} runs `{}`, not `{name}`",
found.workflow
)
.into());
}
match found.outcome.as_deref() {
Some("stopped") => {
return Err(format!("instance {id} was stopped").into());
}
Some("capped") if cap.is_empty() => {
return Err(format!(
"instance {id} stopped: capped. Resume it with a higher cap: \
`--cap max_units=<n>` or `--cap max_edits=<n>`"
)
.into());
}
_ => {}
}
if !projects.is_empty() || tag.is_some() || !set.is_empty() {
return Err(format!(
"instance {id} holds the target and arguments it started with; \
`--instance` takes no projects, no `--tag` and no `--set`"
)
.into());
}
store.workflow_revision(found.revision)?.ok_or_else(|| {
format!(
"instance {id} ran under revision {}, which is gone",
found.revision
)
})?
}
None => store
.active_workflow()?
.ok_or("no workflow revision is in effect; `pma workflow activate <rev>`")?,
};
let doc = revision.document()?;
if doc.workflow(&name).is_none() {
return Err(
format!("revision {} has no workflow `{name}`", revision.revision).into(),
);
}
// A pass walks the flat graph: a call is resolved before anything
// runs, so the frontier, the caps and the edge indexes a move is
// keyed by are all one graph's.
let mut w = doc.flatten(&name)?;
let (instance, args) = match instance {
Some(id) => {
let found = store.workflow_instance(id)?.expect("loaded above");
let mut args: serde_json::Value =
serde_json::from_str(&found.args).unwrap_or(serde_json::json!({}));
if !cap.is_empty() {
raise_caps(&mut args, &w.caps, &cap)?;
store.reopen_instance(id, &args.to_string())?;
println!("instance {id}: caps raised, recorded on the instance");
}
(id, args)
}
None => {
let mut names = projects.clone();
if let Some(tag) = &tag {
for (project, t) in store.project_tags()? {
if t == *tag && !names.contains(&project) {
names.push(project);
}
}
}
let mut args = serde_json::to_value(w.bind(&set)?)?;
if local {
args["@local"] = serde_json::Value::Bool(true);
}
let units = pass::root_units(&store, &doc, &name, &names)?;
// The per-unit ceiling was weighed at activation. What a
// pass spends is bounded by `batch_budget` and by the plan
// approved for it.
let estimate = doc.estimate(&name, units.len() as i64, cfg.agent_budget)?;
// A dry run plans and prices and writes nothing: an
// instance it left behind would be an open instance
// nobody meant to start.
if dry_run {
let moves: Vec<(String, usize, bool)> = units
.iter()
.flat_map(|u| {
pass::entry_moves(&w, u)
.into_iter()
.map(move |(edge, taken, _)| (u.id.clone(), edge, taken))
})
.collect();
let (rules, plan) =
pass::plan_over(&store, &cfg, &over, &w, &args, &units, &moves)?;
println!(
"`{name}` over {} unit(s), at most ${:.2} in all",
units.len(),
estimate.cost
);
warn_unrouted(&store, &w)?;
print_dry_run(&rules, &plan);
return Ok(());
}
let target = match &tag {
Some(t) => format!("--tag {t}"),
None => names.join(" "),
};
// The instance and its argument bag are written together:
// a half-entered bag would be a frozen target missing units.
let id = store.atomically(|| {
let id = store.add_workflow_instance(
&name,
revision.revision,
&args.to_string(),
&target,
)?;
for unit in &units {
store.add_workflow_unit(id, unit)?;
pass::enter(&store, id, &w, unit)?;
}
Ok(id)
})?;
println!(
"instance {id} of `{name}`: {} unit(s), at most ${:.2} in all",
units.len(),
estimate.cost
);
(id, args)
}
};
if let Some(caps) = args.get("@caps") {
w.caps.max_units = caps["max_units"].as_i64().unwrap_or(w.caps.max_units);
w.caps.max_edits = caps["max_edits"].as_i64().unwrap_or(w.caps.max_edits);
}
if dry_run {
let (rules, plan) = pass::plan(&store, &cfg, &over, &w, &args, instance)?;
warn_unrouted(&store, &w)?;
print_dry_run(&rules, &plan);
return Ok(());
}
let home = store::state_home()?;
let given = pass::Invocation {
home: &home,
args: &args,
approve: approve.as_deref(),
unattended,
};
let outcome = pass::advance(&store, &cfg, &over, &doc, &w, instance, &given)?;
for refused in &outcome.refused {
eprintln!("refused: {refused}");
}
if outcome.ran {
if let Some(plan) = &approve {
store.settle_jobs_awaiting(plan)?;
}
println!("the approved plan ran; `pma review` lists any edits it made");
}
for line in &outcome.landed {
println!("{line}");
}
if outcome.plan.is_empty() {
if outcome.waiting.is_empty() {
store.finish_instance(instance, "finished")?;
let _ = std::fs::remove_dir_all(
home.join("workflow-trees").join(instance.to_string()),
);
println!("instance {instance}: nothing left to run");
} else {
for (node, n) in &outcome.waiting {
println!("waiting at {node}: {n} unit(s)");
}
println!(
"instance {instance} is waiting on a check; run it again later with \
`pma workflow run {name} --instance {instance}`"
);
}
return Ok(());
}
let plan = &outcome.plan;
let job = jobs::current();
if let Some(job) = job {
let mut approve = vec![
"workflow".to_string(),
"run".into(),
name.clone(),
"--instance".into(),
instance.to_string(),
"--approve".into(),
plan.id(),
];
approve.extend(flags);
store.set_job_awaiting(job, &approve)?;
}
print!("{}", pass::describe(&plan.steps, "next: "));
let how = match job {
Some(job) => format!("pma job approve {job}"),
None => format!(
"pma workflow run {name} --instance {instance} --approve {}",
plan.id()
),
};
println!(
"\nplan {}: at most ${:.2}. Nothing was spent on it. Approve it with `{how}`.",
plan.id(),
plan.cost(),
);
Ok(())
}
WorkflowAction::Stop { instance } => {
say(api::act(
&Store::open_default()?,
Action::StopWorkflow { instance },
)?);
Ok(())
}
WorkflowAction::Show { revision } => {
let store = Store::open_default()?;
let found = match revision {
Some(n) => store
.workflow_revisions()?
.into_iter()
.find(|r| r.revision == n),
None => store.active_workflow()?,
}
.ok_or("no such workflow revision; `pma workflow` lists them")?;
println!("{}", found.document);
Ok(())
}
}
}
/// Names each agent node the routing policy in effect would refuse.
fn warn_unrouted(store: &Store, w: &workflow::Workflow) -> Result<()> {
for warning in pass::unrouted(store, w)? {
eprintln!("warning: {warning}");
}
Ok(())
}
/// What a dry run shows: the rule nodes that would run, then the agent runs,
/// with the plan's id when a first pass would print the same plan.
fn print_dry_run(rules: &[pass::Planned], plan: &pass::Plan) {
let mut steps = rules.to_vec();
steps.extend(plan.steps.iter().cloned());
print!("{}", pass::describe(&steps, "would run: "));
if rules.is_empty() && !plan.is_empty() {
println!(
"plan {}: at most ${:.2}; `--approve {}` runs it",
plan.id(),
plan.cost(),
plan.id()
);
}
}
/// Records raised caps on an instance's arguments, under `@caps`, which no
/// parameter can be named. A cap may only go up: lowering one under work
/// already written would describe an instance that never existed.
fn raise_caps(
args: &mut serde_json::Value,
declared: &workflow::Caps,
given: &[String],
) -> Result<()> {
let mut caps = args
.get("@caps")
.cloned()
.unwrap_or_else(|| serde_json::json!({}));
for g in given {
let (key, value) = g
.split_once('=')
.ok_or_else(|| format!("`{g}`: expected max_units=N or max_edits=N"))?;
let current = match key {
"max_units" => declared.max_units,
"max_edits" => declared.max_edits,
_ => {
return Err(
format!("`{key}` is not a cap; expected max_units or max_edits").into(),
);
}
};
let current = caps[key].as_i64().unwrap_or(current);
let n: i64 = value
.parse()
.map_err(|_| format!("`{g}`: expected a whole number"))?;
if n <= current {
return Err(format!("`{key}` is {current}; a raised cap must be higher").into());
}
caps[key] = serde_json::Value::from(n);
}
if !args.is_object() {
*args = serde_json::json!({});
}
args["@caps"] = caps;
Ok(())
}
fn policy_text(store: &Store, from: &str) -> Result<String> {
if from == "-" {
let mut text = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut text)?;
return Ok(text);
}
if let Ok(n) = from.parse::<i64>() {
return store
.route_revisions()?
.into_iter()
.find(|r| r.revision == n)
.map(|r| r.document)
.ok_or_else(|| format!("no policy revision {n}").into());
}
std::fs::read_to_string(from).map_err(|e| format!("{from}: {e}").into())
}
fn route_command(action: Option<RouteAction>) -> Result<()> {
let store = Store::open_default()?;
let Some(action) = action else {
let revisions = store.route_revisions()?;
if revisions.is_empty() {
println!(
"no routing policy; dispatch uses `pma config agent` and each task's class.\n\
`pma route propose <file>` stores one."
);
return Ok(());
}
let rows: Vec<Vec<String>> = revisions
.iter()
.map(|r| {
let state = match (r.activated_at, r.shadow) {
(None, _) => "draft".to_string(),
(Some(_), true) => {
format!("shadow, by {}", r.activated_by.as_deref().unwrap_or("?"))
}
(Some(_), false) => {
format!("active, by {}", r.activated_by.as_deref().unwrap_or("?"))
}
};
let routes = r.policy().map(|p| p.routes.len()).unwrap_or(0);
vec![
format!("{}", r.revision),
state,
format!("{routes} routes"),
format!("proposed by {}", r.proposed_by),
report::ago(dates::now() - r.created_at),
]
})
.collect();
print!("{}", report::table(&rows, ""));
return Ok(());
};
match action {
RouteAction::Propose { file, by } => {
let text = policy_text(&store, &file)?;
let n = store.add_route_revision(&text, &by.unwrap_or_else(whoami))?;
println!("revision {n} stored as a draft; `pma route activate {n}` puts it in effect");
}
RouteAction::Activate {
revision,
shadow,
by,
} => {
store.activate_route(revision, &by.unwrap_or_else(whoami), shadow)?;
println!(
"revision {revision} is {}",
if shadow {
"in shadow: routes are recorded, not applied"
} else {
"in effect"
}
);
}
RouteAction::Show { revision } => {
let doc = match revision {
Some(n) => policy_text(&store, &n.to_string())?,
None => {
store
.active_route()?
.ok_or("no revision is in effect; name one")?
.document
}
};
print!("{doc}");
if !doc.ends_with('\n') {
println!();
}
}
RouteAction::Replay { file } => {
let policy = route::Policy::parse(&policy_text(&store, &file)?)?;
let runs = store.runs()?;
let (differences, compared) = route::replay(&policy, &runs);
if compared == 0 {
println!("no run carries a class and a complexity to replay against");
return Ok(());
}
println!(
"{compared} runs replayed, {} routed differently",
differences.len()
);
if !differences.is_empty() {
let rows: Vec<Vec<String>> = differences
.iter()
.map(|d| {
vec![
format!(" #{}", d.run),
d.was.clone(),
"->".into(),
d.would_be.clone(),
]
})
.collect();
print!("{}", report::table(&rows, ""));
}
println!(
"\nCost is not projected. What a different model would spend, or whether it \n\
would succeed, is not in this data; only a canary settles that."
);
}
}
Ok(())
}
fn agent_command(action: Option<AgentAction>) -> Result<()> {
let store = Store::open_default()?;
let Some(action) = action else {
let cfg = api::config(&store)?;
let rows: Vec<Vec<String>> = store
.agents()?
.iter()
.map(|w| {
let mut flags: Vec<&str> = Vec::new();
if w.reports_cost {
flags.push("cost");
}
if w.enforces_budget {
flags.push("budget");
}
if w.sandbox {
flags.push("sandbox");
}
if w.allow.is_some() {
flags.push("allowlist");
}
if w.resumes {
flags.push("resumes");
}
vec![
if w.name == cfg.agent {
format!("* {}", w.name)
} else {
format!(" {}", w.name)
},
w.command.clone(),
w.parse.name(),
if flags.is_empty() {
"-".into()
} else {
flags.join(",")
},
]
})
.collect();
if rows.is_empty() {
println!("no agents; `pma agent set <name> command <program>` adds one");
} else {
print!("{}", report::table(&rows, ""));
println!(
"\n* is `pma config agent`. A worker is how to run a program; which model \
it runs\n at is a preset (`pma preset`). Flags are cost reported, budget \
enforced, sandbox,\n allowlist and resume; `pma agent show <name>` prints \
the rest."
);
}
return Ok(());
};
match action {
AgentAction::Show { name } => {
let w = store.agent(&name)?;
let rows = vec![
vec!["command".into(), w.command.clone()],
vec![
"args".into(),
serde_json::to_string(&w.args).unwrap_or_default(),
],
vec![
"allow".into(),
w.allow.clone().unwrap_or_else(|| "none".into()),
],
vec!["parse".into(), w.parse.name()],
vec!["reports-cost".into(), w.reports_cost.to_string()],
vec!["enforces-budget".into(), w.enforces_budget.to_string()],
vec!["sandbox".into(), w.sandbox.to_string()],
vec!["resumes".into(), w.resumes.to_string()],
vec![
"env".into(),
serde_json::to_string(&w.env).unwrap_or_default(),
],
];
print!("{}", report::table(&rows, ""));
}
AgentAction::Rm { name } => {
if !store.remove_agent(&name)? {
return Err(format!("unknown agent `{name}`").into());
}
}
AgentAction::Set { name, field, value } => {
let mut w = store.agent(&name).unwrap_or_else(|_| worker::Worker {
name: name.clone(),
command: String::new(),
args: Vec::new(),
allow: None,
parse: worker::Parser::TextTail,
reports_cost: false,
enforces_budget: false,
sandbox: false,
resumes: false,
env: std::collections::BTreeMap::new(),
});
let flag = |v: &str| match v {
"true" | "yes" => Ok(true),
"false" | "no" => Ok(false),
_ => Err(format!("expected true or false, not `{v}`")),
};
match field.as_str() {
"command" => w.command = value,
"args" => {
w.args = serde_json::from_str(&value)
.map_err(|e| format!("args must be a JSON array of strings: {e}"))?;
}
"allow" => w.allow = (!value.is_empty()).then_some(value),
"parse" => {
w.parse = worker::Parser::parse(&value).ok_or_else(|| {
format!(
"unknown parser `{value}`; expected {}",
worker::Parser::names()
)
})?;
}
"reports-cost" => w.reports_cost = flag(&value)?,
"enforces-budget" => w.enforces_budget = flag(&value)?,
"sandbox" => w.sandbox = flag(&value)?,
"resumes" => w.resumes = flag(&value)?,
"model" => {
return Err(format!(
"a worker no longer names a model: \
`pma preset set <name> {name} {value}`"
)
.into());
}
"env" => {
w.env = serde_json::from_str(&value)
.map_err(|e| format!("env must be a JSON object of name to value: {e}"))?;
}
_ => {
let names: Vec<&str> = worker::FIELDS.iter().map(|(n, _)| *n).collect();
return Err(
format!("unknown field `{field}`; expected {}", names.join(", ")).into(),
);
}
}
if w.command.is_empty() {
return Err(format!("set `command` for `{name}` first").into());
}
store.set_agent(&w)?;
}
}
Ok(())
}
fn run_report(by: Option<&str>) -> Result<()> {
let by = match by {
None => report_runs::By::Class,
Some(s) => report_runs::By::parse(s).ok_or_else(|| {
let names: Vec<&str> = report_runs::By::ALL.iter().map(|(n, _)| *n).collect();
format!("unknown dimension `{s}`; expected {}", names.join(", "))
})?,
};
show(Query::Report { by })
}
fn run_verify(projects: &[String], tags: &[String]) -> Result<()> {
let store = Store::open_default()?;
let home = store::state_home()?;
// It adds and removes a worktree, as a dispatch does.
let _session = Session::acquire(&store::home()?)?;
let cfg = api::config(&store)?;
let names = select(&store, projects, tags)?;
if names.is_empty() {
return Err("name a project, or --tag".into());
}
let rows = store.projects()?;
let mut failed = 0;
for name in &names {
let row = rows
.iter()
.find(|r| &r.name == name)
.ok_or_else(|| format!("unknown project `{name}`"))?;
if row.absent_since.is_some() {
return Err(format!("{name} is not under a root; run `pma scan`").into());
}
let p = dispatch::preflight(&store, &home, &cfg, name, &row.path)?;
let at = &p.base[..p.base.len().min(7)];
let log = p
.log
.as_ref()
.map_or(String::new(), |l| format!("; log: {}", l.display()));
let line = match (&p.command, p.ok) {
(None, _) => {
format!("no verify command; set `pma config projects.{name}.verify <command>`")
}
(Some(c), Some(true)) => format!("`{c}` passed at {at} in {}s", p.seconds),
(Some(c), Some(false)) => format!("`{c}` FAILED at {at} in {}s{log}", p.seconds),
(Some(c), None) => {
format!("`{c}` did not finish at {at}: timed out or could not start{log}")
}
};
if p.ok != Some(true) {
failed += 1;
}
println!("{name}: {line}");
}
match failed {
0 => Ok(()),
n => Err(format!("{n} of {} projects did not pass their check", names.len()).into()),
}
}
/// Publishes the named runs one way: `pma pr` or `pma push`. Every run is
/// checked before any is published, so a list with one run that is not
/// approved changes nothing. `all` takes every approved run instead.
fn run_publish(ids: &[i64], all: bool, target: publish::Target) -> Result<()> {
let store = Store::open_default()?;
let _session = Session::acquire(&store::home()?)?;
let cfg = api::config(&store)?;
let mut runs = Vec::new();
if all {
runs = store.runs()?;
runs.retain(|r| r.state == RunState::Approved);
if runs.is_empty() {
println!("no approved runs");
return Ok(());
}
}
for id in ids {
let run = store.run(*id)?;
if run.state != RunState::Approved {
return Err(format!(
"run #{id} is {}; only an approved run is published. `pma review {id}` shows it",
run.state.name()
)
.into());
}
if !runs.iter().any(|r: &store::Run| r.id == run.id) {
runs.push(run);
}
}
runs.sort_by_key(|r| r.id);
let mut failed = 0;
publish::publish(
&store,
&store::state_home()?,
&cfg,
runs,
target,
|run, outcome| match outcome {
Ok(o) => println!("#{} {}: {o}", run.id, run.project),
Err(e) => {
failed += 1;
println!("#{} {}: {e}", run.id, run.project);
}
},
)?;
if failed > 0 {
return Err(format!("{failed} runs not published; they stay approved").into());
}
Ok(())
}
fn run_sync(names: &[String], tags: &[String], apply: bool) -> Result<()> {
let store = Store::open_default()?;
let names = &select(&store, names, tags)?;
let rows = store.projects()?;
for n in names {
if !rows.iter().any(|r| &r.name == n) {
return Err(format!("unknown project `{n}`").into());
}
}
let me = sync::login()?;
let (mut changes, mut failed, mut edited) = (0, 0, Vec::new());
for row in rows
.iter()
.filter(|r| names.is_empty() || names.contains(&r.name))
{
if row.absent_since.is_some() {
if !names.is_empty() {
println!("{}: skipped: not under a root", row.name);
}
continue;
}
let path = row.path.join("TODO.md");
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let skip = |why: &str| println!("{}: skipped: {why}", row.name);
let parsed = todo::parse(&text);
if parsed.has_errors() {
skip("TODO.md has lint errors; see `pma lint`");
continue;
}
let Some(repo) = row.slug.as_deref() else {
if !names.is_empty() {
skip("no GitHub origin recorded; run `pma scan`");
}
continue;
};
let issues = match sync::issues(repo) {
Ok(i) => i,
Err(e) => {
skip(&e);
failed += 1;
continue;
}
};
let actions = sync::plan(&parsed, &issues, &me);
for a in &actions {
match a.line() {
Some(line) => println!("{}:{line}: {}", row.name, a.describe()),
None => println!("{}: {}", row.name, a.describe()),
}
}
let planned = actions.iter().filter(|a| a.is_change()).count();
if !apply || planned == 0 {
changes += planned;
continue;
}
let before = text;
match sync::apply(repo, &path, &actions) {
Ok(n) => changes += n,
Err(e) => {
println!("{}: stopped: {e}", row.name);
failed += 1;
}
}
if std::fs::read_to_string(&path).is_ok_and(|after| after != before) {
edited.push(row.name.clone());
}
}
if changes == 0 && failed == 0 {
println!("in sync");
} else if apply {
println!("{changes} changes made");
} else if changes > 0 {
println!("{changes} changes; run `pma sync --apply` to make them");
}
if !edited.is_empty() {
println!(
"TODO.md changed, uncommitted, in: {}; commit, then `pma scan`",
edited.join(", ")
);
}
if failed > 0 {
return Err(format!("{failed} projects not synced").into());
}
Ok(())
}
fn note(action: Option<NoteAction>) -> Result<()> {
let store = Store::open_default()?;
let words = |w: Vec<String>| w.join(" ");
match action {
None => print!("{}", render(api::query(&store, Query::Notes)?)),
Some(NoteAction::Add { text }) => {
say(api::act(&store, Action::AddNote { text: words(text) })?)
}
Some(NoteAction::Edit { id, text }) => say(api::act(
&store,
Action::EditNote {
id,
text: words(text),
},
)?),
Some(NoteAction::Rm { id }) => say(api::act(&store, Action::RemoveNote { id })?),
}
Ok(())
}
fn run_watch(once: bool) -> Result<()> {
use std::io::IsTerminal;
let store = Store::open_default()?;
let tty = std::io::stdout().is_terminal();
loop {
let view = api::query(&store, Query::Agents)?;
let View::Agents { jobs, runs, .. } = &view else {
unreachable!("an agents query returns agents");
};
let busy = jobs
.iter()
.any(|j| matches!(j.state.as_str(), "queued" | "running"))
|| runs.iter().any(|r| r.state == store::RunState::Running);
if tty && !once {
// Clear the screen and home the cursor.
print!("\x1b[2J\x1b[H");
}
print!("{}", render(view));
if once || !busy {
return Ok(());
}
std::thread::sleep(std::time::Duration::from_secs(2));
}
}
fn run_job(action: Option<JobAction>) -> Result<()> {
let store = Store::open_default()?;
match action {
None => print!("{}", render(api::query(&store, Query::Jobs)?)),
Some(JobAction::Log { id }) => {
print!("{}", render(api::query(&store, Query::JobLog { id })?))
}
Some(JobAction::Stop { id }) => say(api::act(&store, Action::StopJob { id })?),
Some(JobAction::Approve { id }) => say(api::act(&store, Action::ApproveJob { id })?),
}
Ok(())
}
fn run_tui() -> Result<()> {
use std::io::IsTerminal;
if !std::io::stdout().is_terminal() {
return Err("pma tui needs a terminal; use `pma next` or `pma matrix` otherwise".into());
}
tui::run(&Store::open_default()?)
}
#[cfg(feature = "web")]
fn run_web(no_open: bool, app: bool, port: u16) -> Result<()> {
// Opened here first, so a bad store or settings file fails now rather
// than on the page's first request.
Store::open_default()?;
let server = pma_web::Server::bind(port)?;
let url = server.url();
println!("pma web: {url}\nCtrl-C stops it.");
let opened = match (no_open, app) {
(true, _) => Ok(()),
(false, true) => pma_web::open_app(&url),
(false, false) => pma_web::open_browser(&url),
};
if let Err(e) = opened {
eprintln!("warning: {e}; open the address yourself");
}
server.serve()
}
fn selection(names: &[String], tags: &[String]) -> Selection {
Selection {
projects: names.to_vec(),
tags: tags.to_vec(),
}
}
/// Prints what an action said.
fn say(out: api::Outcome) {
for line in out.said {
println!("{line}");
}
for line in out.warnings {
eprintln!("warning: {line}");
}
}
fn show(q: Query) -> Result<()> {
show_with(&Store::open_default()?, q)
}
fn show_with(store: &Store, q: Query) -> Result<()> {
let view = api::query(store, q)?;
if let View::Run {
run, moved: true, ..
} = &view
{
eprintln!(
"warning: run #{} changed while it was shown; read it again before approving",
run.id
);
}
print!("{}", render(view));
Ok(())
}
/// A view as the CLI prints it.
fn render(view: View) -> String {
match view {
View::Next {
header,
lists,
limit,
} => format!("{header}\n\n{}", next::render(&lists, limit)),
View::Matrix {
header,
placed,
limit,
quadrant,
today,
} => format!(
"{header}\n\n{}",
report::matrix(&placed, limit, quadrant, today)
),
View::Status {
header,
portfolio: p,
explain,
} => {
let rows: Vec<report::StatusRow> = p
.projects
.iter()
.map(|(project, row)| report::StatusRow {
project,
tiered: row.tier.is_some() || p.cfg.default_tier.is_some(),
has_todo: row.has_todo,
lint_errors: row.lint_errors,
scan_error: row.scan_error.as_deref(),
})
.collect();
format!("{header}\n\n{}", report::status(&p.cfg, &rows, explain))
}
View::Stale {
header,
placed,
limit,
} => format!("{header}\n\n{}", report::stale(&placed, limit)),
View::Report { runs, attempts, by } => report_runs::report(&runs, &attempts, by),
View::Runs(runs) => match runs.is_empty() {
true => "no runs to review\n".into(),
false => report::runs(&runs),
},
View::Run {
run,
attempts,
changelog,
diff,
..
} => report::run_detail(&run, &attempts, changelog.as_deref(), &diff),
View::Agents {
state,
jobs,
runs,
now,
} => watch::screen(&state, &jobs, &runs, now),
View::Jobs(all) => jobs::list(&all),
View::JobLog { id, text } => {
text.unwrap_or_else(|| format!("job {id} has no output yet\n"))
}
View::Notes(notes) => {
let rows: Vec<Vec<String>> = notes
.into_iter()
.map(|n| {
vec![
format!("#{}", n.id),
dates::format(dates::day(n.updated_at)),
n.text,
]
})
.collect();
let none = match rows.is_empty() {
true => "no notes; add one with `pma note add <text>`\n",
false => "",
};
format!("{none}{}", report::table(&rows, ""))
}
View::Workflows {
revisions,
instances,
} => {
if revisions.is_empty() {
return "no workflow revisions. `pma workflow check <file>` reads a document, \n\
`pma workflow propose <file>` stores one.\n"
.into();
}
let rows: Vec<Vec<String>> = revisions
.iter()
.map(|r| {
let state = match r.activated_at {
None => "draft".to_string(),
Some(_) => {
format!("active, by {}", r.activated_by.as_deref().unwrap_or("?"))
}
};
let names = r
.document()
.map(|d| {
d.workflows
.iter()
.map(|w| w.name.clone())
.collect::<Vec<_>>()
.join(", ")
})
.unwrap_or_default();
vec![
format!("{}", r.revision),
state,
names,
match (r.worst_case_runs, r.worst_case_cost) {
(Some(runs), Some(cost)) => {
format!("<= {runs} runs, ${cost:.2} per unit")
}
_ => String::new(),
},
format!("proposed by {}", r.proposed_by),
report::ago(dates::now() - r.created_at),
]
})
.collect();
let mut out = report::table(&rows, "");
if !instances.is_empty() {
let rows: Vec<Vec<String>> = instances
.iter()
.map(|i| {
vec![
format!("instance {}", i.id),
i.workflow.clone(),
i.target.clone(),
i.outcome.clone().unwrap_or_else(|| "open".into()),
report::ago(dates::now() - i.started_at),
]
})
.collect();
out.push('\n');
out.push_str(&report::table(&rows, ""));
}
out
}
View::Campaigns(all) => {
if all.is_empty() {
return "no campaigns; `pma campaign add <name> <text> --projects a,b` defines one\n"
.into();
}
let rows: Vec<Vec<String>> = all
.iter()
.map(|c| {
let taken = c.members.iter().filter(|(_, r)| r.is_some()).count();
vec![
c.name.clone(),
format!("class {}", c.class.name()),
format!("{taken}/{} dispatched", c.members.len()),
report::truncate(&c.text, 50),
]
})
.collect();
report::table(&rows, "")
}
View::Project {
name,
path,
scanned_at,
tags,
verify,
status,
placed,
today,
runs,
} => {
let mut out = format!("{name} {}\n", path.display());
match status {
None => out.push_str("not found by the last scan\n"),
Some((states, cells)) => {
let mut rows: Vec<Vec<String>> = report::STATUS_HEADINGS
.iter()
.zip(&cells)
.skip(1)
.map(|(h, c)| vec![format!(" {h}"), c.clone()])
.collect();
rows.extend(
states
.iter()
.filter(|(_, why)| !why.is_empty())
.map(|(st, why)| vec![format!(" {}", st.name()), why.clone()]),
);
out.push_str(&report::table(&rows, ""));
}
}
out.push_str(&format!(
" verify {}\n scanned {}\n",
verify.as_deref().unwrap_or("detected at dispatch"),
scanned_at.map_or("never".into(), |t| report::ago(dates::now() - t))
));
if !tags.is_empty() {
out.push_str(&format!(" tags {}\n", tags.join(", ")));
}
out.push_str(&format!("\nOpen tasks: {}\n", placed.len()));
let tasks: Vec<Vec<String>> = placed
.iter()
.map(|p| {
vec![
format!(
" {}",
p.task.line.map_or(p.task.project.clone(), |l| format!(
"{}:{l}",
p.task.project
))
),
p.task.priority.name().into(),
report::when(p, today),
report::truncate(&p.task.text, 70),
]
})
.collect();
out.push_str(&report::table(&tasks, ""));
out.push_str(&format!("\nRuns: {}\n", runs.len()));
match runs.is_empty() {
true => out.push_str(" none yet\n"),
false => out.push_str(&report::runs(&runs)),
}
out
}
View::Campaign { campaign: c, runs } => {
let rows: Vec<Vec<String>> = c
.members
.iter()
.map(|(project, run)| {
let state = match run.and_then(|id| runs.iter().find(|r| r.id == id)) {
None => "not dispatched".to_string(),
Some(r) => format!(
"#{} {}{}",
r.id,
r.state.name(),
r.outcome
.as_deref()
.map_or(String::new(), |o| format!(" {o}"))
),
};
vec![format!(" {project}"), state]
})
.collect();
format!("{}: {}\n{}", c.name, c.text, report::table(&rows, ""))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A front end queues a long action as the CLI command it names, so each
/// one must be a command the CLI accepts, or the job fails on start.
#[test]
fn every_queued_action_is_a_command_the_cli_parses() {
let of = Selection {
projects: vec!["a".into()],
tags: vec!["t".into()],
};
let worker = api::WorkerChoice {
agent: Some("claude".into()),
model: Some("haiku".into()),
preset: Some("p".into()),
};
let queued = [
Action::Scan {
of: of.clone(),
offline: false,
deps: true,
},
Action::Scan {
of: of.clone(),
offline: true,
deps: false,
},
Action::Dispatch {
targets: vec![],
tags: vec!["t".into()],
auto: true,
count: Some(2),
retry: false,
worker: worker.clone(),
},
Action::Dispatch {
targets: vec!["a:3".into()],
tags: vec![],
auto: false,
count: None,
retry: true,
worker: worker.clone(),
},
Action::WorkflowRun {
name: "w".into(),
projects: vec!["a".into()],
tag: Some("t".into()),
instance: None,
set: vec!["x=1".into()],
approve: None,
unattended: true,
local: true,
cap: vec![],
worker: worker.clone(),
},
Action::WorkflowRun {
name: "w".into(),
projects: vec![],
tag: None,
instance: Some(3),
set: vec![],
approve: Some("abc".into()),
unattended: false,
local: false,
cap: vec!["max_units=9".into()],
worker,
},
Action::ReworkRun {
id: 4,
feedback: "--not a flag".into(),
},
Action::Publish {
ids: vec![],
all_approved: true,
target: publish::Target::Push,
},
Action::Publish {
ids: vec![4, 5],
all_approved: false,
target: publish::Target::Pr,
},
Action::RunCampaign {
name: "c".into(),
count: Some(1),
},
Action::Sync {
of: of.clone(),
apply: true,
},
Action::Verify { of },
];
for a in &queued {
let line = api::command_line(a).expect("a queued action");
let args = std::iter::once("pma".to_string()).chain(line.iter().cloned());
if let Err(e) = Cli::try_parse_from(args) {
panic!("{line:?}: {e}");
}
}
assert!(api::command_line(&Action::SettlePrs).is_none());
}
/// The grouped listing is the only listing, so a command missing from
/// `GROUPS` would be a command missing from the help. This is what makes
/// hand-written grouping safe.
#[test]
fn every_command_is_in_exactly_one_group() {
let command = Cli::command();
let grouped: Vec<&str> = GROUPS
.iter()
.flat_map(|(_, names)| *names)
.copied()
.collect();
for sub in command.get_subcommands() {
let name = sub.get_name();
// A hidden command is kept out of the help on purpose.
if name == "help" || sub.is_hide_set() {
continue;
}
let count = grouped.iter().filter(|n| **n == name).count();
assert_eq!(count, 1, "`{name}` appears in {count} groups, not 1");
}
for name in &grouped {
assert!(
command.get_subcommands().any(|s| s.get_name() == *name),
"`{name}` is grouped but is not a command"
);
}
}
/// Every line fits a narrow terminal, which is why the one-liners are
/// short and the long form lives in each command's own help.
#[test]
fn the_listing_does_not_wrap() {
let command = Cli::command();
for line in grouped_commands(&command).lines() {
assert!(line.len() <= 72, "{} chars: {line}", line.len());
}
}
}