rigger 0.22.0

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

mod adopt;
mod answers;
mod calendar;
mod card;
mod commit;
mod context;
mod db;
#[allow(dead_code)]
mod doc;
mod export;
mod gate;
mod hub;
mod import;
mod line;
mod link;
mod mcp;
mod open;
mod owner;
mod paths;
mod profile;
mod repo;
mod retro;
mod search;
mod session;
mod show;
mod skill;
mod sync;
mod week;

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};

use crate::db::Db;

#[derive(Parser)]
#[command(name = "rigger", version, about, long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Create the database and the default profile
    Init,
    /// Add, list and show projects
    Project {
        #[command(subcommand)]
        command: ProjectCommand,
    },
    /// Read a notes hub into versions, tasks and events
    Import {
        /// Project name
        project: String,
        /// Directory of the hub to read
        #[arg(long, required_unless_present = "answers", conflicts_with = "answers")]
        hub: Option<PathBuf>,
        /// A questionnaire the owner answered, as JSON: its choices become decisions and wishes
        #[arg(long, value_name = "FILE")]
        answers: Option<PathBuf>,
        /// Say what would be recorded, and write nothing
        #[arg(long)]
        check: bool,
        /// Print the report as JSON
        #[arg(long)]
        json: bool,
    },
    /// Switch, list and add profiles: one record per way of working
    Profile {
        #[command(subcommand)]
        command: ProfileCommand,
    },
    /// Give a task a status
    Task {
        #[command(subcommand)]
        command: TaskCommand,
    },
    /// Record every repository under a directory, with its hub and its tags
    Adopt {
        /// Directory whose children are repositories; the profile's roots when omitted
        root: Option<PathBuf>,
        /// Directory whose children are hubs, one per project name; the profile's when omitted
        #[arg(long)]
        hubs: Option<PathBuf>,
        /// Say what would be recorded, and write nothing
        #[arg(long)]
        check: bool,
        /// Print the report as JSON
        #[arg(long)]
        json: bool,
    },
    /// Write a thin project skill from a template and the record
    Skill {
        /// Project name
        #[arg(required_unless_present_any = ["print_template", "line"])]
        project: Option<String>,
        /// Write it into the assistant's skills directory instead of printing it
        #[arg(long)]
        install: bool,
        /// Write it under this directory instead; implies --install
        #[arg(long, value_name = "DIR")]
        dir: Option<PathBuf>,
        /// Overwrite a skill file that was written by hand
        #[arg(long)]
        replace: bool,
        /// Read the template from this file instead of the data directory
        #[arg(long, value_name = "FILE")]
        template: Option<PathBuf>,
        /// Print the built-in template, to start one of your own from
        #[arg(long)]
        print_template: bool,
        /// Write one skill for the whole line instead of one per project
        #[arg(long, conflicts_with = "project")]
        line: bool,
    },
    /// The project's screen: what it is, where it stands, what it has written
    Show {
        /// Project name
        project: String,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Print what an assistant needs to start a session on a project
    Context {
        /// Project name
        project: String,
        /// Print as JSON
        #[arg(long)]
        json: bool,
        /// Show what each section of the packet costs
        #[arg(long)]
        explain: bool,
        /// Token budget for the packet
        #[arg(long, default_value_t = context::DEFAULT_BUDGET)]
        budget: usize,
    },
    /// Record an event: a decision, a finding, a pitfall, a change, a next step
    Note {
        /// Project name
        project: String,
        /// What happened
        text: String,
        /// Kind of event
        #[arg(long, value_name = "KIND", default_value = "finding")]
        kind: NoteKind,
        /// The principle this decision stands on
        #[arg(long, value_name = "NAME")]
        principle: Option<String>,
    },
    /// Start an assistant session in the project, with the packet in hand
    Open {
        /// Project name
        project: String,
        /// Print the first message instead of starting a session
        #[arg(long)]
        print: bool,
        /// Token budget for the packet
        #[arg(long, default_value_t = context::DEFAULT_BUDGET)]
        budget: usize,
    },
    /// Read tags and commits into facts: what shipped, and what has happened since
    Sync {
        /// Project name; every project when omitted
        project: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Questions waiting for your answer, across every project
    Inbox {
        /// Only this project
        #[arg(long)]
        project: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// What moved lately, five lines per project
    Digest {
        /// Project name; every project that moved when omitted
        project: Option<String>,
        /// How far back to look, as days: 7d, 30d
        #[arg(long, default_value = "7d")]
        since: String,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Search the record: where was this decided, when was that fixed
    Find {
        /// What to look for; FTS5 syntax, so `budget AND packet` works
        query: String,
        /// Only this project
        #[arg(long)]
        project: Option<String>,
        /// Only this kind of event
        #[arg(long, value_name = "KIND")]
        kind: Option<String>,
        /// How many results to show
        #[arg(long, default_value_t = 20)]
        limit: u32,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// The events that led to a version: what was decided, found and hit
    Why {
        /// Project name; omitted when reading a principle across the line
        project: Option<String>,
        /// Version, as the record spells it
        version: Option<String>,
        /// Read one principle across every project instead of one version
        #[arg(long, value_name = "NAME")]
        principle: Option<String>,
        /// List the principles the record has used
        #[arg(long)]
        principles: bool,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Plan a version: aim it at a week of the calendar
    Version {
        #[command(subcommand)]
        command: VersionCommand,
    },
    /// Weeks by projects: what is planned, what shipped, what slipped
    Calendar {
        /// How many weeks to show, starting this week
        #[arg(long, default_value_t = 6)]
        weeks: u32,
        /// Start from this week instead of the current one
        #[arg(long, value_name = "WEEK")]
        from: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// This week's focus: what is aimed at it, and what is already late
    Next {
        /// Read a week other than the current one
        #[arg(long, value_name = "WEEK")]
        week: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// The Monday brief: the focus, what ships on Friday, what waits on you
    Week {
        /// Read a week other than the current one
        #[arg(long, value_name = "WEEK")]
        week: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// The shopfront queue: what has gone out this week, and what waits for Friday
    ReleaseDay {
        /// Read a week other than the current one
        #[arg(long, value_name = "WEEK")]
        week: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Look back: what the plan said, what the tags say, where they parted
    Retro {
        /// Look back over a whole cycle of the calendar instead of the default weeks
        #[arg(long)]
        cycle: bool,
        /// How many weeks to look back over, ending with this week
        #[arg(long, value_name = "N", conflicts_with = "cycle")]
        weeks: Option<u32>,
        /// End the window at this week instead of the current one
        #[arg(long, value_name = "WEEK")]
        to: Option<String>,
        /// Write the summary into the record as an event
        #[arg(long)]
        record: bool,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Open and close a sitting, so its events belong together
    Session {
        #[command(subcommand)]
        command: SessionCommand,
    },
    /// Write a hub back out of the record
    Export {
        /// Project name; omitted with --line
        #[arg(required_unless_present = "line")]
        project: Option<String>,
        /// Directory of the hub to write
        #[arg(long, required_unless_present = "line", conflicts_with = "line")]
        hub: Option<PathBuf>,
        /// Write the line's public registry instead of a hub
        #[arg(long)]
        line: bool,
        /// Where the registry goes; standard output when omitted
        #[arg(long, value_name = "FILE", requires = "line")]
        to: Option<PathBuf>,
        /// Say what would change without writing anything
        #[arg(long)]
        check: bool,
        /// Take over files written by hand, so the record owns them from now on
        #[arg(long)]
        adopt: bool,
        /// Also write the handwritten texts back out: vision, rituals, research
        #[arg(long)]
        docs: bool,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Serve the record over MCP, on stdin and stdout
    Mcp,
    /// Answer a question or sort a wish, so it leaves the packet
    Resolve {
        /// Project name
        project: String,
        /// Id of the question or wish, as the packet lists it
        id: i64,
        /// The answer; a question answered this way becomes a decision
        answer: Option<String>,
    },
    /// Record a wish: something to sort into the plan later
    Wish {
        /// Project name
        project: String,
        /// What you want
        text: String,
        /// The neighbour asking for it, when a wish comes from one
        #[arg(long = "from", value_name = "PROJECT")]
        from_project: Option<String>,
    },
    /// Tie two projects together: a pair, what one draws on, what draws on it
    Link {
        #[command(subcommand)]
        command: LinkCommand,
    },
    /// The handwritten texts of a project: vision, rituals, research
    Doc {
        #[command(subcommand)]
        command: DocCommand,
    },
    /// Run the command that says a project is fit to commit, and record how it went
    Gate {
        /// Project name; the one the working directory sits in when omitted
        project: Option<String>,
        /// Print what would be run, and run nothing
        #[arg(long)]
        check: bool,
        /// Print the result as JSON
        #[arg(long)]
        json: bool,
    },
    /// How the work is done: the rituals of the line, and of one project
    Rules {
        /// Project name; the line's own rituals alone when omitted
        project: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Copy the database aside, stamped with the moment and its schema
    Backup {
        /// How many copies to keep; older ones are deleted
        #[arg(long, default_value_t = KEEP_BACKUPS, value_name = "N")]
        keep: usize,
        /// List the copies instead of taking one
        #[arg(long)]
        list: bool,
    },
    /// Show the database path, schema version and record counts
    Doctor {
        /// Also check the hubs the record generates against what is on disk
        #[arg(long)]
        hubs: bool,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
}

/// The kinds a `note` can record. A question is not among them: it is
/// addressed to the owner and arrives from the hub or, later, from the
/// assistant's `ask_owner` tool.
#[derive(Clone, Copy, clap::ValueEnum)]
enum NoteKind {
    /// A decision and its reason
    Decision,
    /// Something learnt about the code or the domain
    Finding,
    /// A trap worth remembering
    Pitfall,
    /// Something that changed in the product
    Change,
    /// The one line the next session starts from
    Next,
    /// A line for the hub's state block: where things stand, in one sentence
    State,
    /// A step of the plan of edits, for a card
    Plan,
}

impl NoteKind {
    fn as_str(self) -> &'static str {
        match self {
            NoteKind::Decision => "decision",
            NoteKind::Finding => "finding",
            NoteKind::Pitfall => "pitfall",
            NoteKind::Change => "change",
            NoteKind::Next => "next",
            NoteKind::State => "state",
            NoteKind::Plan => "plan",
        }
    }
}

/// What a link between two projects says.
///
/// Mirrors `link::Kind` rather than being it: `clap` wants an enum it can
/// derive a value parser on, and the domain type should not have to know
/// what a command line is.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum LinkKind {
    /// Two halves of one capability; neither ships alone
    Pair,
    /// This project draws on the other
    Consumer,
    /// The other project draws on this one
    Donor,
}

impl LinkKind {
    fn to_domain(self) -> link::Kind {
        match self {
            LinkKind::Pair => link::Kind::Pair,
            LinkKind::Consumer => link::Kind::Consumer,
            LinkKind::Donor => link::Kind::Donor,
        }
    }
}

#[derive(Subcommand)]
enum LinkCommand {
    /// Record a tie between two projects, or two of their versions
    ///
    /// Each side is a project, or a project and a version written
    /// `kasl@v1.13.0`. The version is part of one argument rather than a
    /// positional of its own: with two optional versions between two
    /// projects, `rigger link kasl v1.13.0 kasl-server` has two readings
    /// and a command line that guesses would anchor the wrong half.
    Add {
        /// Project on this side, optionally `project@version`
        from: String,
        /// Project on the other side, optionally `project@version`
        to: String,
        /// What the tie is
        #[arg(long, value_name = "KIND", default_value = "pair")]
        kind: LinkKind,
        /// A sentence saying what the two share
        #[arg(long)]
        note: Option<String>,
    },
    /// The ties one project has, read from its side
    List {
        /// Project name; every link of the record when omitted
        project: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Forget a tie, by the id `link list` prints
    Remove {
        /// Id of the link
        id: i64,
    },
    /// The pairs whose halves have parted company
    Drift {
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum DocCommand {
    /// List the documents of a project
    List {
        /// Project name
        project: String,
        /// Only this kind: vision, decisions, research, rituals, other
        #[arg(long)]
        kind: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Print a document
    Show {
        /// Project name
        project: String,
        /// The document's address, as `list` prints it
        slug: String,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Write a new document, in $EDITOR unless a body is given
    Add {
        /// Project name
        project: String,
        /// What it is called
        title: String,
        /// Kind: vision, decisions, research, rituals, other
        #[arg(long, default_value = "other")]
        kind: String,
        /// The address to give it; made from the title when omitted
        #[arg(long)]
        slug: Option<String>,
        /// The body, instead of opening an editor; `-` reads standard input
        #[arg(long)]
        body: Option<String>,
    },
    /// Edit a document in $EDITOR
    Edit {
        /// Project name
        project: String,
        /// The document's address, as `list` prints it
        slug: String,
        /// A new title for it
        #[arg(long)]
        title: Option<String>,
        /// The body, instead of opening an editor; `-` reads standard input
        #[arg(long)]
        body: Option<String>,
    },
    /// Remove a document from the record
    Remove {
        /// Project name
        project: String,
        /// The document's address, as `list` prints it
        slug: String,
    },
    /// The skeleton a new document of a kind starts from
    Template {
        /// Kind: vision, decisions, research, rituals, other
        kind: String,
        /// Write it to the profile's directory, to edit into your own
        #[arg(long)]
        write: bool,
    },
}

#[derive(Subcommand)]
enum ProfileCommand {
    /// List the profiles, marking the one in use
    List {
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Show one profile; the one in use when no name is given
    Show {
        /// Profile name
        name: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Make a profile the one every command uses
    Use {
        /// Profile name
        name: String,
    },
    /// Add a profile, with a database of its own
    Add {
        /// Profile name
        name: String,
        /// What the unit of work is
        #[arg(long, value_enum, default_value_t = profile::Kind::Line)]
        kind: profile::Kind,
        /// A directory whose children are repositories; may be given more than once
        #[arg(long = "root", value_name = "DIR")]
        roots: Vec<PathBuf>,
        /// The directory whose children are hubs, one per project name
        #[arg(long, value_name = "DIR")]
        hubs: Option<PathBuf>,
        /// How a ticket id is spelt, as a regular expression
        #[arg(long, value_name = "REGEX")]
        id_pattern: Option<String>,
        /// Where incoming material lands
        #[arg(long, value_name = "DIR")]
        inbox: Option<PathBuf>,
        /// Switch to it right away
        #[arg(long)]
        r#use: bool,
    },
    /// Change what a profile says about itself; a field given replaces what it had
    Set {
        /// Profile name; the one in use when omitted
        name: Option<String>,
        /// A directory whose children are repositories; may be given more than once, replaces the roots
        #[arg(long = "root", value_name = "DIR")]
        roots: Vec<PathBuf>,
        /// The directory whose children are hubs, one per project name
        #[arg(long, value_name = "DIR")]
        hubs: Option<PathBuf>,
        /// How a ticket id is spelt, as a regular expression
        #[arg(long, value_name = "REGEX")]
        id_pattern: Option<String>,
        /// Where incoming material lands
        #[arg(long, value_name = "DIR")]
        inbox: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum TaskCommand {
    /// Make a card for a task: a ticket id, or a local key until one is given
    New {
        /// The task's title
        title: String,
        /// Ticket id, such as WA-4130; a local key is made when omitted
        #[arg(long = "id", value_name = "KEY")]
        key: Option<String>,
        /// Another name the task goes by; may be given more than once
        #[arg(long = "alias", value_name = "TEXT")]
        aliases: Vec<String>,
        /// A project the task is worked in; may be given more than once
        #[arg(long = "project", value_name = "NAME")]
        projects: Vec<String>,
        /// The branch it is worked on, in every project given
        #[arg(long)]
        branch: Option<String>,
        /// What the task is, in one paragraph
        #[arg(long)]
        summary: Option<String>,
    },
    /// Find the card a line of text means: by id, by title, by case number
    Find {
        /// The task as it was handed over: id, title, numbers, any of them
        query: String,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Make a card the open one, so that the record knows what is in hand
    Open {
        /// Card key, alias or id
        task: String,
    },
    /// The card in hand, if one is open
    Active {
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Close a card: done by default, or the status given
    Close {
        /// Card key, alias or id; the open card when omitted
        task: Option<String>,
        /// The status to leave it in
        #[arg(long, default_value = "done")]
        status: String,
    },
    /// Show a card: what it is, where it is worked, what was written
    Show {
        /// Card key, alias or id
        task: String,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// The packet an assistant starts a task from
    Context {
        /// Card key, alias or id
        task: String,
        /// Token budget for the packet
        #[arg(long, default_value_t = context::DEFAULT_BUDGET)]
        budget: usize,
    },
    /// Link a card to a project, with the branch it is worked on there
    Link {
        /// Card key, alias or id
        task: String,
        /// Project name
        project: String,
        /// The branch
        #[arg(long)]
        branch: Option<String>,
        /// What the project is to the task: where it is fixed, or only read
        #[arg(long)]
        role: Option<String>,
    },
    /// List cards
    List {
        /// open (the default), all, or one status
        #[arg(long, default_value = "open")]
        status: String,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Give a card a new key; the old one stays as an alias
    Rename {
        /// Card key, alias or id
        task: String,
        /// The new key
        key: String,
    },
    /// Add a name a card goes by
    Alias {
        /// Card key, alias or id
        task: String,
        /// The alias
        alias: String,
    },
    /// Say what a card is, in one paragraph
    Summary {
        /// Card key, alias or id
        task: String,
        /// The paragraph
        text: String,
    },
    /// Record an event against a card: a decision, a finding, a pitfall, a plan step, a change, the next step
    Note {
        /// Card key, alias or id
        task: String,
        /// What happened
        text: String,
        /// Kind of event
        #[arg(long, value_name = "KIND", default_value = "finding")]
        kind: NoteKind,
    },
    /// Give a task a status: new, active, waiting-handoff, frozen or done
    Status {
        /// Card key, alias, or the id the packet or `plan` lists
        task: String,
        /// The status
        status: String,
    },
}

#[derive(Subcommand)]
enum ProjectCommand {
    /// Record a repository as a project
    Add {
        /// Path to the repository root
        path: PathBuf,
        /// Project name; defaults to the name the repository declares
        #[arg(long)]
        name: Option<String>,
    },
    /// Record a place the record keeps for itself, with no repository
    Service {
        /// Project name
        name: String,
    },
    /// List recorded projects
    List {
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Show one project
    Show {
        /// Project name
        name: String,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Set what the record keeps about a project
    Set {
        /// Project name
        name: String,
        /// The command that says the project is fit to commit, as a shell would run it
        #[arg(long, value_name = "COMMAND")]
        gate: Option<String>,
        /// Forget the gate
        #[arg(long, conflicts_with = "gate")]
        no_gate: bool,
        /// The command to run when a sitting on this project closes
        #[arg(long, value_name = "COMMAND")]
        on_session_end: Option<String>,
        /// Forget the end-of-session command
        #[arg(long, conflicts_with = "on_session_end")]
        no_on_session_end: bool,
    },
    /// Record how a product looks from outside: its mark, colours, form and docs
    Mark {
        /// Project name
        name: String,
        /// The two-letter code of its mark
        #[arg(long)]
        code: Option<String>,
        /// The colour it owns, as #RRGGBB
        #[arg(long)]
        accent: Option<String>,
        /// The second colour, for a mark drawn as a pair
        #[arg(long)]
        accent2: Option<String>,
        /// What shape of thing it is: cli, desktop, web, library, service
        #[arg(long)]
        form: Option<String>,
        /// Where its documentation lives
        #[arg(long, value_name = "URL")]
        docs: Option<String>,
        /// Forget the mark entirely
        #[arg(long, conflicts_with_all = ["code", "accent", "accent2", "form", "docs"])]
        clear: bool,
    },
    /// Set the tier a project sits in, and how often it should release
    Tier {
        /// Project name
        name: String,
        /// A, B, C, or out for a project outside the rotation
        tier: String,
        /// Weeks between releases; the tier's own rhythm when omitted
        #[arg(long, value_name = "WEEKS")]
        rhythm: Option<u32>,
    },
}

#[derive(Subcommand)]
enum SessionCommand {
    /// Open a sitting; everything recorded until `end` belongs to it
    Start {
        /// Project name; the project of the working directory when omitted
        project: Option<String>,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
    /// Close the sitting and say what it held
    End {
        /// Project name; the project of the working directory when omitted
        project: Option<String>,
        /// A title for the diary entry, if one is being written
        #[arg(long, value_name = "TEXT")]
        heading: Option<String>,
        /// Append the entry to this diary file
        #[arg(long, value_name = "FILE")]
        diary: Option<PathBuf>,
        /// Say nothing unless something is worth saying, for a hook
        #[arg(long)]
        remind: bool,
        /// Print as JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum VersionCommand {
    /// Aim a version at a week of the calendar
    Plan {
        /// Project name
        project: String,
        /// Version, as the record spells it
        version: String,
        /// The week it is aimed at, as `2026-W37`
        #[arg(long, value_name = "WEEK")]
        week: Option<String>,
        /// Take the version off the calendar
        #[arg(long, conflicts_with = "week")]
        clear: bool,
    },
}

/// The stack the work runs on.
///
/// Windows gives the main thread 1 MB, and clap's derived parser walks the
/// command tree with one frame per level. Unoptimised frames are several
/// times fatter than optimised ones, so a tree this size overflowed that
/// megabyte in debug builds while release was fine - `rigger --version`
/// died before reaching any code of ours. Tests run debug binaries, so
/// this was every test, not a corner.
///
/// Asking for the stack rather than flattening the commands: the tree is
/// the product's surface, and it should be free to grow.
const STACK: usize = 16 * 1024 * 1024;

fn main() -> ExitCode {
    // The default thread stack is what `main` gets; a spawned one takes
    // the size it is given, on every platform rigger ships to.
    match std::thread::Builder::new().stack_size(STACK).spawn(work).map(std::thread::JoinHandle::join) {
        Ok(Ok(code)) => code,
        // A panic has already printed itself; exiting with the code a
        // panicking process uses keeps that unchanged.
        Ok(Err(_)) => ExitCode::from(101),
        Err(e) => {
            eprintln!("error: cannot start the working thread: {e}");
            ExitCode::FAILURE
        }
    }
}

fn work() -> ExitCode {
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(err) => return usage_error(err),
    };
    match run(cli) {
        Ok(()) => ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("error: {err:#}");
            ExitCode::FAILURE
        }
    }
}

/// Prints what clap wants to say, and chooses the exit code.
///
/// `--help` and `--version` are successes; a usage error is a failure. What
/// matters is *which* failure: clap's own code is 2, and 2 is the code an
/// assistant's Stop hook uses to refuse the stop and hold the turn open. A
/// hook is a command line written once in a settings file and never seen
/// again - a typo in it, or an older rigger on the PATH without the
/// subcommand, would wedge every session it fired in. Found by installing
/// the hook and running it: the rigger on PATH was a release behind, and
/// `rigger session end --remind` exited 2.
///
/// So rigger never exits 2. A usage error is exit 1 like every other
/// failure, and a hook that cannot be understood is simply ignored.
fn usage_error(err: clap::Error) -> ExitCode {
    let _ = err.print();
    match err.use_stderr() {
        true => ExitCode::FAILURE,
        false => ExitCode::SUCCESS,
    }
}

fn run(cli: Cli) -> Result<()> {
    match cli.command {
        Command::Init => init(),
        Command::Project { command } => match command {
            ProjectCommand::Add { path, name } => project_add(path, name),
            ProjectCommand::Service { name } => project_service(&name),
            ProjectCommand::List { json } => project_list(json),
            ProjectCommand::Show { name, json } => project_show(&name, json),
            ProjectCommand::Set {
                name,
                gate,
                no_gate,
                on_session_end,
                no_on_session_end,
            } => project_set(&name, gate.as_deref(), no_gate, on_session_end.as_deref(), no_on_session_end),
            ProjectCommand::Mark {
                name,
                code,
                accent,
                accent2,
                form,
                docs,
                clear,
            } => project_mark(
                &name,
                code.as_deref(),
                accent.as_deref(),
                accent2.as_deref(),
                form.as_deref(),
                docs.as_deref(),
                clear,
            ),
            ProjectCommand::Tier { name, tier, rhythm } => project_tier(&name, &tier, rhythm),
        },
        Command::Import {
            project,
            hub,
            answers,
            check,
            json,
        } => match answers {
            Some(answers) => import_answers(&project, &answers, check, json),
            None => import_hub(&project, &hub.expect("clap requires --hub without --answers"), json),
        },
        Command::Profile { command } => match command {
            ProfileCommand::List { json } => profile_list(json),
            ProfileCommand::Show { name, json } => profile_show(name.as_deref(), json),
            ProfileCommand::Use { name } => profile_use(&name),
            ProfileCommand::Add {
                name,
                kind,
                roots,
                hubs,
                id_pattern,
                inbox,
                r#use,
            } => profile_add(
                &name,
                profile::Profile {
                    kind,
                    roots,
                    hubs,
                    id_pattern,
                    inbox,
                },
                r#use,
            ),
            ProfileCommand::Set {
                name,
                roots,
                hubs,
                id_pattern,
                inbox,
            } => profile_set(name.as_deref(), roots, hubs, id_pattern, inbox),
        },
        Command::Task { command } => match command {
            TaskCommand::New {
                title,
                key,
                aliases,
                projects,
                branch,
                summary,
            } => task_new(&title, key.as_deref(), &aliases, &projects, branch.as_deref(), summary.as_deref()),
            TaskCommand::Find { query, json } => task_find(&query, json),
            TaskCommand::Open { task } => task_open(&task),
            TaskCommand::Active { json } => task_active(json),
            TaskCommand::Close { task, status } => task_close(task.as_deref(), &status),
            TaskCommand::Show { task, json } => task_show(&task, json),
            TaskCommand::Context { task, budget } => task_context(&task, budget),
            TaskCommand::Link { task, project, branch, role } => task_link(&task, &project, branch.as_deref(), role.as_deref()),
            TaskCommand::List { status, json } => task_list(&status, json),
            TaskCommand::Rename { task, key } => task_rename(&task, &key),
            TaskCommand::Alias { task, alias } => task_alias(&task, &alias),
            TaskCommand::Summary { task, text } => task_summary(&task, &text),
            TaskCommand::Note { task, text, kind } => note_on_card(&task, kind.as_str(), &text),
            TaskCommand::Status { task, status } => task_status(&task, &status),
        },
        Command::Adopt { root, hubs, check, json } => adopt_root(root.as_deref(), hubs.as_deref(), check, json),
        Command::Skill {
            project,
            install,
            dir,
            replace,
            template,
            print_template,
            line,
        } => {
            let install = install || dir.is_some();
            if line {
                write_line_skill(install, dir.as_deref(), replace, template.as_deref(), print_template)
            } else {
                write_skill(project.as_deref(), install, dir.as_deref(), replace, template.as_deref(), print_template)
            }
        }
        Command::Show { project, json } => show_project(&project, json),
        Command::Context {
            project,
            json,
            explain,
            budget,
        } => show_context(&project, json, explain, budget),
        Command::Open { project, print, budget } => open_session(&project, print, budget),
        Command::Note {
            project,
            text,
            kind,
            principle,
        } => note(&project, kind.as_str(), &text, principle.as_deref(), None),
        Command::Sync { project, json } => sync_projects(project.as_deref(), json),
        Command::Inbox { project, json } => inbox(project.as_deref(), json),
        Command::Digest { project, since, json } => digest(project.as_deref(), &since, json),
        Command::Find {
            query,
            project,
            kind,
            limit,
            json,
        } => find(&query, project.as_deref(), kind.as_deref(), limit, json),
        Command::Why {
            project,
            version,
            principle,
            principles,
            json,
        } => why(project.as_deref(), version.as_deref(), principle.as_deref(), principles, json),
        Command::Version { command } => match command {
            VersionCommand::Plan { project, version, week, clear } => version_plan(&project, &version, week.as_deref(), clear),
        },
        Command::Calendar { weeks, from, json } => show_calendar(weeks, from.as_deref(), json),
        Command::Next { week, json } => show_next(week.as_deref(), json),
        Command::Week { week, json } => show_week(week.as_deref(), json),
        Command::ReleaseDay { week, json } => show_release_day(week.as_deref(), json),
        Command::Retro {
            cycle,
            weeks,
            to,
            record,
            json,
        } => show_retro(cycle, weeks, to.as_deref(), record, json),
        Command::Session { command } => match command {
            SessionCommand::Start { project, json } => session_start(project.as_deref(), json),
            SessionCommand::End {
                project,
                heading,
                diary,
                remind,
                json,
            } => session_end(project.as_deref(), heading.as_deref(), diary.as_deref(), remind, json),
        },
        Command::Export {
            project,
            hub,
            line,
            to,
            check,
            adopt,
            docs,
            json,
        } => match line {
            true => export_line(to.as_deref(), check),
            false => export_hub(
                &project.expect("clap requires a project without --line"),
                &hub.expect("clap requires --hub without --line"),
                check,
                adopt,
                docs,
                json,
            ),
        },
        Command::Mcp => mcp::serve(),
        Command::Resolve { project, id, answer } => resolve(&project, id, answer.as_deref()),
        Command::Wish { project, text, from_project } => note(&project, "wish", &text, None, from_project.as_deref()),
        Command::Link { command } => match command {
            LinkCommand::Add { from, to, kind, note } => link_add(&from, &to, kind, note.as_deref()),
            LinkCommand::List { project, json } => link_list(project.as_deref(), json),
            LinkCommand::Remove { id } => link_remove(id),
            LinkCommand::Drift { json } => link_drift(json),
        },
        Command::Doc { command } => match command {
            DocCommand::List { project, kind, json } => doc_list(&project, kind.as_deref(), json),
            DocCommand::Show { project, slug, json } => doc_show(&project, &slug, json),
            DocCommand::Add {
                project,
                title,
                kind,
                slug,
                body,
            } => doc_add(&project, &title, &kind, slug.as_deref(), body.as_deref()),
            DocCommand::Edit { project, slug, title, body } => doc_edit(&project, &slug, title.as_deref(), body.as_deref()),
            DocCommand::Remove { project, slug } => doc_remove(&project, &slug),
            DocCommand::Template { kind, write } => doc_template(&kind, write),
        },
        Command::Gate { project, check, json } => gate(project.as_deref(), check, json),
        Command::Rules { project, json } => rules(project.as_deref(), json),
        Command::Backup { keep, list } => backup(keep, list),
        Command::Doctor { hubs, json } => doctor(hubs, json),
    }
}

/// Reads a questionnaire the owner answered into the record.
///
/// The page that produced it is where these answers otherwise stay, and a
/// plan made from them says what was decided without saying what it was
/// decided against - which is the half that answers "why this and not that"
/// a year later.
fn import_answers(project: &str, path: &Path, check: bool, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    let answers = answers::read(path)?;
    let entries = answers.entries();
    let at = answers.at().unwrap_or_else(db::now);

    if check {
        println!(
            "{} would take {} from {}:",
            project.name,
            plural(entries.len(), "event", "events"),
            path.display()
        );
        for entry in &entries {
            println!("  {:<9} {}", entry.kind, first_line(&entry.body));
        }
        return Ok(());
    }

    let mut added = 0usize;
    let mut already = 0usize;
    for entry in &entries {
        match db.record_event(project.id, entry.kind, &entry.body, &at, "owner")? {
            db::Change::Unchanged => already += 1,
            _ => added += 1,
        }
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "project": project.name,
                "added": added,
                "already_recorded": already,
            }))?
        );
        return Ok(());
    }
    println!("{}:", project.name);
    println!("  {:<10} {added} added", "answers");
    if already > 0 {
        // Reading the same page twice is ordinary - it is how a correction
        // to it is applied - and saying so is how that stays ordinary.
        println!("  {:<10} {already} already recorded", "");
    }
    Ok(())
}

fn import_hub(project: &str, hub_dir: &Path, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let Some(project) = db.project_by_name(project)? else {
        bail!("no project named '{project}'; see `rigger project list`");
    };
    let hub = hub::read(hub_dir)?;
    // Where the hub is, so a later check can find it. Not guessed from the
    // repository path: the hubs of this line live in a notes vault. Spelt
    // the way the platform spells it, not the way the shell happened to.
    let hub_dir = &dunce::canonicalize(hub_dir).unwrap_or_else(|_| hub_dir.to_path_buf());
    db.set_hub_path(project.id, hub_dir)?;
    let report = import::import(&db, project.id, &hub)?;

    if json {
        println!("{}", serde_json::to_string_pretty(&report)?);
        return Ok(());
    }
    for warning in &report.warnings {
        println!("note: {warning}");
    }
    if !report.changed() {
        println!("{}: nothing changed", project.name);
        return Ok(());
    }
    println!("{}:", project.name);
    let line = |label: &str, added: u32, updated: u32| {
        if added + updated > 0 {
            println!("  {label:<10} {added} added, {updated} updated");
        }
    };
    line("versions", report.versions_added, report.versions_updated);
    line("tasks", report.tasks_added, report.tasks_updated);
    if report.versions_dropped + report.tasks_dropped > 0 {
        println!(
            "  {:<10} {} and {} struck from the hub",
            "dropped",
            plural(report.versions_dropped as usize, "version", "versions"),
            plural(report.tasks_dropped as usize, "task", "tasks")
        );
    }
    if report.questions_withdrawn > 0 {
        println!(
            "  {:<10} {} struck from the hub",
            "withdrawn",
            plural(report.questions_withdrawn as usize, "question", "questions")
        );
    }
    if report.decisions_added > 0 {
        println!("  {:<10} {} added", "decisions", report.decisions_added);
    }
    if report.questions_added > 0 {
        println!("  {:<10} {} added", "questions", report.questions_added);
    }
    if report.wishes_added > 0 {
        println!("  {:<10} {} taken out of {}", "wishes", report.wishes_added, hub::WISHES_FILE);
    }
    line("documents", report.documents_added, report.documents_updated);
    Ok(())
}

/// Records every checkout under a directory, and reads each one's hub and
/// tags - the three commands a project used to take, once for the line.
///
/// Told nothing, it walks the roots the profile names, with the profile's
/// hubs: a line that has said once where it keeps things need not say so
/// again every time it has grown.
fn adopt_root(root: Option<&Path>, hubs: Option<&Path>, check: bool, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let config = profile::Config::load()?;
    let (name, current) = config.current()?;
    let roots: Vec<PathBuf> = match root {
        Some(root) => vec![root.to_path_buf()],
        None if current.roots.is_empty() => {
            bail!("profile '{name}' names no roots; give a directory, or set one with `rigger profile set {name} --root <dir>`")
        }
        None => current.roots.clone(),
    };
    let hubs = hubs.or(current.hubs.as_deref());
    let mut adopted = Vec::new();
    for root in &roots {
        adopted.extend(adopt::adopt(&db, root, hubs, check)?);
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&adopted)?);
        return Ok(());
    }
    let width = adopted.iter().map(|a| a.name.len()).max().unwrap_or(0);
    let mut recorded = 0;
    let mut known = 0;
    let mut without = 0;
    let mut skipped = 0;
    let mut hubs_read = 0;
    for a in &adopted {
        let status = match (&a.status, check) {
            (adopt::Status::Recorded, true) => "would record",
            (adopt::Status::Recorded, false) => "recorded",
            (adopt::Status::Known, _) => "known",
            (adopt::Status::NoHub, _) => "no hub",
            (adopt::Status::Skipped(_), _) => "skipped",
        };
        match &a.status {
            adopt::Status::Recorded => recorded += 1,
            adopt::Status::Known => known += 1,
            adopt::Status::NoHub => without += 1,
            adopt::Status::Skipped(_) => skipped += 1,
        }
        let hub = match (&a.hub, &a.status, check) {
            (_, adopt::Status::NoHub, _) => String::new(),
            (None, _, _) => "hub: none".to_string(),
            (Some(_), adopt::Status::Skipped(_), _) | (Some(_), _, true) => "hub: found".to_string(),
            (Some(_), _, false) => {
                hubs_read += 1;
                a.hub_summary()
            }
        };
        let git = match (&a.status, check) {
            (adopt::Status::Skipped(_) | adopt::Status::NoHub, _) | (_, true) => String::new(),
            _ if a.shipped + a.changes_read == 0 => "   git: nothing new".to_string(),
            _ => format!(
                "   git: {} shipped, {} read",
                plural(a.shipped as usize, "version", "versions"),
                plural(a.changes_read as usize, "change", "changes")
            ),
        };
        println!("{:width$}  {status:<12} {hub}{git}", a.name);
        if let adopt::Status::Skipped(reason) = &a.status {
            println!("{:width$}  {reason}", "");
        }
        for warning in &a.warnings {
            println!("{:width$}  note: {warning}", "");
        }
    }
    let total = adopted.len();
    let verb = if check { "would be recorded" } else { "recorded" };
    let without = match without {
        0 => String::new(),
        n => format!(", {n} without a hub"),
    };
    println!(
        "\n{}: {recorded} {verb}, {known} known{without}, {skipped} skipped; {} read.",
        plural(total, "repository", "repositories"),
        plural(hubs_read, "hub", "hubs")
    );
    if check {
        println!("Nothing was written. Run again without --check to record them.");
    }
    Ok(())
}

/// Writes a project's skill from the template and the record.
///
/// Printed unless asked to install, so the first run shows what a skill
/// will say before anything is overwritten. A file somebody wrote by hand
/// is not replaced without `--replace`: what it holds may belong in the hub
/// first, and the mark is how the next run knows the file is rigger's.
fn write_skill(project: Option<&str>, install: bool, dir: Option<&Path>, replace: bool, template: Option<&Path>, print_template: bool) -> Result<()> {
    if print_template {
        print!("{}", skill::DEFAULT_TEMPLATE);
        return Ok(());
    }
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project.unwrap_or_default())?;
    let (template, source) = skill::load_template(template)?;
    let about = match project.kind {
        db::Kind::Repo => repo::detect_about(Path::new(&project.path)),
        db::Kind::Service => None,
    };
    let fields = skill::Fields {
        name: &project.name,
        path: &project.path,
        remote: project.remote.as_deref(),
        hub: project.hub_path.as_deref().map(Path::new),
        about: about.as_deref(),
    };
    let rendered = skill::render(&template, &fields)?;
    for note in &rendered.notes {
        eprintln!("note: {note}");
    }
    if !install {
        print!("{}", rendered.text);
        return Ok(());
    }

    let dir = match dir {
        Some(dir) => dir.to_path_buf(),
        None => skill::skills_dir()?,
    }
    .join(&project.name);
    let path = dir.join("SKILL.md");
    let before = std::fs::read_to_string(&path).unwrap_or_default();
    if !before.is_empty() && !skill::is_generated(&before) && !replace {
        bail!(
            "{} was written by hand and rigger has not written it before.
Move what it says that only this project can say into the hub, then run again with `--replace`.",
            path.display()
        );
    }
    if before == rendered.text {
        println!("{} is already what the template says.", path.display());
        return Ok(());
    }
    std::fs::create_dir_all(&dir).with_context(|| format!("cannot create {}", dir.display()))?;
    std::fs::write(&path, &rendered.text).with_context(|| format!("cannot write {}", path.display()))?;
    let what = if before.is_empty() { "Wrote" } else { "Rewrote" };
    println!("{what} {} from {source}.", path.display());
    Ok(())
}

/// One skill for the whole line, instead of one per project.
///
/// Seventeen near-identical skills were seventeen copies of the same
/// instructions, and a change to the ritual was seventeen rewrites - or,
/// as it usually went, one rewrite and sixteen files quietly stale. What
/// differs between them is the project's name, and a name is an argument,
/// not a file.
///
/// The name of the skill is the profile's: a line of products and a ticket
/// desk are different ways of working and should not answer to one skill.
fn write_line_skill(install: bool, dir: Option<&Path>, replace: bool, template: Option<&Path>, print_template: bool) -> Result<()> {
    if print_template {
        print!("{}", skill::DEFAULT_LINE_TEMPLATE);
        return Ok(());
    }
    let db = Db::open(&paths::db_path()?)?;
    let line = profile::Config::load()?.current_name().to_string();
    let (template, source) = skill::load_line_template(template)?;
    let listed = listed_projects(&db)?;
    let description = skill::line_description(&line, &listed);
    let rendered = skill::render_line(&template, &line, &description, &listed)?;
    if !install {
        print!("{}", rendered.text);
        return Ok(());
    }

    let dir = match dir {
        Some(dir) => dir.to_path_buf(),
        None => skill::skills_dir()?,
    }
    .join(&line);
    let path = dir.join("SKILL.md");
    let before = std::fs::read_to_string(&path).unwrap_or_default();
    if !before.is_empty() && !skill::is_generated(&before) && !replace {
        bail!(
            "{} was written by hand and rigger has not written it before.
Move what it says into the record, then run again with `--replace`.",
            path.display()
        );
    }
    if before == rendered.text {
        println!("{} is already what the template says.", path.display());
        return Ok(());
    }
    std::fs::create_dir_all(&dir).with_context(|| format!("cannot create {}", dir.display()))?;
    std::fs::write(&path, &rendered.text).with_context(|| format!("cannot write {}", path.display()))?;
    let what = if before.is_empty() { "Wrote" } else { "Rewrote" };
    println!(
        "{what} {} from {source}: {} projects, description {} of {} characters.",
        path.display(),
        listed.len(),
        description.chars().count(),
        skill::DESCRIPTION_LIMIT
    );
    Ok(())
}

/// Every project the line's skill lists, in the order it lists them.
///
/// A place the record keeps for itself is left out: it has no repository
/// to work in and no stage to continue, so naming it among the projects
/// would be offering an assistant somewhere it cannot go.
fn listed_projects(db: &Db) -> Result<Vec<skill::Listed>> {
    let mut listed: Vec<skill::Listed> = db
        .projects()?
        .into_iter()
        .filter(|p| p.kind == db::Kind::Repo)
        .map(|p| skill::Listed {
            about: repo::detect_about(Path::new(&p.path)),
            name: p.name,
            path: p.path,
        })
        .collect();
    listed.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(listed)
}

fn open_project(db: &Db, name: &str) -> Result<db::Project> {
    if let Some(project) = db.project_by_name(name)? {
        return Ok(project);
    }
    // The profile's own name is a place, not a typo: it is where facts
    // about every project go - the rituals of the line, a retro across all
    // of them. Made on demand rather than by a setup step nobody would know
    // to run, the way a desk makes itself the first time a card needs one.
    if name == profile::Config::load()?.current_name() {
        return db.profile_project();
    }
    bail!("no project named '{name}'; see `rigger project list`")
}

/// A project named outright, or the one the working directory sits in.
///
/// A hook has no project name to pass: the Stop hook of an assistant is
/// handed a working directory and nothing else. But it runs *in* the
/// project, and the record already knows every project by its path - so the
/// directory is the name, and the hook needs to be told nothing.
///
/// Walks upwards, because a session ends wherever the last command left the
/// shell, which may be a subdirectory of the checkout.
fn project_here(db: &Db, name: Option<&str>) -> Result<db::Project> {
    if let Some(name) = name {
        return open_project(db, name);
    }
    let here = std::env::current_dir().context("cannot read the working directory")?;
    let here = dunce::canonicalize(&here).unwrap_or(here);
    for dir in here.ancestors() {
        if let Some(project) = db.project_by_path(&dir.to_string_lossy())? {
            return Ok(project);
        }
    }
    bail!(
        "no project recorded at {} or above it; name one, or add this directory with `rigger project add`",
        here.display()
    )
}

fn show_project(project: &str, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    let about = match project.kind {
        db::Kind::Repo => repo::detect_about(Path::new(&project.path)),
        db::Kind::Service => None,
    };
    let screen = show::build(&db, &project, about)?;
    if json {
        println!("{}", serde_json::to_string_pretty(&screen)?);
        return Ok(());
    }
    print!("{}", show::render(&screen));
    Ok(())
}

fn show_context(project: &str, json: bool, explain: bool, budget: usize) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    let packet = context::build(&db, &project, budget)?;

    if json {
        println!("{}", serde_json::to_string_pretty(&packet)?);
        return Ok(());
    }
    let text = context::render(&packet);
    print!("{text}");
    if explain {
        println!("\n## Cost");
        for cost in context::costs(&packet) {
            println!("{:<14} {:>5} tokens", cost.section, cost.tokens);
        }
        println!("{:<14} {:>5} tokens of {budget}", "total", context::estimate_tokens(&text));
        // What the budget refused, by name. The packet says how many
        // events it dropped; this says which, so that "there is something
        // you have not seen" can be acted on.
        print!("{}", context::render_dropped(&packet));
    }
    Ok(())
}

fn open_session(project: &str, print: bool, budget: usize) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    let packet = context::build(&db, &project, budget)?;
    let message = open::first_message(&context::render(&packet));

    if print {
        print!("{message}");
        return Ok(());
    }
    let dir = Path::new(&project.path);
    open::check_dir(dir)?;
    let (program, _) = open::assistant();
    eprintln!("Starting {program} in {} with the packet for {}", project.path, project.name);
    let code = open::run(dir, &message)?;
    if code != 0 {
        std::process::exit(code);
    }
    Ok(())
}

/// Reads git for one project, or for every recorded project.
fn sync_projects(project: Option<&str>, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let projects = match project {
        Some(name) => vec![open_project(&db, name)?],
        None => db.projects()?,
    };
    let mut reports = Vec::new();
    for project in &projects {
        // A place the record keeps for itself has no repository, and asking
        // git about it would warn on every run about a project working
        // exactly as intended. Named on its own it says so once, rather
        // than failing at something it was never meant to do.
        if !project.kind.reads_git() {
            if projects.len() == 1 {
                println!("{} is a place the record keeps for itself; there is no repository to read", project.name);
            }
            continue;
        }
        reports.push(sync::sync(&db, project)?);
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&reports)?);
        return Ok(());
    }
    for report in &reports {
        print_sync(report, projects.len() > 1);
    }
    Ok(())
}

/// One project's sync, as a line or as a paragraph.
///
/// A quiet project prints nothing when several are synced at once: a run
/// across the whole line is read for what changed, and seventeen "nothing
/// changed" lines hide the two that did.
fn print_sync(report: &sync::Report, many: bool) {
    let quiet = !report.changed() && report.untagged.is_empty() && report.warnings.is_empty();
    if many && quiet {
        return;
    }
    println!("{}:", report.project);
    for warning in &report.warnings {
        println!("  note: {warning}");
    }
    let newly: Vec<&sync::Shipped> = report.shipped.iter().filter(|s| s.newly).collect();
    for shipped in &newly {
        let unplanned = report.unplanned.contains(&shipped.version);
        let note = if unplanned { "  (not in the plan)" } else { "" };
        println!("  shipped    {} on {}{note}", shipped.version, shipped.date);
    }
    if report.changes_recorded > 0 {
        let n = report.changes_recorded;
        let plural = if n == 1 { "change" } else { "changes" };
        println!("  read       {n} {plural} from commit messages");
    }
    for version in &report.untagged {
        println!("  no tag     {version} is closed in the plan");
    }
    // Activity is state, not news: it says the same thing on every run until
    // someone commits. Printed when there is something else to say, so a run
    // that changed nothing does not end with a line that looks like it did.
    if report.commits_since_tag > 0 && !quiet {
        let since = match report.shipped.iter().max_by_key(|s| db::version_order(&s.version)) {
            Some(newest) => format!(" since {}", newest.version),
            None => String::new(),
        };
        let when = report.last_commit_at.as_deref().unwrap_or("unknown");
        let commits = report.commits_since_tag;
        let plural = if commits == 1 { "commit" } else { "commits" };
        println!("  activity   {commits} {plural}{since}, last on {when}");
    }
    if quiet {
        println!("  nothing changed");
    }
}

/// An event written against a card, under the desk.
fn note_on_card(task: &str, kind: &str, text: &str) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    if kind == "state" {
        bail!("a state line belongs to a project's README, not to a card");
    }
    let card = find_card(&db, task)?;
    let desk = db.desk_project()?;
    db.record_task_event(desk.id, card.id, kind, text, &db::now(), "assistant")?;
    println!("Recorded a {kind} on {}", card.key);
    Ok(())
}

fn note(project: &str, kind: &str, text: &str, principle: Option<&str>, asked_by: Option<&str>) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    // A state line is not an event: it is the top of the README's state
    // block, which an export writes from the record.
    if kind == "state" {
        db.add_state_line(project.id, &db::today(), text)?;
        println!("Added a state line for {}; `rigger export` writes it into the README", project.name);
        return Ok(());
    }
    // A principle names what a decision stands on, and only a decision
    // stands on one: a change or a gate run is something that happened, not
    // something believed. Said rather than ignored, because a principle
    // silently dropped is a principle the owner thinks is recorded.
    if principle.is_some() && kind != "decision" {
        bail!("a principle belongs to a decision; this is a {kind}");
    }
    // The neighbour has to exist before the wish is written, so that a
    // typo in the name is a refusal rather than a wish nobody asked for.
    let asker = match asked_by {
        Some(name) => Some(open_project(&db, name)?),
        None => None,
    };
    if let Some(asker) = &asker
        && asker.id == project.id
    {
        bail!("{} cannot be the neighbour asking {} for something", asker.name, project.name);
    }
    let change = db.record_event(project.id, kind, text, &db::now(), "assistant")?;
    if let Some(id) = db.latest_event_id(project.id, kind)? {
        if let Some(principle) = principle {
            db.name_principle(id, principle)?;
        }
        if let Some(asker) = &asker {
            db.name_asker(id, asker.id)?;
        }
    }
    match (kind, &asker) {
        ("wish", Some(asker)) => println!("Recorded a wish for {} from {}", project.name, asker.name),
        _ => println!("Recorded a {kind} for {}", project.name),
    }
    if let Some(principle) = principle {
        println!("  on the principle {principle:?}");
    }
    if change == db::Change::Unchanged {
        println!("  the record already held it");
    }
    Ok(())
}

fn resolve(project: &str, id: i64, answer: Option<&str>) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    let (kind, body) = db.resolve_event(project.id, id, answer)?;
    let first_line = body.lines().next().unwrap_or(&body);
    match kind.as_str() {
        "question" => println!("Answered [{id}]: {first_line}"),
        _ => println!("Sorted [{id}]: {first_line}"),
    }
    if answer.is_some() {
        println!("  the answer is recorded as a decision");
    }
    Ok(())
}

/// Searches every project's events at once.
fn find(query: &str, project: Option<&str>, kind: Option<&str>, limit: u32, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    // A project that does not exist is a typo, not an empty result: saying
    // "nothing found" would send someone looking for the wrong thing.
    if let Some(name) = project {
        open_project(&db, name)?;
    }
    use search::Provider as _;
    let provider = search::Fts(&db);
    let hits = search::look(&provider, query, project, kind, limit).with_context(|| format!("{query:?} is not a search {} understands", provider.name()))?;

    if json {
        println!("{}", serde_json::to_string_pretty(&hits)?);
        return Ok(());
    }
    if hits.is_empty() {
        println!("{}", search::nothing_found(query, project, kind));
        return Ok(());
    }
    // The project column is dead weight when the search was for one project.
    let show_project = project.is_none();
    for event in &hits.events {
        print!("{}", search::render_event(event, show_project));
    }
    // Documents under the events, and named: a vision and a decision are
    // different kinds of answer, and one that has to be opened with a
    // second command should say so rather than look like a line of the
    // list above it.
    if !hits.documents.is_empty() {
        if !hits.events.is_empty() {
            println!();
        }
        println!("Documents");
        for doc in &hits.documents {
            print!("{}", search::render_document(doc, show_project));
            println!("             {}", search::open_command(doc));
        }
    }
    if hits.events.len() as u32 == limit {
        println!("({limit} shown; --limit for more)");
    }
    Ok(())
}

/// The work that went into one version.
fn why(project: Option<&str>, version: Option<&str>, principle: Option<&str>, principles: bool, json: bool) -> Result<()> {
    if principles {
        return list_principles(json);
    }
    if let Some(principle) = principle {
        return why_principle(principle, project, json);
    }
    let (Some(project), Some(version)) = (project, version) else {
        bail!("`why` wants a project and a version, or `--principle <name>`; `rigger why --principles` lists the names")
    };
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    let why = search::why(&db, &project, version)?;

    if json {
        println!("{}", serde_json::to_string_pretty(&why)?);
        return Ok(());
    }

    let mut heading = why.version.name.clone();
    if let Some(title) = &why.version.title {
        heading.push_str(&format!(" · {title}"));
    }
    match &why.version.shipped_at {
        Some(on) => println!("{heading} — shipped {on}"),
        None => println!("{heading} — being built"),
    }
    match &why.after {
        Some(before) => println!("the work after {} ({})", before.name, before.shipped_at.as_deref().unwrap_or("undated")),
        None => println!("the work from the start of the record"),
    }
    println!();

    if why.events.is_empty() {
        println!("Nothing was recorded in that window.");
        // Two releases can share a moment - a tag points at a commit, and
        // this line sometimes tags two of them in the same second. Saying so
        // is better than an empty answer that looks like a missing record.
        if let Some(before) = &why.after
            && before.shipped_ts.is_some()
            && before.shipped_ts == why.version.shipped_ts
        {
            println!(
                "{} and {} were tagged in the same second, so no work falls between them.",
                before.name, why.version.name
            );
        }
        return Ok(());
    }
    for event in &why.events {
        print!("{}", search::render_event(event, false));
    }
    Ok(())
}

/// The names the record has used for principles, and how often.
///
/// A vocabulary, not a list to maintain: what makes a name a principle of
/// this profile is that a decision was recorded on it. A list kept beside
/// the decisions would be a second truth, and the one that went stale.
fn list_principles(json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let principles = db.principles()?;
    if json {
        println!("{}", serde_json::to_string_pretty(&principles)?);
        return Ok(());
    }
    if principles.is_empty() {
        println!("No decision names a principle yet.");
        println!("`rigger note <project> <text> --kind decision --principle <name>` starts one.");
        return Ok(());
    }
    for (name, count) in &principles {
        println!("{name}  —  {}", plural(*count as usize, "decision", "decisions"));
    }
    Ok(())
}

/// One principle read across the whole line.
///
/// A principle is believed because of what happened, and what happened is
/// spread over eighteen projects: "no users, no compatibility" was arrived
/// at in one product and applied in six. Read one project at a time it
/// looks like six opinions; read as one thread it is something the line
/// learnt, and the thread is what makes it arguable.
fn why_principle(principle: &str, project: Option<&str>, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    if let Some(name) = project {
        open_project(&db, name)?;
    }
    let mut events = db.on_principle(principle)?;
    if let Some(name) = project {
        events.retain(|e| e.project == name);
    }
    if json {
        println!("{}", serde_json::to_string_pretty(&events)?);
        return Ok(());
    }
    if events.is_empty() {
        println!("Nothing stands on {principle:?} in the record.");
        // A principle nobody has used is far likelier a misspelling than a
        // new one: the names are written by hand, twice, months apart.
        let known = db.principles()?;
        if !known.is_empty() {
            println!();
            println!("The record knows these:");
            for (name, count) in known.iter().take(12) {
                println!("  {name} ({count})");
            }
        }
        return Ok(());
    }
    let projects: std::collections::BTreeSet<&str> = events.iter().map(|e| e.project.as_str()).collect();
    println!("{principle}");
    println!(
        "{} across {}",
        plural(events.len(), "decision", "decisions"),
        plural(projects.len(), "project", "projects")
    );
    println!();
    for event in &events {
        let day = event.at.split('T').next().unwrap_or(&event.at);
        let version = event.version.as_deref().map(|v| format!(" · {v}")).unwrap_or_default();
        println!("{day} · {}{version}", event.project);
        for line in event.body.lines() {
            println!("  {line}");
        }
        println!();
    }
    Ok(())
}

/// One side of a link as it is written on a command line: `kasl@v1.13.0`,
/// or just `kasl`.
fn link_side(text: &str) -> (&str, Option<&str>) {
    match text.split_once('@') {
        Some((project, version)) if !version.is_empty() => (project, Some(version)),
        _ => (text, None),
    }
}

fn link_add(from: &str, to: &str, kind: LinkKind, note: Option<&str>) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let (from_name, from_version) = link_side(from);
    let (to_name, to_version) = link_side(to);
    let from_project = open_project(&db, from_name)?;
    let to_project = open_project(&db, to_name)?;
    if from_project.id == to_project.id {
        bail!("a link joins two projects; {} is one", from_project.name);
    }
    let kind = kind.to_domain();
    let (id, change, anchored) = db.add_link(&db::NewLink {
        kind,
        from_project: from_project.id,
        from_version,
        to_project: to_project.id,
        to_version,
        note,
    })?;
    let side = |name: &str, version: Option<&String>| match version {
        Some(v) => format!("{name} {v}"),
        None => name.to_string(),
    };
    let arrow = if kind.symmetric() { "<->" } else { "->" };
    let both = format!(
        "{} {arrow} {} ({kind})",
        side(&from_project.name, anchored.from.as_ref()),
        side(&to_project.name, anchored.to.as_ref())
    );
    match change {
        db::Change::Added => println!("[{id}] {both}"),
        _ => println!("[{id}] already recorded: {both}"),
    }
    Ok(())
}

fn link_list(project: Option<&str>, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let links = match project {
        Some(name) => {
            let project = open_project(&db, name)?;
            db.links_of(project.id)?
        }
        None => {
            let mut all: Vec<link::Link> = Vec::new();
            for project in db.projects()? {
                for found in db.links_of(project.id)? {
                    // Each link is found from both of its ends; keep the
                    // first sighting so the list is of links, not of ends.
                    if !all.iter().any(|seen| seen.id == found.id) {
                        all.push(found);
                    }
                }
            }
            all.sort_by(|a, b| a.near.project.cmp(&b.near.project).then_with(|| a.id.cmp(&b.id)));
            all
        }
    };
    if json {
        println!("{}", serde_json::to_string_pretty(&links)?);
        return Ok(());
    }
    if links.is_empty() {
        match project {
            Some(name) => println!("{name} is tied to nothing in the record."),
            None => println!("The record holds no links yet."),
        }
        println!("`rigger link add <project>[@version] <project>[@version]` records one.");
        return Ok(());
    }
    for found in &links {
        println!("{}", render_link(found));
    }
    Ok(())
}

/// One link on one line, read from the near end.
fn render_link(found: &link::Link) -> String {
    let side = |end: &link::End| match &end.version {
        Some(version) => format!("{} {version}", end.project),
        None => end.project.clone(),
    };
    let arrow = if found.kind.symmetric() { "<->" } else { "->" };
    let note = found.note.as_deref().map(|n| format!("  {n}")).unwrap_or_default();
    format!("[{}] {:<9} {} {arrow} {}{note}", found.id, found.kind, side(&found.near), side(&found.far))
}

fn link_remove(id: i64) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    match db.remove_link(id)? {
        true => println!("Forgot link [{id}]"),
        false => bail!("the record has no link [{id}]; `rigger link list` prints the ids"),
    }
    Ok(())
}

fn link_drift(json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let parted = link::parted(&db.pairs()?);
    if json {
        println!("{}", serde_json::to_string_pretty(&parted)?);
        return Ok(());
    }
    if parted.is_empty() {
        println!("Every pair in the record has both halves in step.");
        return Ok(());
    }
    for item in &parted {
        println!("{}", drift_line(item));
    }
    Ok(())
}

/// What a parted pair says, in one line.
fn drift_line(item: &link::Parted) -> String {
    fn version(end: &link::End) -> &str {
        end.version.as_deref().unwrap_or("its half")
    }
    let note = item.note.as_deref().map(|n| format!(" — {n}")).unwrap_or_default();
    match item.drift {
        link::Drift::ShippedAlone => format!(
            "{} {} shipped without {} {}{note}",
            item.ahead.project,
            version(&item.ahead),
            item.behind.project,
            version(&item.behind),
        ),
        link::Drift::RunAhead => format!(
            "{} is {} ahead of {}, which is still at {}{note}",
            item.ahead.project,
            plural(item.versions.unwrap_or(0) as usize, "version", "versions"),
            item.behind.project,
            version(&item.behind),
        ),
    }
}

/// The questions waiting for the owner, gathered from every project.
fn inbox(project: Option<&str>, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    if let Some(name) = project {
        open_project(&db, name)?;
    }
    let mut waiting = db.open_questions()?;
    if let Some(name) = project {
        waiting.retain(|q| q.project == name);
    }
    // A neighbour's order is not a question for the owner - nobody is being
    // asked to decide anything - but it is the other thing that sits in a
    // project waiting on someone else, and the inbox is where the owner
    // looks for what is waiting. Kept as its own group rather than mixed in
    // with the questions, because answering one and doing the other are not
    // the same job.
    let mut asked = db.all_asked_wishes()?;
    if let Some(name) = project {
        asked.retain(|a| a.project == name);
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "waiting": waiting,
                "shared": owner::shared_subjects(&waiting),
                "asked_by_neighbours": asked,
            }))?
        );
        return Ok(());
    }

    if waiting.is_empty() && asked.is_empty() {
        match project {
            Some(name) => println!("{name} is waiting on nothing."),
            None => println!("Nothing is waiting on you."),
        }
        return Ok(());
    }

    let projects: std::collections::BTreeSet<&str> = waiting.iter().map(|q| q.project.as_str()).collect();
    if waiting.is_empty() {
        print_asked(&asked, project.is_some());
        return Ok(());
    }
    match project {
        Some(_) => println!(
            "{}
",
            plural(waiting.len(), "question", "questions")
        ),
        None => println!(
            "{} in {}
",
            plural(waiting.len(), "question", "questions"),
            plural(projects.len(), "project", "projects")
        ),
    }

    // Grouped by project, because answering is done a project at a time -
    // and within one, oldest first, since that is what has waited longest.
    let mut last: Option<&str> = None;
    for question in &waiting {
        let name = if last == Some(question.project.as_str()) {
            String::new()
        } else {
            question.project.clone()
        };
        last = Some(&question.project);
        println!("{name:<12} [{:>3}] {}  {}", question.id, question.date, owner::subject(&question.body));
    }

    // One answer that settles three projects is the most valuable thing on
    // this screen, and without saying so it looks like three separate jobs.
    let shared = owner::shared_subjects(&waiting);
    if !shared.is_empty() {
        println!(
            "
Asked by several projects - one answer settles each group:"
        );
        for group in &shared {
            println!("  {} — {}", group.subject, group.projects.join(", "));
        }
    }
    print_asked(&asked, project.is_some());
    println!(
        "
Answer one with: rigger resolve <project> <id> \"<answer>\""
    );
    Ok(())
}

/// The orders neighbours have placed, as their own group.
///
/// These are not questions and the owner is not being asked to decide
/// anything: they are work one product is waiting on another to do. They
/// belong on this screen because it is where the owner looks for what is
/// waiting - and apart from the questions because the two are answered in
/// entirely different ways.
fn print_asked(asked: &[db::AskedOf], one_project: bool) {
    if asked.is_empty() {
        return;
    }
    println!();
    println!("Neighbours are asking for:");
    let mut last: Option<&str> = None;
    for wish in asked {
        // Grouped by the project being asked, like the questions above, so
        // that one product's orders read as one list.
        let name = match (one_project, last == Some(wish.project.as_str())) {
            (true, _) | (_, true) => String::new(),
            _ => wish.project.clone(),
        };
        last = Some(&wish.project);
        let first = wish.body.lines().next().unwrap_or("").trim();
        println!("{name:<12} [{:>3}] {}  {} — {}", wish.id, wish.date, owner::subject(first), wish.asked_by);
    }
    println!();
    println!("Sort one with: rigger resolve <project> <id>");
}

/// What moved lately, per project.
fn digest(project: Option<&str>, since: &str, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let days = parse_days(since)?;
    let from = day_before(days);

    let projects = match project {
        Some(name) => vec![open_project(&db, name)?],
        None => db.projects()?,
    };

    // The tier signals are read for the current week, whatever window the
    // digest itself covers: a promise broken is broken now, and a shorter
    // `--since` should not hide it.
    let signals = week_facts(&db, calendar::Week::current())?.signals;

    let mut reports = Vec::new();
    for project in &projects {
        let facts = db.digest(project.id, &from)?;
        let stage = db.current_stage(project.id)?;
        let next = stage.map(|s| match s.title {
            Some(title) => format!("{} · {title}", s.version),
            None => s.version,
        });
        let quiet = db.last_event_at(project.id)?.as_deref().and_then(days_since_utc);
        let signal = signals.iter().find(|s| s.project == project.name).map(signal_line);
        let lines = owner::digest_lines(&facts, next.as_deref(), quiet, signal.as_deref());
        reports.push((project.name.clone(), facts, next, lines, signal));
    }

    if json {
        let payload: Vec<_> = reports
            .iter()
            .map(|(name, facts, next, lines, signal)| serde_json::json!({ "project": name, "facts": facts, "next": next, "lines": lines, "signal": signal }))
            .collect();
        println!("{}", serde_json::to_string_pretty(&serde_json::json!({ "since": from, "projects": payload }))?);
        return Ok(());
    }

    println!(
        "Since {from}
"
    );

    // A project with nothing but its next stage to report has not moved:
    // naming it in one line beats five lines that say nothing happened.
    //
    // A project raising a signal is the exception, and the important one: a
    // carrying product that has stopped releasing is quiet by definition,
    // and folding it into the quiet line is exactly how it stays unnoticed.
    let (moved, still): (Vec<_>, Vec<_>) = reports
        .iter()
        .partition(|(_, facts, _, _, signal)| signal.is_some() || !facts.shipped.is_empty() || facts.decisions + facts.findings + facts.changes > 0);

    let listed = if project.is_some() {
        reports.iter().collect::<Vec<_>>()
    } else {
        moved.clone()
    };
    for (name, _, _, lines, _) in &listed {
        println!("{name}");
        for line in lines.iter() {
            println!("  {line}");
        }
    }
    if listed.is_empty() {
        println!("Nothing moved.");
    }
    if project.is_none() && !still.is_empty() {
        let names: Vec<&str> = still.iter().map(|(name, _, _, _, _)| name.as_str()).collect();
        println!(
            "
Quiet: {}",
            names.join(", ")
        );
    }
    Ok(())
}

/// `7d`, `30d`, or a bare number of days.
fn parse_days(since: &str) -> Result<i64> {
    let digits = since.trim().trim_end_matches(['d', 'D']);
    digits
        .parse::<i64>()
        .ok()
        .filter(|d| *d >= 0)
        .with_context(|| format!("{since:?} is not a number of days; write it as `7d` or `30`"))
}

/// The day `days` before today, in UTC.
fn day_before(days: i64) -> String {
    let seconds = jiff::Timestamp::now().as_second() - days * 86_400;
    jiff::Timestamp::from_second(seconds)
        .map(|t| t.to_string().split('T').next().unwrap_or_default().to_string())
        .unwrap_or_default()
}

/// Whole days between a recorded timestamp and now.
fn days_since_utc(timestamp: &str) -> Option<i64> {
    let then: jiff::Timestamp = timestamp.parse().ok()?;
    Some(((jiff::Timestamp::now().as_second() - then.as_second()) / 86_400).max(0))
}

fn plural(n: usize, one: &str, many: &str) -> String {
    format!("{n} {}", if n == 1 { one } else { many })
}

/// A body given on the command line, or read from standard input when it
/// is `-`: a document is prose, and prose arrives from a pipe as often as
/// from a keyboard.
fn body_argument(body: &str) -> Result<String> {
    if body != "-" {
        return Ok(body.to_string());
    }
    let mut text = String::new();
    std::io::Read::read_to_string(&mut std::io::stdin(), &mut text).context("cannot read the body from standard input")?;
    Ok(text)
}

/// Opens `seed` in the editor and gives back what was saved.
///
/// The scratch file is removed afterwards whatever happened: it holds the
/// owner's prose, and leaving copies of that in the temporary directory is
/// not something a record tool should do.
fn body_from_editor(project: &str, slug: &str, seed: &str) -> Result<String> {
    let path = doc::scratch_path(project, slug);
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("cannot make {}", dir.display()))?;
    }
    std::fs::write(&path, seed).with_context(|| format!("cannot write {}", path.display()))?;
    let edited = doc::edit_file(&path).and_then(|()| std::fs::read_to_string(&path).with_context(|| format!("cannot read back {}", path.display())));
    let _ = std::fs::remove_file(&path);
    // The directory is this process's, so it goes with the file it held.
    let _ = std::fs::remove_dir(doc::scratch_dir());
    edited
}

/// The body for a new or edited document: what was passed, or what the
/// editor was left with.
fn body_for(project: &str, slug: &str, body: Option<&str>, seed: &str) -> Result<String> {
    match body {
        Some(body) => body_argument(body),
        None => body_from_editor(project, slug, seed),
    }
}

fn doc_list(project: &str, kind: Option<&str>, json: bool) -> Result<()> {
    if let Some(kind) = kind {
        doc::check_kind(kind)?;
    }
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    let docs = db.documents(project.id, kind)?;
    if json {
        // Without the bodies: a listing is for finding a document, and the
        // vision of a mature project is longer than the rest of the screen.
        println!(
            "{}",
            serde_json::to_string_pretty(
                &docs
                    .iter()
                    .map(|d| serde_json::json!({
                        "slug": d.slug,
                        "kind": d.kind,
                        "title": d.title,
                        "updated_at": d.updated_at,
                        "bytes": d.body.len(),
                    }))
                    .collect::<Vec<_>>()
            )?
        );
        return Ok(());
    }
    if docs.is_empty() {
        println!("{} has no documents yet.", project.name);
        println!("Write one with: rigger doc add {} \"Vision\" --kind vision", project.name);
        return Ok(());
    }
    println!("{}:", plural(docs.len(), "document", "documents"));
    // The addresses set the column, so one long slug pushes the rest along
    // rather than stepping out of a fixed width and bending the whole table.
    let width = docs.iter().map(|d| d.slug.chars().count()).max().unwrap_or(0).max(12);
    for d in &docs {
        let when = days_since_utc(&d.updated_at)
            .map(|days| match days {
                0 => "today".to_string(),
                1 => "yesterday".to_string(),
                d => format!("{d} days ago"),
            })
            .unwrap_or_else(|| "unknown".to_string());
        println!("  {:<width$} {:<10} {:<12} {}", d.slug, d.kind, when, first_line(&d.title));
    }
    Ok(())
}

fn doc_show(project: &str, slug: &str, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    let doc = open_document(&db, &project, slug)?;
    if json {
        println!("{}", serde_json::to_string_pretty(&doc)?);
        return Ok(());
    }
    // The body alone, so that `rigger doc show x vision > vision.md` gives
    // back a file rather than a screen with a header glued to the top.
    println!("{}", doc.body.trim_end());
    Ok(())
}

fn doc_add(project: &str, title: &str, kind: &str, slug: Option<&str>, body: Option<&str>) -> Result<()> {
    doc::check_kind(kind)?;
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;

    // A vision written twice is a vision nobody reads, so the second one is
    // refused by name rather than made: the fix is to edit the first.
    if doc::is_singular(kind)
        && let Some(existing) = db.documents(project.id, Some(kind))?.first()
    {
        bail!(
            "{} already has a {kind}: '{}'; edit it with `rigger doc edit {} {}`",
            project.name,
            existing.slug,
            project.name,
            existing.slug
        );
    }

    let slug = match slug {
        Some(slug) => slug.to_string(),
        // A title with no ASCII in it - the owner's hub is in Russian -
        // slugs to nothing, and an empty address is no address: the kind
        // plus a number is one that can at least be typed.
        None => match db::slugify(title) {
            slug if !slug.is_empty() => slug,
            _ => next_slug(&db, project.id, kind)?,
        },
    };
    if db.document(project.id, &slug)?.is_some() {
        bail!(
            "{} already has a document at '{slug}'; give another with --slug, or edit that one",
            project.name
        );
    }

    let text = body_for(&project.name, &slug, body, &doc::template(kind, title))?;
    if text.trim().is_empty() {
        println!("Nothing was written; no document was made.");
        return Ok(());
    }
    let written = db.write_document(project.id, kind, &slug, title, &text)?;
    println!(
        "Wrote {} ({kind}, {}) to {}",
        written.slug,
        plural(written.body.len(), "byte", "bytes"),
        project.name
    );
    Ok(())
}

fn doc_edit(project: &str, slug: &str, title: Option<&str>, body: Option<&str>) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    let doc = open_document(&db, &project, slug)?;

    // A title change alone must not open an editor: it was asked for on the
    // command line and is answered there.
    let text = match (title, body) {
        (Some(_), None) => doc.body.clone(),
        _ => body_for(&project.name, &doc.slug, body, &doc.body)?,
    };
    let title = title.unwrap_or(&doc.title);
    if text == doc.body && title == doc.title {
        println!("{} is unchanged.", doc.slug);
        return Ok(());
    }
    if text.trim().is_empty() {
        bail!(
            "the document was left empty; nothing was written. Remove it with `rigger doc remove {} {}`",
            project.name,
            doc.slug
        );
    }
    let written = db.write_document(project.id, &doc.kind, &doc.slug, title, &text)?;
    println!("Wrote {} ({}, {})", written.slug, written.kind, plural(written.body.len(), "byte", "bytes"));
    Ok(())
}

fn doc_remove(project: &str, slug: &str) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    let doc = open_document(&db, &project, slug)?;
    db.delete_document(project.id, &doc.slug)?;
    println!("Removed {} ({}) from {}", doc.slug, doc.kind, project.name);
    Ok(())
}

/// Shows the skeleton a kind starts from, or writes it out to be edited.
///
/// Without this the override is a filename in a doc page: the way to change
/// what a vision asks you should be to run the command that shows it.
fn doc_template(kind: &str, write: bool) -> Result<()> {
    doc::check_kind(kind)?;
    if !write {
        let paths = doc::template_paths(kind)?;
        let from = paths.iter().find(|p| p.is_file());
        println!("{}", doc::template(kind, doc::TITLE_PLACEHOLDER).trim_end());
        println!();
        match from {
            Some(path) => println!("(from {})", path.display()),
            None => println!("(the built-in skeleton; `rigger doc template {kind} --write` to make it yours)"),
        }
        return Ok(());
    }
    let path = doc::template_paths(kind)?
        .into_iter()
        .next()
        .context("the profile has no directory to write a skeleton into")?;
    if path.exists() {
        bail!("{} already exists; edit it, or delete it to go back to the built-in one", path.display());
    }
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("cannot make {}", dir.display()))?;
    }
    // Written with the placeholder in it, so the first edit does not have to
    // discover that the title is substituted.
    std::fs::write(&path, doc::template(kind, doc::TITLE_PLACEHOLDER)).with_context(|| format!("cannot write {}", path.display()))?;
    println!("Wrote {}", path.display());
    println!("Edit it; `{}` in it becomes the document's title.", doc::TITLE_PLACEHOLDER);
    Ok(())
}

/// Prints how the work is done: the rituals of the line, then those of one
/// project.
///
/// Both are documents, and the split is the point. What every project does
/// the same way (a stage ends in a tag, English is what ships, the gate is
/// green before a commit) is written once, against the profile; what only
/// this project can say about itself is written against the project.
/// Before this, the two were glued together into every skill file, so a
/// change to the line's rituals was seventeen edits, and the copies
/// drifted.
///
/// Read by an assistant at the start of a sitting, which is why it prints
/// a document and nothing around it: no counts, no timestamps, no advice.
fn rules(project: Option<&str>, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let line = db.service_project()?;
    let line_rules = match &line {
        Some(p) => db.singular_document(p.id, db::RULES_KIND)?,
        None => None,
    };
    let project = project.map(|name| open_project(&db, name)).transpose()?;
    let project_rules = match &project {
        Some(p) => db.singular_document(p.id, db::RULES_KIND)?,
        None => None,
    };

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "line": line_rules.as_ref().map(|d| &d.body),
                "project": project.as_ref().map(|p| &p.name),
                "project_rules": project_rules.as_ref().map(|d| &d.body),
            }))?
        );
        return Ok(());
    }

    let mut printed = false;
    if let Some(doc) = &line_rules {
        println!("{}", doc.body.trim_end());
        printed = true;
    }
    if let Some(doc) = &project_rules {
        if printed {
            println!();
        }
        println!("{}", doc.body.trim_end());
        printed = true;
    }
    if printed {
        return Ok(());
    }

    // Nothing written yet is a state to get out of, so the way out is the
    // whole message.
    let profile = profile::Config::load()?.current_name();
    match &project {
        Some(p) => println!("Neither the line nor {} has written down how the work is done.", p.name),
        None => println!("The line has not written down how the work is done."),
    }
    println!("Write the line's with:    rigger doc add {profile} \"Rituals\" --kind rituals");
    if let Some(p) = &project {
        println!("And what only {} says:   rigger doc add {} \"Rituals\" --kind rituals", p.name, p.name);
    }
    Ok(())
}

/// A document by its address, with the list of what there is when it is
/// not one: a wrong address is nearly always a typo for a right one.
fn open_document(db: &Db, project: &db::Project, slug: &str) -> Result<db::Document> {
    if let Some(doc) = db.document(project.id, slug)? {
        return Ok(doc);
    }
    let known = db.documents(project.id, None)?;
    if known.is_empty() {
        bail!("{} has no document at '{slug}', and none at all yet", project.name);
    }
    bail!(
        "{} has no document at '{slug}'; it has {}",
        project.name,
        known.iter().map(|d| d.slug.as_str()).collect::<Vec<_>>().join(", ")
    );
}

/// An address for a document whose title gives none: the kind, then the
/// first free number after it.
fn next_slug(db: &Db, project_id: i64, kind: &str) -> Result<String> {
    if db.document(project_id, kind)?.is_none() {
        return Ok(kind.to_string());
    }
    for n in 2.. {
        let candidate = format!("{kind}-{n}");
        if db.document(project_id, &candidate)?.is_none() {
            return Ok(candidate);
        }
    }
    unreachable!("the loop returns on the first free number")
}

/// How many copies `backup` keeps when nothing else is asked.
///
/// Enough that a fault noticed a few sittings late still has a copy from
/// before it, few enough that a database of a few megabytes does not turn
/// its own directory into a disk problem.
const KEEP_BACKUPS: usize = 10;

/// When `doctor` starts saying the insurance is old, and when it says it is
/// a problem. A day is one sitting's worth of work at risk; a week is the
/// point where the copy no longer resembles the record.
const BACKUP_STALE_DAYS: i64 = 1;
const BACKUP_OLD_DAYS: i64 = 7;

/// How `doctor` judges the age of the newest copy: fresh, stale, old, or
/// none at all. One function so the JSON and the printed line cannot drift.
fn backup_state(age_days: Option<i64>) -> &'static str {
    match age_days {
        None => "none",
        Some(d) if d >= BACKUP_OLD_DAYS => "old",
        Some(d) if d >= BACKUP_STALE_DAYS => "stale",
        Some(_) => "fresh",
    }
}

fn backup(keep: usize, list: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    if list {
        let copies = db.backups()?;
        if copies.is_empty() {
            println!("No copies yet. Take one with: rigger backup");
            return Ok(());
        }
        println!("{} newest first:", plural(copies.len(), "copy", "copies"));
        for path in &copies {
            let age = path
                .file_name()
                .and_then(|n| db::stamp_of(&n.to_string_lossy()))
                .and_then(|at| days_since_utc(&at))
                .map(|d| match d {
                    0 => "today".to_string(),
                    1 => "yesterday".to_string(),
                    d => format!("{d} days ago"),
                })
                .unwrap_or_else(|| "unknown".to_string());
            println!("  {:<40} {age}", path.file_name().unwrap_or_default().to_string_lossy());
        }
        return Ok(());
    }
    let target = db.backup()?;
    println!("Copied to {}", target.display());
    let removed = db.prune_backups(keep)?;
    if !removed.is_empty() {
        println!("Kept the {keep} newest, deleted {}.", plural(removed.len(), "older copy", "older copies"));
    }
    Ok(())
}

fn init() -> Result<()> {
    // The config first, so that a fresh install has a profile to speak of
    // and the file a person can edit is where `doctor` says it is.
    let config_path = profile::Config::path()?;
    if !config_path.exists() {
        profile::Config::default().save()?;
        println!("Created {} with the '{}' profile", config_path.display(), profile::DEFAULT);
    }
    let path = paths::db_path()?;
    if path.exists() {
        Db::open(&path)?;
        println!("Already initialised: {}", path.display());
        return Ok(());
    }
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
    }
    let db = Db::create(&path)?;
    println!("Created {} (schema version {})", db.path().display(), db.schema_version()?);
    println!("Next: rigger project add <path>");
    Ok(())
}

fn profile_list(json: bool) -> Result<()> {
    let config = profile::Config::load()?;
    let current = config.current_name();
    if json {
        let rows: Vec<serde_json::Value> = config
            .profiles
            .iter()
            .map(|(name, p)| serde_json::json!({ "name": name, "current": *name == current, "profile": p }))
            .collect();
        println!("{}", serde_json::to_string_pretty(&rows)?);
        return Ok(());
    }
    let width = config.profiles.keys().map(String::len).max().unwrap_or(0);
    for (name, p) in &config.profiles {
        let mark = if *name == current { "*" } else { " " };
        println!("{mark} {name:width$}  {}  {}", p.kind.as_str(), profile::db_path_for(name)?.display());
    }
    Ok(())
}

fn profile_show(name: Option<&str>, json: bool) -> Result<()> {
    let config = profile::Config::load()?;
    let name = name.map(str::to_string).unwrap_or_else(|| config.current_name());
    let Some(p) = config.profiles.get(&name) else {
        bail!("no profile named '{name}'; see `rigger profile list`");
    };
    if json {
        println!("{}", serde_json::to_string_pretty(&serde_json::json!({ "name": name, "profile": p }))?);
        return Ok(());
    }
    println!("{name}");
    println!("  kind:      {}", p.kind.as_str());
    println!("  database:  {}", profile::db_path_for(&name)?.display());
    if !p.roots.is_empty() {
        println!(
            "  roots:     {}",
            p.roots.iter().map(|r| r.display().to_string()).collect::<Vec<_>>().join(", ")
        );
    }
    if let Some(hubs) = &p.hubs {
        println!("  hubs:      {}", hubs.display());
    }
    if let Some(pattern) = &p.id_pattern {
        println!("  ids:       {pattern}");
    }
    if let Some(inbox) = &p.inbox {
        println!("  inbox:     {}", inbox.display());
    }
    println!("  config:    {}", profile::Config::path()?.display());
    Ok(())
}

fn profile_use(name: &str) -> Result<()> {
    let mut config = profile::Config::load()?;
    if !config.profiles.contains_key(name) {
        bail!("no profile named '{name}'; see `rigger profile list`");
    }
    config.current = name.to_string();
    config.save()?;
    println!("Every command now uses the '{name}' profile");
    if std::env::var_os(profile::PROFILE_ENV).is_some() {
        println!("  note: {} is set and overrides this while it is", profile::PROFILE_ENV);
    }
    Ok(())
}

/// Adds a profile and its database. The database is created here rather
/// than on first use, so that `profile list` can point at a file that is
/// there.
fn profile_add(name: &str, p: profile::Profile, use_it: bool) -> Result<()> {
    if name.trim().is_empty() || name.contains(['/', '\\', ' ']) {
        bail!("a profile name is one word, without slashes: '{name}' is not");
    }
    let mut config = profile::Config::load()?;
    if config.profiles.contains_key(name) {
        bail!("a profile named '{name}' already exists; see `rigger profile show {name}`");
    }
    let path = profile::db_path_for(name)?;
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
    }
    if !path.exists() {
        Db::create(&path)?;
    }
    config.profiles.insert(name.to_string(), p.clone());
    if use_it {
        config.current = name.to_string();
    }
    config.save()?;
    println!("Added the '{name}' profile ({}) with its database at {}", p.kind.as_str(), path.display());
    match use_it {
        true => println!("Every command now uses it"),
        false => println!("Switch to it with: rigger profile use {name}"),
    }
    Ok(())
}

/// Changes what a profile says about itself. Only the fields given change;
/// the roots given replace the roots it had, because a list appended to
/// can never be shortened.
fn profile_set(name: Option<&str>, roots: Vec<PathBuf>, hubs: Option<PathBuf>, id_pattern: Option<String>, inbox: Option<PathBuf>) -> Result<()> {
    let mut config = profile::Config::load()?;
    let name = name.map(str::to_string).unwrap_or_else(|| config.current_name());
    let Some(p) = config.profiles.get_mut(&name) else {
        bail!("no profile named '{name}'; see `rigger profile list`");
    };
    if roots.is_empty() && hubs.is_none() && id_pattern.is_none() && inbox.is_none() {
        bail!("nothing to set; give --root, --hubs, --id-pattern or --inbox");
    }
    if !roots.is_empty() {
        p.roots = roots;
    }
    if let Some(hubs) = hubs {
        p.hubs = Some(hubs);
    }
    if let Some(pattern) = id_pattern {
        p.id_pattern = Some(pattern);
    }
    if let Some(inbox) = inbox {
        p.inbox = Some(inbox);
    }
    config.save()?;
    println!("Profile '{name}' updated");
    profile_show(Some(&name), false)
}

/// The setting that names the card in hand, and when it was taken up.
const ACTIVE_CARD: &str = "active_card";
const ACTIVE_SINCE: &str = "active_since";
/// A card left open this long is not in hand any more: a desk that forgot
/// to close it yesterday must not be told today that it is.
const STALE_HOURS: i64 = 8;

/// A card by whatever names it, or a clear refusal.
fn find_card(db: &Db, text: &str) -> Result<card::Card> {
    match db.card_by_ref(text)? {
        Some(card) => Ok(card),
        None => bail!("no card named '{text}'; `rigger task find` looks one up, `rigger task new` makes one"),
    }
}

/// The task a reference means - a card by key or alias, or a plain task
/// of a project by id - with the project it belongs to.
fn find_task(db: &Db, text: &str) -> Result<(i64, i64)> {
    if let Some(card) = db.card_by_ref(text)? {
        return Ok((db.desk_project()?.id, card.id));
    }
    if let Ok(id) = text.trim().parse::<i64>()
        && let Some(project_id) = db.task_owner(id)?
    {
        return Ok((project_id, id));
    }
    bail!("no task named '{text}'; a card's key, or the id the packet lists")
}

fn task_status(task: &str, status: &str) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let (project_id, id) = find_task(&db, task)?;
    let (title, was) = db.set_task_status(project_id, id, status)?;
    match was == status {
        true => println!("Task {task} was already {status}: {title}"),
        false => println!("Task {task} is now {status} (was {was}): {title}"),
    }
    Ok(())
}

fn task_new(title: &str, key: Option<&str>, aliases: &[String], projects: &[String], branch: Option<&str>, summary: Option<&str>) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    if title.trim().is_empty() {
        bail!("a card needs a title");
    }
    let card = db.new_card(key, title, aliases)?;
    if let Some(summary) = summary {
        db.set_card_summary(card.id, summary)?;
    }
    for name in projects {
        let project = open_project(&db, name)?;
        db.link_card(card.id, project.id, branch, None)?;
    }
    // The card just made is the one in hand: nobody makes a card for a
    // task they are not about to work on.
    db.set_setting(ACTIVE_CARD, Some(&card.id.to_string()))?;
    db.set_setting(ACTIVE_SINCE, Some(&db::now()))?;
    println!("Made card {} and opened it: {}", card.key, card.title);
    if key.is_none() {
        println!("  a local key; `rigger task rename {} <ID>` when the tracker names it", card.key);
    }
    print_links(&db, card.id)?;
    Ok(())
}

fn print_links(db: &Db, task_id: i64) -> Result<()> {
    for link in db.card_links(task_id)? {
        let branch = link.branch.as_deref().map(|b| format!(" on {b}")).unwrap_or_default();
        let role = link.role.as_deref().map(|r| format!(" - {r}")).unwrap_or_default();
        println!("  {} ({}){branch}{role}", link.project, link.path);
    }
    Ok(())
}

fn task_find(query: &str, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let parsed = card::parse(query);
    let cards = db.cards(None)?;
    let (hits, verdict) = card::find(&parsed, &cards, 8);
    // The weak trail: an id or a case number mentioned in the text of
    // other cards - a task that moved leaves its old number behind.
    let shown: Vec<String> = hits.iter().map(|h| h.key.clone()).collect();
    let mut mentions = Vec::new();
    for needle in parsed.ids.iter().chain(parsed.numbers.iter()) {
        for (key, title) in db.cards_mentioning(needle, &shown)? {
            mentions.push((needle.clone(), key, title));
        }
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "verdict": verdict,
                "hits": hits,
                "mentions": mentions.iter().map(|(n, k, t)| serde_json::json!({ "needle": n, "key": k, "title": t })).collect::<Vec<_>>(),
            }))?
        );
        return Ok(());
    }
    if cards.is_empty() {
        println!("No cards yet. Make one with: rigger task new \"<title>\" [--id <KEY>]");
        return Ok(());
    }
    if hits.is_empty() {
        println!("No match among {} cards.", cards.len());
    } else {
        let width = hits.iter().map(|h| h.key.len()).max().unwrap_or(0);
        for h in &hits {
            println!("{:>3}  {:width$}  {:<16} {}  ({})", h.score, h.key, h.status, h.title, h.why);
        }
    }
    for (needle, key, title) in &mentions {
        println!("mentioned {needle}: {key} - {title}");
    }
    println!(
        "\n{}",
        match verdict {
            card::Verdict::Take => format!("take {}: it is the one.", hits[0].key),
            card::Verdict::Ask => "ask: show these and let the owner pick, or say it is new.".to_string(),
            card::Verdict::New => "new: nothing is close; make a card.".to_string(),
        }
    );
    Ok(())
}

/// The card in hand, unless it was left open longer than a working day.
fn active_card(db: &Db) -> Result<Option<card::Card>> {
    let Some(id) = db.setting(ACTIVE_CARD)? else { return Ok(None) };
    if let Some(since) = db.setting(ACTIVE_SINCE)?
        && let Ok(then) = since.parse::<jiff::Timestamp>()
        && (jiff::Timestamp::now().as_second() - then.as_second()) > STALE_HOURS * 3600
    {
        return Ok(None);
    }
    db.card(id.parse().unwrap_or_default())
}

fn task_open(task: &str) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let card = find_card(&db, task)?;
    db.set_setting(ACTIVE_CARD, Some(&card.id.to_string()))?;
    db.set_setting(ACTIVE_SINCE, Some(&db::now()))?;
    println!("Card {} is in hand: {}", card.key, card.title);
    Ok(())
}

fn task_active(json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let card = active_card(&db)?;
    if json {
        println!("{}", serde_json::to_string_pretty(&card)?);
        return Ok(());
    }
    match card {
        Some(card) => println!("{}  {:<16} {}", card.key, card.status, card.title),
        None => println!("No card is in hand. Open one with: rigger task open <KEY>"),
    }
    Ok(())
}

fn task_close(task: Option<&str>, status: &str) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let card = match task {
        Some(text) => find_card(&db, text)?,
        None => match active_card(&db)? {
            Some(card) => card,
            None => bail!("no card is in hand; name one: rigger task close <KEY>"),
        },
    };
    let desk = db.desk_project()?;
    let (title, was) = db.set_task_status(desk.id, card.id, status)?;
    if db.setting(ACTIVE_CARD)?.as_deref() == Some(&card.id.to_string()) {
        db.set_setting(ACTIVE_CARD, None)?;
        db.set_setting(ACTIVE_SINCE, None)?;
    }
    println!("Closed {} as {status} (was {was}): {title}", card.key);
    Ok(())
}

fn task_show(task: &str, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let card = find_card(&db, task)?;
    let links = db.card_links(card.id)?;
    let events = db.task_events(card.id)?;
    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({ "card": card, "links": links, "events": events.len() }))?
        );
        return Ok(());
    }
    println!("{} · {}", card.key, card.title);
    println!("  status:   {}", card.status);
    if !card.aliases.is_empty() {
        println!("  aliases:  {}", card.aliases.join(", "));
    }
    println!("  since:    {}", card.created_at);
    if let Some(summary) = &card.summary {
        println!("  summary:  {summary}");
    }
    if !links.is_empty() {
        println!("  worked in:");
        print_links(&db, card.id)?;
    }
    let mut counts = std::collections::BTreeMap::new();
    for e in &events {
        *counts.entry(e.kind.as_str()).or_insert(0) += 1;
    }
    if !counts.is_empty() {
        let parts: Vec<String> = counts.iter().map(|(k, n)| format!("{n} {k}")).collect();
        println!("  recorded: {}", parts.join(", "));
    }
    if let Some(next) = events.iter().rev().find(|e| e.kind == "next") {
        println!("  next:     {}", first_line(&next.body));
    }
    Ok(())
}

/// The packet a task starts from: what it is, where it is worked, and
/// everything written against it, by kind, newest first.
fn render_card(db: &Db, card: &card::Card, budget: usize) -> Result<String> {
    let links = db.card_links(card.id)?;
    let events = db.task_events(card.id)?;
    let mut out = format!("# {} · {}\n\n", card.key, card.title);
    out.push_str(&format!("Status: {}", card.status));
    if !card.aliases.is_empty() {
        out.push_str(&format!(" · also {}", card.aliases.join(", ")));
    }
    out.push('\n');
    if let Some(summary) = &card.summary {
        out.push_str(&format!("\n{summary}\n"));
    }
    if !links.is_empty() {
        out.push_str("\n## Worked in\n");
        for link in &links {
            let branch = link.branch.as_deref().map(|b| format!(" on `{b}`")).unwrap_or_default();
            let role = link.role.as_deref().map(|r| format!(" - {r}")).unwrap_or_default();
            out.push_str(&format!("- {} ({}){branch}{role}\n", link.project, link.path));
        }
    }
    if let Some(next) = events.iter().rev().find(|e| e.kind == "next") {
        out.push_str(&format!("\n## Next step\n{}\n", next.body.trim()));
    }
    // Newest first within a kind, and the kinds in the order a session
    // reads them: what was decided, what was found, what bit, what is
    // planned, what changed.
    let sections = [
        ("decision", "Decisions"),
        ("finding", "Findings"),
        ("pitfall", "Pitfalls"),
        ("plan", "Plan"),
        ("change", "Changes"),
        ("question", "Waiting for the owner"),
    ];
    let mut left_out = 0usize;
    for (kind, heading) in sections {
        let mut items: Vec<&db::RecentEvent> = events.iter().filter(|e| e.kind == kind).collect();
        items.reverse();
        if items.is_empty() {
            continue;
        }
        out.push_str(&format!("\n## {heading}\n"));
        for item in items {
            let line = format!("- {} · {}\n", item.date, item.body.trim());
            if context::estimate_tokens(&out) + context::estimate_tokens(&line) > budget {
                left_out += 1;
                continue;
            }
            out.push_str(&line);
        }
    }
    if left_out > 0 {
        out.push_str(&format!("\n({left_out} older events left out by the budget)\n"));
    }
    Ok(out)
}

fn task_context(task: &str, budget: usize) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let card = find_card(&db, task)?;
    print!("{}", render_card(&db, &card, budget)?);
    Ok(())
}

fn task_link(task: &str, project: &str, branch: Option<&str>, role: Option<&str>) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let card = find_card(&db, task)?;
    let project = open_project(&db, project)?;
    db.link_card(card.id, project.id, branch, role)?;
    println!("{} is worked in:", card.key);
    print_links(&db, card.id)
}

fn task_list(status: &str, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let cards = db.cards(Some(status))?;
    if json {
        println!("{}", serde_json::to_string_pretty(&cards)?);
        return Ok(());
    }
    if cards.is_empty() {
        println!(
            "No cards{}.",
            if status == "all" { "" } else { " that are " }.to_string() + if status == "all" { "" } else { status }
        );
        return Ok(());
    }
    let width = cards.iter().map(|c| c.key.len()).max().unwrap_or(0);
    for c in &cards {
        println!("{:width$}  {:<16} {}", c.key, c.status, c.title);
    }
    Ok(())
}

fn task_rename(task: &str, key: &str) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let card = find_card(&db, task)?;
    let renamed = db.rename_card(card.id, key)?;
    println!("{} is now {}; {} stays as an alias", card.key, renamed.key, card.key);
    Ok(())
}

fn task_alias(task: &str, alias: &str) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let card = find_card(&db, task)?;
    let card = db.add_alias(card.id, alias)?;
    println!("{} also goes by: {}", card.key, card.aliases.join(", "));
    Ok(())
}

fn task_summary(task: &str, text: &str) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let card = find_card(&db, task)?;
    db.set_card_summary(card.id, text)?;
    println!("{} summarised", card.key);
    Ok(())
}

fn project_add(path: PathBuf, name: Option<String>) -> Result<()> {
    let root = dunce::canonicalize(&path).with_context(|| format!("{} is not a directory rigger can read", path.display()))?;
    if !root.is_dir() {
        bail!("{} is not a directory", root.display());
    }
    let db = Db::open(&paths::db_path()?)?;
    let name = name.unwrap_or_else(|| repo::detect_name(&root));
    let remote = repo::detect_remote(&root);
    let project = db.add_project(&name, &root.to_string_lossy(), remote.as_deref(), db::Kind::Repo)?;
    println!("Recorded '{}' at {}", project.name, project.path);
    match &project.remote {
        Some(url) => println!("  remote: {url}"),
        None => println!("  remote: none (no origin in .git/config)"),
    }
    refresh_line_skill(&db)?;
    Ok(())
}

/// Rewrites the line's one skill, when one has been installed.
///
/// The body lists the projects, so a project added after it was written
/// leaves it describing a line that is one short - and an assistant asked
/// to work on the new project reads a skill that has never heard of it.
/// Only when the file is already there: installing a skill is something
/// the owner asks for once, not something `project add` decides.
fn refresh_line_skill(db: &Db) -> Result<()> {
    // Only inside the directory this run was pointed at. A run with a
    // record of its own has no business rewriting the skill in the owner's
    // home - and did, until a test's fixture turned up there.
    if !skill::may_refresh_installed() {
        return Ok(());
    }
    let line = profile::Config::load()?.current_name().to_string();
    let path = skill::skills_dir()?.join(&line).join("SKILL.md");
    let before = match std::fs::read_to_string(&path) {
        Ok(text) if skill::is_generated(&text) => text,
        _ => return Ok(()),
    };
    let (template, _) = skill::load_line_template(None)?;
    let listed = listed_projects(db)?;
    let description = skill::line_description(&line, &listed);
    let rendered = skill::render_line(&template, &line, &description, &listed)?;
    if rendered.text == before {
        return Ok(());
    }
    std::fs::write(&path, &rendered.text).with_context(|| format!("cannot write {}", path.display()))?;
    println!("  {} now lists {} projects", path.display(), listed.len());
    Ok(())
}

/// Records a place the record keeps for itself.
///
/// A retro looks across every project and has to leave its summary
/// somewhere that is not one of them. That place has no repository and
/// never will, so it is recorded as what it is: `sync` does not ask git
/// about it and `doctor` does not list it as waiting to be synced.
fn project_service(name: &str) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    // The path is a name, not a location: the column is unique and every
    // other project fills it with a directory, so a marker keeps the two
    // apart without pretending there is a directory to look in.
    let path = format!("service:{name}");
    let project = db.add_project(name, &path, None, db::Kind::Service)?;
    println!("Recorded '{}' as a place the record keeps for itself", project.name);
    println!("  no repository: sync will not ask git about it");
    Ok(())
}

fn project_list(json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let projects = db.projects()?;
    if json {
        println!("{}", serde_json::to_string_pretty(&projects)?);
        return Ok(());
    }
    if projects.is_empty() {
        println!("No projects yet. Add one with: rigger project add <path>");
        return Ok(());
    }
    let width = projects.iter().map(|p| p.name.len()).max().unwrap_or(0);
    for p in &projects {
        println!("{:width$}  {}", p.name, where_it_lives(p));
    }
    Ok(())
}

/// What to show where a project's location goes.
///
/// A place the record keeps for itself has no location, and the marker its
/// path column holds is bookkeeping - showing it reads as a broken path.
fn where_it_lives(project: &db::Project) -> String {
    match project.kind {
        db::Kind::Repo => project.path.clone(),
        db::Kind::Service => "(no repository - a place the record keeps for itself)".to_string(),
    }
}

fn project_show(name: &str, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let Some(project) = db.project_by_name(name)? else {
        bail!("no project named '{name}'; see `rigger project list`");
    };
    if json {
        println!("{}", serde_json::to_string_pretty(&project)?);
        return Ok(());
    }
    println!("{}", project.name);
    match project.kind {
        db::Kind::Repo => {
            println!("  path:    {}", project.path);
            println!("  remote:  {}", project.remote.as_deref().unwrap_or("none"));
        }
        db::Kind::Service => println!("  kind:    a place the record keeps for itself; no repository"),
    }
    println!("  since:   {}", project.created_at);
    if let Some(gate) = &project.gate {
        println!("  gate:    {gate}");
    }
    Ok(())
}

/// Sets what the record keeps about a project, beyond what git can tell it.
///
/// The gate is the first of these: the command CI runs, so that "green
/// before a commit" has one spelling per project instead of a copy in the
/// skill file, the README and whatever an assistant remembers.
fn project_set(name: &str, gate: Option<&str>, no_gate: bool, on_session_end: Option<&str>, no_on_session_end: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, name)?;

    if !no_gate && gate.is_none() && !no_on_session_end && on_session_end.is_none() {
        // Nothing asked for is a question, not a no-op: a command that
        // silently did nothing would look like it had worked.
        match &project.gate {
            Some(gate) => println!("{}: gate is `{gate}`", project.name),
            None => println!("{} has no gate; set one with --gate \"<command>\"", project.name),
        }
        match &project.on_session_end {
            Some(hook) => println!("{}: a closing session runs `{hook}`", project.name),
            None => println!(
                "{} runs nothing when a session closes; set it with --on-session-end \"<command>\"",
                project.name
            ),
        }
        return Ok(());
    }

    if no_gate {
        db.set_gate(project.id, None)?;
        println!("{} has no gate now.", project.name);
    } else if let Some(gate) = gate {
        let gate = gate.trim();
        if gate.is_empty() {
            bail!("an empty gate is not a gate; use --no-gate to take it off");
        }
        db.set_gate(project.id, Some(gate))?;
        println!("{}: gate is `{gate}`", project.name);
        println!("Run it with: rigger gate {}", project.name);
    }

    if no_on_session_end {
        db.set_on_session_end(project.id, None)?;
        println!("{} runs nothing when a session closes now.", project.name);
    } else if let Some(hook) = on_session_end {
        let hook = hook.trim();
        if hook.is_empty() {
            bail!("an empty command is not a command; use --no-on-session-end to take it off");
        }
        db.set_on_session_end(project.id, Some(hook))?;
        println!("{}: a closing session runs `{hook}`", project.name);
        println!("It runs after the sitting is written down, and its outcome is recorded.");
    }
    Ok(())
}

/// Runs a project's gate and records how it went.
///
/// Exits non-zero when the gate is red, so that it composes: a hook, a
/// script, or a shell can act on it without reading the text. The output of
/// the gate goes straight to the terminal, because a gate is watched while
/// it runs; what the record keeps is the verdict and how long it took.
fn gate(project: Option<&str>, check: bool, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = project_here(&db, project)?;
    let Some(command) = project.gate.clone() else {
        bail!(
            "{} has no gate. Set it to what CI runs:
  rigger project set {} --gate \"cargo fmt --all --check && cargo clippy --all-targets -- -D warnings && cargo test\"",
            project.name,
            project.name
        );
    };

    let dir = Path::new(&project.path);
    if !dir.is_dir() {
        bail!("{} is recorded at {}, which is not there", project.name, project.path);
    }

    if check {
        println!("{} would run, in {}:", project.name, project.path);
        println!("  {command}");
        return Ok(());
    }

    let run = gate::run(&command, dir).with_context(|| format!("cannot run the gate of {}", project.name))?;
    let body = run.event_body(&command);
    db.record_event(project.id, "gate", &body, &db::now(), "assistant")?;

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "project": project.name,
                "command": command,
                "passed": run.passed(),
                "exit_code": run.code,
                "seconds": run.seconds,
            }))?
        );
    } else {
        println!();
        println!("{}: {body}", project.name);
    }

    if !run.passed() {
        // Said by the exit code rather than by an error, because the gate has
        // already printed why it is red and an anyhow message on top would
        // bury it under a second account of the same failure.
        std::process::exit(1);
    }
    Ok(())
}

/// Records how a product looks from outside.
fn project_mark(
    name: &str,
    code: Option<&str>,
    accent: Option<&str>,
    accent2: Option<&str>,
    form: Option<&str>,
    docs: Option<&str>,
    clear: bool,
) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, name)?;

    if clear {
        db.set_mark(project.id, &db::Mark::default())?;
        println!("{} has no mark recorded now.", project.name);
        return Ok(());
    }

    if code.is_none() && accent.is_none() && accent2.is_none() && form.is_none() && docs.is_none() {
        // Nothing asked for is a question, not a no-op.
        match (&project.mark_code, &project.accent) {
            (None, None) => println!("{} has no mark recorded; `--code` and `--accent` start one", project.name),
            _ => {
                println!("{}:", project.name);
                for (label, value) in [
                    ("code", &project.mark_code),
                    ("accent", &project.accent),
                    ("accent 2", &project.accent2),
                    ("form", &project.form),
                    ("docs", &project.docs_url),
                ] {
                    if let Some(value) = value {
                        println!("  {label:<8} {value}");
                    }
                }
            }
        }
        return Ok(());
    }

    // What was given is checked before anything is written, so a command
    // that refuses one field does not leave the other four changed.
    if let Some(code) = code {
        line::check_code(code)?;
    }
    for accent in [accent, accent2].into_iter().flatten() {
        line::check_accent(accent)?;
    }
    if let Some(form) = form {
        line::check_form(form)?;
    }

    // What is not named keeps what it had: `--form cli` states the form,
    // not the whole mark. `--clear` is how a mark is taken off.
    let mark = db::Mark {
        code: code.map(str::to_string).or(project.mark_code),
        accent: accent.map(str::to_string).or(project.accent),
        accent2: accent2.map(str::to_string).or(project.accent2),
        form: form.map(str::to_string).or(project.form),
        docs_url: docs.map(str::to_string).or(project.docs_url),
    };
    db.set_mark(project.id, &mark)
        .with_context(|| format!("cannot record the mark of {}", project.name))?;
    println!("{}: mark recorded.", project.name);
    for (label, value) in [
        ("code", &mark.code),
        ("accent", &mark.accent),
        ("accent 2", &mark.accent2),
        ("form", &mark.form),
        ("docs", &mark.docs_url),
    ] {
        if let Some(value) = value {
            println!("  {label:<8} {value}");
        }
    }
    Ok(())
}

/// Writes the line's public registry.
fn export_line(to: Option<&Path>, check: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let registry = line::build(&db, |p| repo::detect_about(Path::new(&p.path)))?;
    // Before the file is written, every time. The one mistake this command
    // can make is publishing something private, and that one cannot be
    // taken back.
    line::check_public(&registry)?;
    let json = format!(
        "{}
",
        serde_json::to_string_pretty(&registry)?
    );

    let Some(path) = to else {
        print!("{json}");
        return Ok(());
    };
    let before = std::fs::read_to_string(path).unwrap_or_default();
    if before == json {
        println!("{} is already what the record says.", path.display());
        return Ok(());
    }
    if check {
        println!("{} would change: {} products", path.display(), registry.products.len());
        return Ok(());
    }
    if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
        std::fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
    }
    std::fs::write(path, &json).with_context(|| format!("cannot write {}", path.display()))?;
    let what = if before.is_empty() { "Wrote" } else { "Rewrote" };
    println!("{what} {} - {} products", path.display(), registry.products.len());
    Ok(())
}

fn project_tier(name: &str, tier: &str, rhythm: Option<u32>) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, name)?;
    let tier = calendar::Tier::parse(tier)?;
    // A tier carries a rhythm of its own, so setting one is a single word
    // in the common case; `--rhythm` is for the project that keeps its
    // tier's company but not its pace.
    let rhythm = match rhythm {
        Some(0) => bail!("a rhythm of 0 weeks is not a rhythm; leave it out to use the tier's"),
        Some(weeks) => Some(weeks),
        None => tier.default_rhythm(),
    };
    db.set_tier(project.id, tier.as_str(), rhythm)?;

    println!("{} is tier {tier} - {}", project.name, tier.describe());
    match rhythm {
        Some(weeks) => println!("  a release every {}", plural(weeks as usize, "week", "weeks")),
        None => println!("  no rhythm to keep"),
    }
    Ok(())
}

fn version_plan(project: &str, version: &str, week: Option<&str>, clear: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    if week.is_none() && !clear {
        bail!("say which week with --week 2026-W37, or --clear to take it off the calendar");
    }
    let week = week.map(calendar::Week::parse).transpose()?;
    let stored = week.map(|w| w.to_string());
    let change = db.set_planned_week(project.id, version, stored.as_deref())?;

    match (week, change) {
        (_, db::Change::Unchanged) => println!("{version} was already there; nothing changed"),
        (Some(week), _) => println!("{version} is aimed at {week} - the week of {}", week.friday()),
        (None, _) => println!("{version} is off the calendar"),
    }
    Ok(())
}

/// The grid: weeks across, projects down.
fn show_calendar(weeks: u32, from: Option<&str>, json: bool) -> Result<()> {
    if weeks == 0 {
        bail!("a calendar of 0 weeks shows nothing; ask for at least one");
    }
    let db = Db::open(&paths::db_path()?)?;
    let now = calendar::Week::current();
    let from = match from {
        Some(text) => calendar::Week::parse(text)?,
        None => now,
    };

    let mut rows = Vec::new();
    let mut all = Vec::new();
    for project in db.projects()? {
        let versions = db.calendar_versions(project.id, &project.name)?;
        let tier = project.tier.as_deref().and_then(|t| calendar::Tier::parse(t).ok());
        let row = calendar::row(&project.name, tier, project.rhythm_weeks, &versions, from, weeks, now);
        if !row.cells.is_empty() {
            rows.push(row);
        }
        all.push((project.name.clone(), versions));
    }

    let span: Vec<calendar::Week> = (0..weeks).map(|n| from.plus(i64::from(n))).collect();

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "now": now,
                "weeks": span,
                "projects": rows,
            }))?
        );
        return Ok(());
    }

    if rows.is_empty() {
        println!("Nothing is on the calendar for these {}.", plural(weeks as usize, "week", "weeks"));
        println!("Aim a version at a week with: rigger version plan <project> <version> --week 2026-W37");
        return Ok(());
    }

    // Each column is as wide as the widest thing in it, so a week holding
    // two releases does not push the rest of the grid out of line.
    let name_width = rows.iter().map(|r| r.project.chars().count()).max().unwrap_or(0).max(7);
    let widths: Vec<usize> = span
        .iter()
        .map(|week| {
            rows.iter()
                .map(|row| cell_text(row, *week).chars().count())
                .max()
                .unwrap_or(0)
                // The heading needs room too, and this week's carries a mark.
                .max(week.to_string().chars().count() + usize::from(*week == now))
        })
        .collect();

    print!("{:name_width$}", "");
    for (week, width) in span.iter().zip(&widths) {
        // This week is marked in the heading, because a grid read on a
        // Wednesday is read from where the reader stands.
        let heading = if *week == now { format!("{week}*") } else { week.to_string() };
        print!("  {heading:width$}");
    }
    println!();

    for row in &rows {
        print!("{:name_width$}", row.project);
        for (week, width) in span.iter().zip(&widths) {
            print!("  {:width$}", cell_text(row, *week));
        }
        if let Some(tier) = row.tier {
            print!("   {tier}");
        }
        println!();
    }

    println!();
    println!(
        "{} shipped as planned   {} slipped   {} overdue   {} unplanned   {} planned",
        calendar::Standing::Shipped.mark(),
        calendar::Standing::Slipped.mark(),
        calendar::Standing::Overdue.mark(),
        calendar::Standing::Unplanned.mark(),
        calendar::Standing::Planned.mark(),
    );

    // Slippage, spelt out. The grid shows that a release moved; only a
    // number says how far, and that is what a retrospective needs.
    let mut late: Vec<String> = Vec::new();
    for row in &rows {
        let Some((_, versions)) = all.iter().find(|(name, _)| *name == row.project) else {
            continue;
        };
        for cell in &row.cells {
            if !matches!(cell.standing, calendar::Standing::Slipped | calendar::Standing::Overdue) {
                continue;
            }
            let Some(version) = versions.iter().find(|v| v.version == cell.version) else {
                continue;
            };
            let Some(weeks) = version.slip().or_else(|| version.overdue(now)) else {
                continue;
            };
            let aimed = version.planned.map(|w| w.to_string()).unwrap_or_default();
            late.push(format!(
                "{:name_width$}  {} — aimed at {aimed}, {}",
                row.project,
                cell.version,
                weeks_late(weeks)
            ));
        }
    }
    if !late.is_empty() {
        println!();
        for line in &late {
            println!("{line}");
        }
    }
    Ok(())
}

/// What one cell of the grid says.
///
/// Two releases in a week are named; more than two are counted. The real
/// record made this necessary rather than tidy: one week of one project
/// holds forty-six releases, and naming them all stretched the column past
/// three hundred characters, wrapped every row and pushed the heading out
/// of line - a grid that could not be read at all. The count keeps the
/// shape, and `why` is where the names belong anyway.
fn cell_text(row: &calendar::Row, week: calendar::Week) -> String {
    let cells: Vec<&calendar::Cell> = row.cells.iter().filter(|cell| cell.week == week).collect();
    let named = |cell: &calendar::Cell| format!("{}{}", cell.standing.mark(), cell.version);
    match cells.len() {
        0 => String::new(),
        1..=2 => cells.iter().map(|c| named(c)).collect::<Vec<_>>().join(" "),
        n => {
            // The first and last say what the run spans; the mark is the
            // worst standing in it, so a slipped release inside a busy week
            // is not hidden by the ones around it.
            let worst = cells
                .iter()
                .map(|c| c.standing)
                .max_by_key(|s| severity(*s))
                .unwrap_or(calendar::Standing::Shipped);
            format!(
                "{}{}..{} ({n})",
                worst.mark(),
                cells.first().map(|c| c.version.as_str()).unwrap_or(""),
                cells.last().map(|c| c.version.as_str()).unwrap_or("")
            )
        }
    }
}

/// How much a standing wants to be seen when a cell can only show one.
fn severity(standing: calendar::Standing) -> u8 {
    match standing {
        calendar::Standing::Overdue => 4,
        calendar::Standing::Slipped => 3,
        calendar::Standing::Planned => 2,
        calendar::Standing::Unplanned => 1,
        calendar::Standing::Shipped => 0,
    }
}

fn weeks_late(weeks: i64) -> String {
    match weeks {
        1 => "a week late".to_string(),
        n if n < 0 => format!("{} early", plural(n.unsigned_abs() as usize, "week", "weeks")),
        n => format!("{} late", plural(n as usize, "week", "weeks")),
    }
}

/// Everything the week screens read, gathered once.
///
/// `next`, `week` and `release-day` are three views of one week, and the
/// awkward part is not any of the three but keeping them agreed: a version
/// counted as the focus by one and as shipped by another would make the
/// screens argue with each other in front of the owner.
struct WeekFacts {
    focus: Vec<calendar::Focus>,
    overdue: Vec<calendar::Focus>,
    lapsed: Vec<calendar::Overdue>,
    signals: Vec<week::Raised>,
    /// Pairs whose halves have parted company. Read here rather than on
    /// demand because a pair belongs to no single project, and every screen
    /// that asks one project at a time is the reason the drift went unseen.
    parted: Vec<link::Parted>,
    release_day: week::ReleaseDay,
}

fn week_facts(db: &Db, now: calendar::Week) -> Result<WeekFacts> {
    let mut focus = Vec::new();
    let mut overdue = Vec::new();
    let mut rhythms = Vec::new();
    let mut standings = Vec::new();
    let mut all_versions = Vec::new();

    for project in db.projects()? {
        let versions = db.calendar_versions(project.id, &project.name)?;
        let tier = project.tier.as_deref().and_then(|t| calendar::Tier::parse(t).ok());

        for version in &versions {
            if version.planned == Some(now) && version.shipped.is_none() {
                focus.push(calendar::Focus {
                    project: project.name.clone(),
                    tier,
                    version: version.version.clone(),
                    title: version.title.clone(),
                    planned: now,
                    overdue_weeks: None,
                });
            } else if let Some(weeks) = version.overdue(now) {
                overdue.push(calendar::Focus {
                    project: project.name.clone(),
                    tier,
                    version: version.version.clone(),
                    title: version.title.clone(),
                    planned: version.planned.unwrap_or(now),
                    overdue_weeks: Some(weeks),
                });
            }
        }

        let last_shipped = versions
            .iter()
            .filter_map(|v| v.shipped.map(|week| (db::version_order(&v.version), week)))
            .max()
            .map(|(_, week)| week);

        // The rhythm check needs a tier and a number to check against; a
        // project with neither is out of the rotation by omission.
        if let (Some(tier), Some(rhythm)) = (tier, project.rhythm_weeks)
            && tier != calendar::Tier::Out
        {
            rhythms.push((project.name.clone(), tier, rhythm, last_shipped));
        }

        if let Some(tier) = tier {
            // A turn in the focus leaves a mark whether or not it ends in a
            // tag: the last commit and the last note both count, because a
            // week spent on a product that shipped nothing was still spent.
            let touched = [db.last_event_at(project.id)?, db.activity(project.id)?.and_then(|a| a.last_commit_at)]
                .into_iter()
                .flatten()
                .filter_map(|stamp| calendar::Week::of_recorded(&stamp))
                .max();
            standings.push(week::Standing {
                project: project.name.clone(),
                tier,
                rhythm_weeks: project.rhythm_weeks,
                last_shipped,
                last_touched: touched,
                has_first_release: last_shipped.is_some(),
            });
        }

        all_versions.extend(versions);
    }

    focus.sort_by(|a, b| a.tier.cmp(&b.tier).then_with(|| a.project.cmp(&b.project)));
    overdue.sort_by(|a, b| b.overdue_weeks.cmp(&a.overdue_weeks).then_with(|| a.project.cmp(&b.project)));

    Ok(WeekFacts {
        focus,
        overdue,
        lapsed: calendar::lapsed(&rhythms, now),
        signals: week::signals(&standings, now),
        parted: link::parted(&db.pairs()?),
        release_day: week::release_day(now, &all_versions),
    })
}

/// Reads a week from the flag, or takes the current one.
fn week_or_now(week: Option<&str>) -> Result<calendar::Week> {
    match week {
        Some(text) => calendar::Week::parse(text),
        None => Ok(calendar::Week::current()),
    }
}

/// The focus of a week: what is aimed at it, and what should have shipped
/// before it.
fn show_next(week_arg: Option<&str>, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let now = week_or_now(week_arg)?;
    let WeekFacts {
        focus,
        overdue,
        lapsed,
        signals,
        parted,
        ..
    } = week_facts(&db, now)?;

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "week": now,
                "friday": now.friday().to_string(),
                "focus": focus,
                "overdue": overdue,
                "lapsed": lapsed,
                "signals": signals,
                "parted": parted,
            }))?
        );
        return Ok(());
    }

    println!("{now} — releases on {}", now.friday());
    println!();

    if focus.is_empty() {
        println!("Nothing is aimed at this week.");
    } else {
        for item in &focus {
            let tier = item.tier.map(|t| format!(" [{t}]")).unwrap_or_default();
            let title = item.title.as_deref().map(|t| format!(" · {t}")).unwrap_or_default();
            println!("{}{tier}  {}{title}", item.project, item.version);
        }
    }

    if !overdue.is_empty() {
        println!();
        println!("Past their week:");
        for item in &overdue {
            let weeks = item.overdue_weeks.unwrap_or_default();
            let ago = if weeks == 1 {
                "a week ago".to_string()
            } else {
                format!("{} ago", plural(weeks.max(0) as usize, "week", "weeks"))
            };
            println!("{}  {} — was due {} ({ago})", item.project, item.version, item.planned);
        }
    }

    // A project that has kept no rhythm is not late for a week, it is late
    // for its tier - the failure the written calendar could never see,
    // because nothing ever compared the rotation to the tags.
    if !lapsed.is_empty() {
        println!();
        println!("Behind their rhythm:");
        for item in &lapsed {
            let since = match item.since {
                Some(week) => format!("last shipped {week}"),
                None => "never shipped".to_string(),
            };
            println!(
                "{} [{}]  {since}, {} without a release, rhythm is {}",
                item.project,
                item.tier,
                plural(item.weeks.max(0) as usize, "week", "weeks"),
                plural(item.rhythm_weeks as usize, "week", "weeks")
            );
        }
    }

    print_signals(&signals);
    print_parted(&parted);
    Ok(())
}

/// The minimums each tier promised, and which of them are being broken.
///
/// Separate from the rhythm lapse above on purpose: a rhythm is a pace and
/// this is a floor. A carrying product is allowed to miss one cycle, so the
/// lapse fires first and the signal only when the allowance is spent.
/// One signal as a line of prose, for a screen that has room for one.
fn signal_line(item: &week::Raised) -> String {
    let weeks = item.weeks.map(|w| plural(w.max(0) as usize, "week", "weeks")).unwrap_or_default();
    match item.signal {
        week::Signal::MissedCycle => format!("tier {} asks for more: more than one cycle missed - {weeks} without a release", item.tier),
        week::Signal::WithoutFocus => format!("tier {} asks for more: no turn in the focus for {weeks}", item.tier),
        week::Signal::SecondStart => match item.alongside.as_deref() {
            Some(first) => format!("tier {} asks for more: started before {first} shipped anything", item.tier),
            None => format!("tier {} asks for more: started out of turn", item.tier),
        },
    }
}

/// The pairs that have parted, under a heading of their own.
///
/// Not folded into the tier signals, though both are warnings: a tier
/// signal is about one project going too slowly, and this is about two
/// projects that stopped agreeing. The answer to one is a week of work;
/// the answer to the other is usually a release of the half left behind.
fn print_parted(parted: &[link::Parted]) {
    if parted.is_empty() {
        return;
    }
    println!();
    println!("Pairs out of step");
    for item in parted {
        println!("  {}", drift_line(item));
    }
}

fn print_signals(signals: &[week::Raised]) {
    if signals.is_empty() {
        return;
    }
    println!();
    println!("Their tier asks for more:");
    for item in signals {
        // Worded once, in `signal_line`, and read here with the heading's
        // own phrase removed. The calendar legend taught this at v0.10.0:
        // two places spelling one fact drift, and the test that compared
        // them is what found it.
        let said = signal_line(item).replacen(&format!("tier {} asks for more: ", item.tier), "", 1);
        println!("{} [{}]  {said}", item.project, item.tier);
    }
}

/// The Monday brief: one screen the week opens on.
///
/// The three things it answers are the three the owner otherwise asks by
/// hand on a Monday morning, from three different places: what am I meant
/// to be working on, what goes out on Friday, and what is waiting on me.
/// None of them is new - the brief is that they arrive together, before the
/// week is spent rather than after.
fn show_week(week_arg: Option<&str>, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let now = week_or_now(week_arg)?;
    let facts = week_facts(&db, now)?;
    let waiting = db.open_questions()?;
    let shared = owner::shared_subjects(&waiting);

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "week": now,
                "monday": now.monday().to_string(),
                "friday": now.friday().to_string(),
                "focus": facts.focus,
                "overdue": facts.overdue,
                "shipping": facts.release_day.queued,
                "shipped": facts.release_day.shipped,
                "waiting": waiting,
                "shared": shared,
                "lapsed": facts.lapsed,
                "signals": facts.signals,
                "parted": facts.parted,
            }))?
        );
        return Ok(());
    }

    println!("{now} — {} to {}", now.monday(), now.friday());
    println!();

    println!("Focus");
    if facts.focus.is_empty() {
        println!("  nothing is aimed at this week");
    } else {
        for item in &facts.focus {
            let tier = item.tier.map(|t| format!(" [{t}]")).unwrap_or_default();
            let title = item.title.as_deref().map(|t| format!(" · {t}")).unwrap_or_default();
            println!("  {}{tier}  {}{title}", item.project, item.version);
        }
    }

    println!();
    println!("Ships on {}", now.friday());
    if facts.release_day.queued.is_empty() && facts.release_day.shipped.is_empty() {
        println!("  nothing is queued");
    } else {
        for item in &facts.release_day.queued {
            let title = item.title.as_deref().map(|t| format!(" · {t}")).unwrap_or_default();
            println!("  {}  {}{title}", item.project, item.version);
        }
        // What has already gone out is part of the same answer: the week has
        // one slot on the shopfront, and a week that has spent it has
        // nothing left to ship however full the queue behind it looks.
        let out = facts.release_day.shipped.len();
        if out > 0 {
            let over = facts.release_day.over_the_slot();
            let spent = if over > 0 {
                format!("  {} already out — {} past this week's one slot", plural(out, "release", "releases"), over)
            } else {
                format!("  {} already out — this week's slot is spent", plural(out, "release", "releases"))
            };
            println!("{spent}");
            println!("  see the queue with: rigger release-day");
        }
    }

    println!();
    println!("Waiting on you");
    if waiting.is_empty() {
        println!("  nothing");
    } else {
        let projects: std::collections::BTreeSet<&str> = waiting.iter().map(|q| q.project.as_str()).collect();
        println!(
            "  {} in {}",
            plural(waiting.len(), "question", "questions"),
            plural(projects.len(), "project", "projects")
        );
        // The groups are what makes the queue smaller than it looks, so they
        // are the part worth naming on a screen that is meant to be short.
        for group in shared.iter().take(3) {
            println!("  {} — {}", group.subject, group.projects.join(", "));
        }
        println!("  see them with: rigger inbox");
    }

    if !facts.overdue.is_empty() {
        println!();
        println!("Past their week:");
        for item in &facts.overdue {
            println!("  {}  {} — was due {}", item.project, item.version, item.planned);
        }
    }

    print_signals(&facts.signals);
    print_parted(&facts.parted);
    Ok(())
}

/// The shopfront queue: what a week has already put out, and what is due.
///
/// The rule this reads against is the one the written calendar set for the
/// outside view: one release a week, on a Friday, and a version ready on a
/// Tuesday waits rather than going out on top of the last one. The reason
/// is not tidiness - two releases in a day read as one burst to anyone
/// watching, and two in different weeks read as a rhythm. The trace is what
/// is meant to be even, not the work.
fn show_release_day(week_arg: Option<&str>, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let now = week_or_now(week_arg)?;
    let day = week_facts(&db, now)?.release_day;

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "week": day.week,
                "friday": day.friday,
                "shipped": day.shipped,
                "queued": day.queued,
                "early": day.early(),
                "over_the_slot": day.over_the_slot(),
            }))?
        );
        return Ok(());
    }

    println!("{now} — releases on {}", day.friday);
    println!();

    if day.queued.is_empty() {
        println!("Nothing is waiting for Friday.");
    } else {
        println!("Waiting for Friday:");
        for item in &day.queued {
            let title = item.title.as_deref().map(|t| format!(" · {t}")).unwrap_or_default();
            println!("  {}  {}{title}", item.project, item.version);
        }
    }

    // Folded by day, because the day is what the rule is about and because
    // a real week of this line holds ninety-four releases: a line each puts
    // the two numbers that answer the question below the fold, where the
    // calendar grid learnt the same lesson at v0.10.0.
    let days = day.days();
    if !days.is_empty() {
        println!();
        println!("Already out this week:");
        for entry in &days {
            let mark = if entry.on_release_day { "Friday" } else { "early" };
            let named: Vec<String> = entry.projects.iter().map(|p| format!("{} {}", p.project, p.summary())).collect();
            println!("  {}  {:<6}  {:>2}  {}", entry.day, mark, entry.releases, named.join(", "));
        }
    }

    // The two numbers say which half of the rule is being broken: going out
    // before Friday, and going out more than once in a week. They are said
    // as counts rather than as complaints - the record reports, and what to
    // do about it is the owner's.
    let early = day.early();
    let over = day.over_the_slot();
    if early > 0 || over > 0 {
        println!();
        if over > 0 {
            println!("{} past the one release this week has room for", plural(over, "release", "releases"));
        }
        if early > 0 {
            println!("{} went out before Friday", plural(early, "release", "releases"));
        }
    }
    Ok(())
}

/// The look back: what the plan said, what the tags say, and where the two
/// parted company.
///
/// The written calendar asked for this every seven weeks and had no way to
/// do it, because nothing there ever read a tag - so the check was a thing
/// to remember, and a thing to remember is a thing that stops happening.
fn show_retro(cycle: bool, weeks: Option<u32>, to: Option<&str>, record: bool, json: bool) -> Result<()> {
    let span = match (cycle, weeks) {
        (true, _) => retro::CYCLE_WEEKS,
        (_, Some(0)) => bail!("a retro of 0 weeks looks back at nothing; ask for at least one"),
        (_, Some(n)) => n,
        // Four weeks by default: long enough to hold more than one release
        // of a tier A product, short enough that a Monday can read it.
        (false, None) => 4,
    };
    let db = Db::open(&paths::db_path()?)?;
    let to = week_or_now(to)?;
    let from = to.plus(-i64::from(span - 1));

    let mut versions = Vec::new();
    let mut projects = Vec::new();
    for project in db.projects()? {
        versions.extend(db.calendar_versions(project.id, &project.name)?);
        let tier = project.tier.as_deref().and_then(|t| calendar::Tier::parse(t).ok());
        projects.push((project.name.clone(), tier, project.rhythm_weeks));
    }
    let looked = retro::look_back(from, to, &versions, &projects);
    let summary = retro::summary(&looked);
    // Read as the window's state, not as something that happened inside
    // it: a pair parts by one half being released, and the release is
    // already in the list above. What a look back adds is the question the
    // list cannot ask - are they still parted now.
    let parted = link::parted(&db.pairs()?);

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "from": looked.from,
                "to": looked.to,
                "weeks": looked.weeks(),
                "shipped": looked.shipped,
                "missed": looked.missed,
                "standings": looked.standings,
                "on_time": looked.on_time(),
                "slipped": looked.slipped(),
                "unplanned": looked.unplanned(),
                "planned_share": looked.planned_share(),
                "parted": parted,
                "summary": summary,
            }))?
        );
        return Ok(());
    }

    println!("{} to {} — {}", looked.from, looked.to, plural(looked.weeks().max(0) as usize, "week", "weeks"));
    println!();

    if looked.shipped.is_empty() && looked.missed.is_empty() {
        println!("Nothing shipped and nothing was aimed at these weeks.");
        // A window where nothing happened is a real answer, but it is not
        // one worth filing: a retro is kept so a later one can find what
        // was concluded, and "nothing" concludes nothing.
        if record {
            println!();
            println!("Nothing to keep.");
        }
        return Ok(());
    }

    // The three numbers the check is read for, and the share underneath
    // them: how much of what shipped was ever planned. A line where nothing
    // was planned has a calendar in name only, and that is worth saying.
    println!(
        "{} shipped — {} on time, {} slipped, {} unplanned",
        looked.shipped.len(),
        looked.on_time(),
        looked.slipped(),
        looked.unplanned()
    );
    if let Some(share) = looked.planned_share() {
        println!("{share}% of what shipped had been planned");
    }

    if !looked.missed.is_empty() {
        println!();
        println!("Planned and not shipped:");
        for item in &looked.missed {
            println!(
                "  {}  {} — was due {} ({} by the end of the window)",
                item.project,
                item.version,
                item.planned,
                weeks_late(item.weeks)
            );
        }
    }

    // Slippage spelt out, worst first: the grid shows that a release moved,
    // only a number says how far, and "what turned out dearer" was one of
    // the three questions the written calendar asked.
    let mut slipped: Vec<&retro::Shipped> = looked.shipped.iter().filter(|s| s.slip.is_some_and(|n| n != 0)).collect();
    slipped.sort_by_key(|s| std::cmp::Reverse(s.slip));
    if !slipped.is_empty() {
        println!();
        println!("Shipped, but not when it was aimed:");
        for item in slipped.iter().take(10) {
            let aimed = item.planned.map(|w| w.to_string()).unwrap_or_default();
            println!(
                "  {}  {} — aimed at {aimed}, out in {} ({})",
                item.project,
                item.version,
                item.week,
                weeks_late(item.slip.unwrap_or(0))
            );
        }
        if slipped.len() > 10 {
            println!("  ... and {} more", slipped.len() - 10);
        }
    }

    print_parted(&parted);

    if !looked.standings.is_empty() {
        println!();
        println!("Per project:");
        let width = looked.standings.iter().map(|s| s.project.chars().count()).max().unwrap_or(0);
        for item in &looked.standings {
            let tier = item.tier.map(|t| format!("[{t}]")).unwrap_or_else(|| "   ".to_string());
            let asked = match item.expected {
                Some(n) => format!("{n} asked"),
                None => "none asked".to_string(),
            };
            let missed = if item.missed > 0 {
                format!(", {} missed", item.missed)
            } else {
                String::new()
            };
            println!(
                "  {:width$} {tier}  {} shipped ({} planned), {asked}{missed}",
                item.project, item.shipped, item.planned_and_shipped
            );
        }
    }

    // "Do the tiers need moving" was the third question the calendar asked.
    // The two directions are shown apart because they are different
    // problems: a product shipping twenty times its tier has outgrown it,
    // one shipping nothing is stalled, and a single list of "misfits" loses
    // exactly the distinction worth acting on.
    let stalled = looked.misfits(retro::Misfit::Stalled);
    let outgrown = looked.misfits(retro::Misfit::Outgrown);
    if !stalled.is_empty() {
        println!();
        println!("Nothing shipped, and their tier asked for something:");
        for item in &stalled {
            let tier = item.tier.map(|t| t.to_string()).unwrap_or_default();
            println!("  {} [{tier}]  0 against {} asked for", item.project, item.expected.unwrap_or(0));
        }
    }
    if !outgrown.is_empty() {
        println!();
        println!("Shipping past their tier — it may be describing the wrong thing now:");
        for item in outgrown.iter().take(5) {
            let tier = item.tier.map(|t| t.to_string()).unwrap_or_default();
            let over = item.times_over().unwrap_or(0);
            println!(
                "  {} [{tier}]  {} shipped against {} asked for ({over}x)",
                item.project,
                item.shipped,
                item.expected.unwrap_or(0)
            );
        }
        if outgrown.len() > 5 {
            println!("  ... and {} more", outgrown.len() - 5);
        }
    }
    if !stalled.is_empty() || !outgrown.is_empty() {
        println!("  move one with: rigger project tier <project> <A|B|C|out>");
    }

    println!();
    if record {
        record_retro(&db, &looked, &summary)?;
    } else {
        println!("Keep this in the record with: rigger retro --record");
    }
    Ok(())
}

/// Writes the retro's summary into the record.
///
/// It goes to the project the record keeps for itself rather than to any of
/// the projects looked at: the summary is about all of them, and filing it
/// under one would make it findable from the wrong place and invisible from
/// the rest. A retro that is only ever printed leaves the same hole the
/// written calendar had, where the check happened and nothing afterwards
/// could tell that it did.
fn record_retro(db: &Db, looked: &retro::Retro, summary: &str) -> Result<()> {
    let Some(project) = db.service_project()? else {
        bail!(
            "no place to keep it: a retro is about every project, so its summary belongs to none of them.
Make one with: rigger project service line"
        );
    };
    // Dated by the window it looked at, not by the moment it was run. The
    // same retro of the same weeks is the same fact however often it is
    // asked for, and stamping it with "now" filed a fresh copy every time -
    // which is how a record fills with restatements of one conclusion.
    let at = format!("{}T00:00:00Z", looked.to.friday());
    let change = db.record_event(project.id, "change", summary, &at, "assistant")?;
    match change {
        db::Change::Unchanged => println!("That retro is already in the record, under '{}'.", project.name),
        _ => println!("Kept in the record under '{}'.", project.name),
    }
    Ok(())
}

/// The reminder a red gate leaves, if the last run of one was red.
///
/// Read from the last gate event rather than from a flag on the project: a
/// flag would have to be cleared by whoever fixed the gate, and the thing
/// nobody does is clear a flag. The record already holds every run, so the
/// last one is the answer.
///
/// Only this sitting's own runs count, and "this sitting" is the session
/// id, not a moment in time. A gate that went red a week ago and was never
/// run again says nothing about this sitting, and a reminder that fires for
/// ever is a reminder that gets ignored.
/// What a project's closing command came to.
#[derive(Debug, serde::Serialize)]
struct HookRun {
    command: String,
    verdict: String,
    passed: bool,
}

/// Runs the command a project says a closing sitting should run.
///
/// A red result does not fail the close. The session is already over and
/// already written down; refusing to end it would leave the record with a
/// sitting open for ever because a publish step could not reach the
/// network. So the outcome is recorded and said out loud, and the session
/// closes either way - visible, not fatal.
///
/// Recorded as a change, because that is what it is: something happened
/// outside the record because a session ended.
fn run_session_hook(db: &Db, project: &db::Project) -> Result<Option<HookRun>> {
    let Some(command) = project.on_session_end.clone() else {
        return Ok(None);
    };
    let dir = Path::new(&project.path);
    if !dir.is_dir() {
        // A project whose directory has moved is not a reason to fail a
        // close; saying so beats a shell error nobody can place.
        eprintln!("{} is not a directory, so `{command}` was not run", project.path);
        return Ok(None);
    }
    eprintln!("Running the end-of-session command: {command}");
    let run = match gate::run(&command, dir) {
        Ok(run) => run,
        Err(e) => {
            eprintln!("cannot run `{command}`: {e}");
            return Ok(None);
        }
    };
    let verdict = run.event_body(&command);
    // Stamped at the moment it finished, not with the day: two runs on one
    // day that came back the same would otherwise be one row, and the
    // second - the one that says the publish worked on the retry - would
    // vanish into the first.
    db.record_event(project.id, "change", &format!("end of session: {verdict}"), &db::now(), "rigger")?;
    Ok(Some(HookRun {
        command,
        passed: run.passed(),
        verdict,
    }))
}

fn red_gate_reminder(db: &Db, project: &db::Project, session: i64) -> Result<Option<String>> {
    let Some(last) = db.last_gate_in_session(session)? else {
        return Ok(None);
    };
    if gate::body_is_green(&last.body) {
        return Ok(None);
    }
    Ok(Some(format!(
        "the gate was last {} - `rigger gate {}` to run it again",
        last.body, project.name
    )))
}

/// Opens a sitting. Everything recorded until `end` belongs to it.
fn session_start(project: Option<&str>, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = project_here(&db, project)?;
    let (session, change) = db.start_session(project.id, &db::now())?;

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({ "session": session, "already_open": change == db::Change::Unchanged }))?
        );
        return Ok(());
    }
    match change {
        // Joining rather than splitting: an assistant that lost its place,
        // or a hook that fired twice, should not orphan half a sitting.
        db::Change::Unchanged => println!("A session on {} is already open, since {}.", project.name, session.started_at),
        _ => println!("Session open on {}. Everything recorded now belongs to it.", project.name),
    }
    Ok(())
}

/// Closes the sitting and says what it held.
///
/// This is the end-of-session ritual, which has always been a list in a
/// skill file that the assistant had to remember at exactly the moment it
/// was running out of context. A ritual that depends on remembering is a
/// ritual that stops happening.
fn session_end(project: Option<&str>, heading: Option<&str>, diary: Option<&Path>, remind: bool, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    // A hook has no name to pass, so a failure to find one is not a failure
    // worth reporting: it fires in every directory, most of which are not
    // projects. Ending silently is the only behaviour that does not turn
    // every unrelated session into an error message.
    let project = match (project_here(&db, project), remind) {
        (Ok(project), _) => project,
        (Err(_), true) => return Ok(()),
        (Err(e), false) => return Err(e),
    };

    let Some(open) = db.open_session(project.id)? else {
        // A hook fires whether or not a session was opened, so having none
        // is ordinary and not a failure.
        if remind {
            return Ok(());
        }
        if json {
            println!("{}", serde_json::to_string_pretty(&serde_json::json!({ "session": serde_json::Value::Null }))?);
            return Ok(());
        }
        println!("No session is open on {}.", project.name);
        println!("Open one with: rigger session start {}", project.name);
        return Ok(());
    };

    let at = db::now();
    let events = db.session_events(open.id)?;
    let shipped = db.shipped_between(project.id, &open.started_at, &at)?;
    let closed = db.tasks_closed_between(project.id, &open.started_at, &at)?;
    let next_step = db.latest_event_body(project.id, "next")?;
    let ended = db::Session {
        ended_at: Some(at.clone()),
        ..open.clone()
    };
    let summary = session::summarise(&project.name, &ended, &events, shipped, closed, next_step);

    db.end_session(open.id, &at)?;

    // A sitting's worth of work has just been written down, and the record
    // is one file. If the newest copy predates today, take one now: the
    // ritual's step that is most often skipped is the one that costs most
    // when it is, and a session always ends, hook or not.
    let insured = match db.newest_backup_at()? {
        Some(at) if days_since_utc(&at).is_some_and(|d| d < BACKUP_STALE_DAYS) => None,
        // A copy that will not be written must not fail the close: the
        // session is already ended and reporting it as an error would
        // invite a second `end` on a record that has none open.
        _ => match db.backup() {
            Ok(target) => {
                db.prune_backups(KEEP_BACKUPS)?;
                Some(target)
            }
            Err(e) => {
                eprintln!("The session closed, but the database could not be copied: {e:#}");
                None
            }
        },
    };

    // The entry goes into the record whatever else happens to it: a hub
    // written from the record reads its diary from there, and a sitting
    // that only wrote to a file was lost the moment the file was generated.
    // `--diary` still appends it to a file, for a hub kept by hand.
    let day = at.split('T').next().unwrap_or_default().to_string();
    if !summary.empty() {
        let entry = session::diary_entry(&summary, &day, heading);
        let body = entry.split_once('\n').map(|(_, rest)| rest.trim()).unwrap_or_default();
        let title = heading.map(str::trim).filter(|h| !h.is_empty()).map(|h| format!("{day} · {h}"));
        db.write_session_diary(open.id, project.id, &day, title.as_deref(), body)?;
    }
    let written = match diary {
        Some(path) => Some(write_diary(path, &summary, heading)?),
        None => None,
    };

    // The project's own closing command, after the record is written and
    // before anything is reported. After, because what it does - rhapsod
    // publishes its novellas - belongs to the sitting that has just been
    // written down, and a command that ran first would publish a session
    // the record had not yet closed.
    let hook = run_session_hook(&db, &project)?;

    let mut missing = summary.missing();
    if let Some(red) = red_gate_reminder(&db, &project, open.id)? {
        missing.push(red);
    }
    if let Some(run) = &hook
        && !run.passed
    {
        missing.push(format!("`{}` came back {}", run.command, run.verdict));
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "session": summary,
                "missing": missing,
                "diary": written,
                "backup": insured,
                "on_session_end": hook,
            }))?
        );
        return Ok(());
    }

    // A hook speaks only when there is something to say. A reminder that
    // fires on every stop is a reminder nobody reads.
    if remind {
        if missing.is_empty() {
            return Ok(());
        }
        println!("Session on {} closed - {}:", project.name, plural(summary.recorded(), "event", "events"));
        for item in &missing {
            println!("  {item}");
        }
        return Ok(());
    }

    println!("Session on {} closed, open since {}.", project.name, open.started_at);
    println!();
    if summary.empty() {
        println!("Nothing was recorded in it.");
    } else {
        if !summary.shipped.is_empty() {
            println!("shipped {}", summary.shipped.join(", "));
        }
        let counted = [
            ("decision", "decisions", summary.decisions.len()),
            ("finding", "findings", summary.findings.len()),
            ("pitfall", "pitfalls", summary.pitfalls.len()),
            ("change", "changes", summary.changes.len()),
            ("question", "questions", summary.questions.len()),
        ];
        let recorded: Vec<String> = counted.iter().filter(|(_, _, n)| *n > 0).map(|(one, many, n)| plural(*n, one, many)).collect();
        if !recorded.is_empty() {
            println!("recorded {}", recorded.join(", "));
        }
        if !summary.tasks_closed.is_empty() {
            println!("closed {}", plural(summary.tasks_closed.len(), "task", "tasks"));
        }
    }
    if let Some(next) = &summary.next_step {
        println!("next: {}", first_line(next));
    }

    if let Some(target) = &insured {
        println!("copied the database to {}", target.display());
    }
    if let Some(run) = &hook {
        println!("{}: {}", run.command, run.verdict);
    }

    if !missing.is_empty() {
        println!();
        println!("The ritual asks for:");
        for item in &missing {
            println!("  {item}");
        }
    }

    match written {
        Some(path) => println!(
            "
Diary entry appended to {path}"
        ),
        None => println!(
            "
Write it into a diary with: rigger session end {} --diary <file>",
            project.name
        ),
    }
    Ok(())
}

/// Appends the entry to a diary file, newest first.
///
/// Newest-first is how the hub's diary is written, so a new entry goes
/// under the heading and above what came before rather than at the end.
fn write_diary(path: &Path, summary: &session::Summary, heading: Option<&str>) -> Result<String> {
    let day = summary.ended_at.split('T').next().unwrap_or_default().to_string();
    let entry = session::diary_entry(summary, &day, heading);

    let existing = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e).with_context(|| format!("cannot read {}", path.display())),
    };

    // The preamble is whatever the file says before its first entry: a
    // title, a note about the format, a rule. A new entry goes after it and
    // above the entries, because that is where the newest one belongs.
    let (preamble, entries) = match existing.find(
        "
## ",
    ) {
        Some(at) => existing.split_at(at + 1),
        None => (existing.as_str(), ""),
    };
    let mut out = String::new();
    if !preamble.trim().is_empty() {
        out.push_str(preamble.trim_end());
        out.push_str(
            "

",
        );
    }
    out.push_str(entry.trim_end());
    out.push_str(
        "

",
    );
    if !entries.trim().is_empty() {
        out.push_str(entries.trim_start());
        if !out.ends_with('\n') {
            out.push('\n');
        }
    }
    std::fs::write(path, out).with_context(|| format!("cannot write {}", path.display()))?;
    Ok(path.display().to_string())
}

/// The first line of a body, for a screen with room for one.
fn first_line(text: &str) -> &str {
    text.lines().find(|l| !l.trim().is_empty()).unwrap_or(text).trim()
}

/// Writes a hub back out of the record.
///
/// The point at which the hub stops being where work is written down and
/// becomes a view of what was written down somewhere else. Only the three
/// files the record can rebuild are touched: Vision, the decision log's
/// prose and the research notes are argument rather than record, and the
/// record has no way to hold an argument that would survive being rebuilt.
fn export_hub(project: &str, hub_dir: &Path, check: bool, adopt: bool, docs: bool, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    if !hub_dir.is_dir() {
        bail!("{} is not a directory", hub_dir.display());
    }
    // Spelt the way the platform spells it, the way import records it.
    let hub_dir = &dunce::canonicalize(hub_dir).unwrap_or_else(|_| hub_dir.to_path_buf());

    let mut files: Vec<(String, String)> = Vec::new();
    for name in export::GENERATED {
        files.push((name.to_string(), generate(&db, &project, name)?));
    }
    // The handwritten texts, when asked for. Off by default because they
    // are a cache and nothing reads them back: the record is where they
    // live now, and writing them every time would put four more files in
    // every diff of every hub for no one's benefit.
    if docs {
        for document in db.documents(project.id, None)? {
            let Some(name) = hub_file_for(&document) else { continue };
            // Without the generated mark: these are the owner's prose, and
            // a mark saying "edits here are overwritten" would be a lie -
            // `import` reads an edit back in.
            files.push((name, format!("{}\n", document.body.trim_end())));
        }
    }
    if !check {
        db.set_hub_path(project.id, hub_dir)?;
    }

    let mut written = Vec::new();
    let mut diffs: Vec<(String, Vec<String>)> = Vec::new();
    for (name, text) in &files {
        let path = hub_dir.join(name);
        // A document is the owner's prose written back out, not a file the
        // record owns: it carries no mark, so the gate below would refuse
        // it for ever.
        let is_document = !export::GENERATED.contains(&name.as_str());
        let before = std::fs::read_to_string(&path).unwrap_or_default();
        // Written in the ending the file already used. Every hub of this
        // line is CRLF, and a generated file in LF would differ from its
        // source on every line - which is not a diff anybody reads.
        let text = &export::with_line_ending(text, export::line_ending(&before));
        let unchanged = before == *text;

        // A file a person has been writing in is not overwritten without
        // being asked. The mark is what says the record owns it, and it is
        // put there by an export - so the first one has to be deliberate.
        // A file a person has been writing in is not overwritten without
        // being asked. The mark is what says the record owns it, and only
        // an explicit `--adopt` puts the mark there the first time.
        if !unchanged && !is_document && !before.is_empty() && !export::is_generated(&before) && !adopt && !check {
            bail!(
                "{} was written by hand and the record does not own it yet.
Check what would change with `--check`, then hand it over with `--adopt`.",
                path.display()
            );
        }
        if !check && !unchanged {
            if let Some(dir) = path.parent() {
                std::fs::create_dir_all(dir).with_context(|| format!("cannot make {}", dir.display()))?;
            }
            std::fs::write(&path, text).with_context(|| format!("cannot write {}", path.display()))?;
        }
        // What would change, not just which file: the question `--check`
        // answers is whether a hand-written line is about to be lost.
        if check && !unchanged {
            diffs.push((name.clone(), export::diff(&before, text, 2)));
        }
        written.push(export::Written {
            file: name.to_string(),
            bytes: text.len(),
            unchanged,
        });
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({ "project": project.name, "files": written }))?
        );
        return Ok(());
    }

    let changed = written.iter().filter(|w| !w.unchanged).count();
    for file in &written {
        let state = match (file.unchanged, check) {
            (true, _) => "unchanged",
            (false, true) => "would change",
            (false, false) => "written",
        };
        println!("  {:<14} {state:<12} {} bytes", file.file, file.bytes);
    }
    for (file, lines) in &diffs {
        if lines.is_empty() {
            continue;
        }
        println!("\n{file}:");
        for line in lines {
            println!("  {line}");
        }
    }
    match (changed, check) {
        (0, _) => println!("\n{} is already what the record says.", hub_dir.display()),
        (n, true) => println!("\n{} of {} files differ from the record.", n, written.len()),
        (n, false) => println!("\n{} wrote {} of {} files.", project.name, n, written.len()),
    }
    Ok(())
}

/// The file a document is written back out to, mirroring what `import`
/// reads. A kind with no place in a hub is not exported.
fn hub_file_for(document: &db::Document) -> Option<String> {
    // The file it was read from, when the record knows it. Composing a name
    // from the title instead wrote a research note out beside the one it
    // came from, under a second name, and one note became two.
    if let Some(file) = document.source_file.as_deref()
        && !file.is_empty()
        && document.kind != "decisions"
    {
        return Some(file.to_string());
    }
    match document.kind.as_str() {
        "vision" => Some("Видение.md".to_string()),
        "rituals" => Some("Ритуалы.md".to_string()),
        // The decisions preamble is the head of a file the record also
        // writes the entries of, so it is not a file of its own.
        "decisions" | "other" => None,
        // The date the slug opens with is put back in front of the title,
        // because that is what the filename is sorted and addressed by:
        // writing out `Заметка.md` where `2026-09-04 — Заметка.md` came in
        // would give the note a different address on the next import.
        "research" => {
            let title = sanitise(&document.title);
            let date = document.slug.split('-').take(3).collect::<Vec<_>>().join("-");
            let named = match date.len() == 10 && date.bytes().all(|b| b.is_ascii_digit() || b == b'-') {
                true if !title.starts_with(&date) => format!("{date} — {title}"),
                _ => title,
            };
            Some(format!("{}/{}.md", hub::RESEARCH_DIR, named))
        }
        _ => None,
    }
}

/// A title as a filename: what a filesystem refuses, turned into spaces.
fn sanitise(title: &str) -> String {
    let cleaned: String = title.chars().map(|c| if r#"\/:*?"<>|"#.contains(c) { ' ' } else { c }).collect();
    cleaned.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// One generated file of a hub, from the record.
///
/// The single place a hub file is produced, so that `export` and
/// `doctor --hubs` cannot disagree about what the record says a file should
/// contain - a check that generated the file a second way would eventually
/// pass while the export wrote something else.
fn generate(db: &Db, project: &db::Project, name: &str) -> Result<String> {
    let prose = db.hub_prose(project.id, name)?;
    Ok(match name {
        n if n == export::GENERATED[0] => {
            let questions: Vec<String> = db.open_events(project.id, "question")?.into_iter().map(|(_, text)| text).collect();
            export::plan(&prose, &db.stages(project.id, false)?, &questions)
        }
        n if n == export::GENERATED[1] => export::changes(&prose, &db.stages(project.id, true)?),
        n if n == export::GENERATED[3] => export::readme(&prose, &db.state_lines(project.id)?),
        _ => export::diary(&prose, &db.diary_entries(project.id)?),
    })
}

/// Where a generated hub file no longer matches the record.
///
/// A file the record owns is a view of the record; edited by hand it stops
/// being one, and the next export would overwrite the edit without saying
/// so. This is what tells the owner before that happens.
fn hub_drift(db: &Db) -> Result<Vec<(String, String, &'static str)>> {
    let mut out = Vec::new();
    for project in db.projects()? {
        // A place the record keeps for itself has no hub to vouch for.
        if !project.kind.reads_git() {
            continue;
        }
        // Where the record says the hub is. It used to be guessed beside
        // the repository, and every hub of this line lives in a notes vault
        // instead - so the check read no files at all and reported that
        // every generated file matched, on hubs it had never opened.
        let Some(dir) = project.hub_path.as_deref().map(std::path::PathBuf::from) else {
            out.push((project.name.clone(), String::from("-"), "no hub recorded; import or export one"));
            continue;
        };
        if !dir.is_dir() {
            out.push((project.name.clone(), String::from("-"), "the hub is not where the record says"));
            continue;
        }
        let mut by_hand = Vec::new();
        for name in export::GENERATED {
            let path = dir.join(name);
            let Ok(text) = std::fs::read_to_string(&path) else { continue };
            if !export::is_generated(&text) {
                by_hand.push(name);
                continue;
            }
            let want = generate(db, &project, name)?;
            let want = export::with_line_ending(&want, export::line_ending(&text));
            if want != text {
                out.push((project.name.clone(), name.to_string(), "edited since it was generated"));
            }
        }
        // A hub still kept by hand is one the record cannot vouch for
        // either - and the one thing "every project through rigger" has
        // left to do. Named as such, so the list says how far along the
        // line is rather than staying silent about the files it skipped.
        if !by_hand.is_empty() {
            out.push((project.name.clone(), by_hand.join(", "), "kept by hand; `rigger export --adopt` hands it over"));
        }

        // The documents a hub also holds. These carry no generated mark -
        // they are the owner's prose - so the question is not "was this
        // edited" but "has the file drifted from what the record holds".
        // An edit here is not a mistake to undo; it is something `import`
        // should be told about before the next `export --docs` writes over
        // it.
        for document in db.documents(project.id, None)? {
            let Some(name) = hub_file_for(&document) else { continue };
            let path = dir.join(&name);
            let Ok(text) = std::fs::read_to_string(&path) else { continue };
            let want = export::with_line_ending(
                &format!(
                    "{}
",
                    document.body.trim_end()
                ),
                export::line_ending(&text),
            );
            if want != text {
                out.push((project.name.clone(), name, "the file differs; `rigger import` takes the edit in"));
            }
        }
    }
    Ok(out)
}

/// Hubs whose wishes file still holds something.
///
/// The file stopped being read at every session in v0.20.0: a wish now
/// arrives through `rigger wish` or the assistant's tool, and lives in the
/// record like everything else. Which means a wish written into the file
/// after that is a wish nobody will ever read - so the one thing the record
/// owes the file is to say when it is not empty.
///
/// Cheap enough to run unasked: one small file per project with a hub.
fn hubs_with_wishes(db: &Db) -> Result<Vec<(String, usize)>> {
    let mut out = Vec::new();
    for project in db.projects()? {
        let Some(hub) = &project.hub_path else { continue };
        let path = Path::new(hub).join(hub::WISHES_FILE);
        let Ok(text) = std::fs::read_to_string(&path) else { continue };
        let wishes = hub::parse_wishes(&text);
        if !wishes.is_empty() {
            out.push((project.name, wishes.len()));
        }
    }
    Ok(out)
}

fn doctor(hubs: bool, json: bool) -> Result<()> {
    let config = profile::Config::load()?;
    let (profile_name, _) = config.current()?;
    let path = paths::db_path()?;
    if !path.exists() {
        if json {
            println!("{}", serde_json::json!({ "profile": profile_name, "database": path, "initialised": false }));
        } else {
            println!("profile:   {profile_name}");
            println!("database:  {} (missing - run `rigger init`)", path.display());
        }
        return Ok(());
    }
    if !json {
        println!("profile:   {profile_name} ({})", profile::Config::path()?.display());
    }
    let db = Db::open(&path)?;
    let schema = db.schema_version()?;
    let counts = db.counts()?;
    // When the record is one file, its age is the one number that says how
    // much work a corrupt file would cost. It is read before the hub checks
    // so that it is printed whether or not those are asked for.
    let newest_backup = db.newest_backup_at()?;
    let backup_age = newest_backup.as_deref().and_then(days_since_utc);

    // Whether the other door opens. An assistant talks to the record over
    // MCP, and a server that does not answer looks from the outside like a
    // record with nothing in it - the failure reads as "this project has no
    // history", which is the most misleading thing rigger could say.
    let server = mcp::self_check(&db);

    // Where the plan and git disagree. Reported, never corrected: the record
    // cannot prove a tag's absence - it may simply not have been fetched -
    // and a silent correction would erase what the owner wrote (ADR 0005).
    let mut mismatches = Vec::new();
    let mut unsynced = Vec::new();
    for project in db.projects()? {
        // Never synced is a thing to fix only for a project git can answer
        // for; a service project would sit in that list for ever, being
        // advised a command that cannot help it.
        if !project.kind.reads_git() {
            continue;
        }
        if db.activity(project.id)?.is_none() {
            unsynced.push(project.name.clone());
            continue;
        }
        for version in db.shipped_without_a_tag(project.id)? {
            mismatches.push((project.name.clone(), version));
        }
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "profile": profile_name,
                "database": path,
                "initialised": true,
                "schema_version": schema,
                "counts": counts,
                "mcp": match &server {
                    Ok(check) => serde_json::to_value(check)?,
                    Err(e) => serde_json::json!({ "error": format!("{e:#}") }),
                },
                "backup": {
                    "newest_at": newest_backup,
                    "age_days": backup_age,
                    "copies": db.backups()?.len(),
                    "state": backup_state(backup_age),
                },
                "hubs": if hubs {
                    serde_json::to_value(
                        hub_drift(&db)?
                            .iter()
                            .map(|(project, file, why)| serde_json::json!({ "project": project, "file": file, "why": why }))
                            .collect::<Vec<_>>(),
                    )?
                } else {
                    serde_json::Value::Null
                },
                "closed_without_a_tag": mismatches
                    .iter()
                    .map(|(project, version)| serde_json::json!({ "project": project, "version": version }))
                    .collect::<Vec<_>>(),
                "never_synced": unsynced,
                "wishes_left_in_the_hub": hubs_with_wishes(&db)?
                    .iter()
                    .map(|(project, count)| serde_json::json!({ "project": project, "wishes": count }))
                    .collect::<Vec<_>>(),
            }))?
        );
        return Ok(());
    }
    println!("database:  {}", path.display());
    println!("schema:    version {schema}");
    println!("projects:  {}", counts.projects);
    println!("versions:  {}", counts.versions);
    println!("tasks:     {}", counts.tasks);
    println!("sessions:  {}", counts.sessions);
    println!("events:    {}", counts.events);
    match &server {
        Ok(check) => println!(
            "mcp:       answers - protocol {}, {}, {}",
            check.protocol,
            plural(check.tools, "tool", "tools"),
            plural(check.prompts, "prompt", "prompts")
        ),
        Err(e) => println!("mcp:       does not answer: {e:#}"),
    }
    match backup_age {
        None => println!("backup:    none - one file, no copy of it; run `rigger backup`"),
        Some(days) => {
            let copies = db.backups()?.len();
            let when = match days {
                0 => "today".to_string(),
                1 => "yesterday".to_string(),
                d => format!("{d} days ago"),
            };
            let verdict = match backup_state(Some(days)) {
                "old" => " - older than a week; run `rigger backup`",
                "stale" => " - older than a day; run `rigger backup`",
                _ => "",
            };
            println!("backup:    {when}, {} kept{verdict}", plural(copies, "copy", "copies"));
        }
    }

    if !unsynced.is_empty() {
        println!(
            "
never synced ({}): {}",
            unsynced.len(),
            unsynced.join(", ")
        );
        println!("  run `rigger sync` to read what git says about them");
    }
    if !mismatches.is_empty() {
        println!(
            "
closed in the plan, no tag in git ({}):",
            mismatches.len()
        );
        for (project, version) in &mismatches {
            println!("  {project:<12} {version}");
        }
        println!("  a tag would settle it; rigger does not change what you wrote");
    }

    let waiting = hubs_with_wishes(&db)?;
    if !waiting.is_empty() {
        println!();
        println!("wishes left in {} ({}):", hub::WISHES_FILE, waiting.len());
        for (project, count) in &waiting {
            println!("  {project:<12} {}", plural(*count, "wish", "wishes"));
        }
        println!("  the file is no longer read at every session: `rigger import <project> --hub <dir>` takes them in");
    }

    // A generated file edited by hand has stopped being a view of the
    // record, and the next export would overwrite the edit without saying
    // so. Off by default because it reads every hub from disk.
    if hubs {
        let drift = hub_drift(&db)?;
        println!();
        if drift.is_empty() {
            println!("hubs: every generated file matches the record");
        } else {
            println!("hubs the record cannot vouch for ({}):", drift.len());
            for (project, file, why) in &drift {
                println!("  {project:<12} {file:<14} {why}");
            }
            // The advice only fits an edit; a hub the record has never
            // seen needs the other sentence.
            if drift.iter().any(|(_, file, why)| file != "-" && why.starts_with("edited")) {
                println!("  edited: `rigger import` takes the edit into the record; `rigger export` discards it");
            }
        }
    }
    Ok(())
}