rigger 0.15.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
//! 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 calendar;
mod commit;
mod context;
mod db;
mod export;
mod hub;
mod import;
mod mcp;
mod open;
mod owner;
mod paths;
mod repo;
mod retro;
mod search;
mod session;
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)]
        hub: PathBuf,
        /// Print the report as JSON
        #[arg(long)]
        json: bool,
    },
    /// Record every repository under a directory, with its hub and its tags
    Adopt {
        /// Directory whose children are repositories
        root: PathBuf,
        /// Directory whose children are hubs, one per project name
        #[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 = "print_template")]
        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,
    },
    /// 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,
    },
    /// 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
        project: String,
        /// Version, as the record spells it
        version: String,
        /// 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
        project: String,
        /// Directory of the hub to write
        #[arg(long)]
        hub: 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,
        /// 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,
    },
    /// Copy the database aside, stamped with the moment and its schema
    Backup,
    /// 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,
}

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",
        }
    }
}

#[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 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,
    },
}

fn main() -> 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::Tier { name, tier, rhythm } => project_tier(&name, &tier, rhythm),
        },
        Command::Import { project, hub, json } => import_hub(&project, &hub, json),
        Command::Adopt { root, hubs, check, json } => adopt_root(&root, hubs.as_deref(), check, json),
        Command::Skill {
            project,
            install,
            dir,
            replace,
            template,
            print_template,
        } => write_skill(
            project.as_deref(),
            install || dir.is_some(),
            dir.as_deref(),
            replace,
            template.as_deref(),
            print_template,
        ),
        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 } => note(&project, kind.as_str(), &text),
        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, json } => why(&project, &version, 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,
            check,
            adopt,
            json,
        } => export_hub(&project, &hub, check, adopt, json),
        Command::Mcp => mcp::serve(),
        Command::Resolve { project, id, answer } => resolve(&project, id, answer.as_deref()),
        Command::Wish { project, text } => note(&project, "wish", &text),
        Command::Backup => backup(),
        Command::Doctor { hubs, json } => doctor(hubs, json),
    }
}

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.decisions_added > 0 {
        println!("  {:<10} {} added", "decisions", report.decisions_added);
    }
    if report.questions_added > 0 {
        println!("  {:<10} {} added", "questions", report.questions_added);
    }
    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.
fn adopt_root(root: &Path, hubs: Option<&Path>, check: bool, json: bool) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let adopted = 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(())
}

fn open_project(db: &Db, name: &str) -> Result<db::Project> {
    match db.project_by_name(name)? {
        Some(project) => Ok(project),
        None => 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_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));
    }
    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");
    }
}

fn note(project: &str, kind: &str, text: &str) -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let project = open_project(&db, project)?;
    db.record_event(project.id, kind, text, &db::now(), "assistant")?;
    println!("Recorded a {kind} for {}", project.name);
    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)?;
    }
    let found = db
        .find_events(&search::as_fts_query(query), project, kind, limit)
        .with_context(|| format!("{query:?} is not a search FTS5 understands"))?;

    if json {
        println!("{}", serde_json::to_string_pretty(&found)?);
        return Ok(());
    }
    if found.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 &found {
        print!("{}", search::render_event(event, show_project));
    }
    if found.len() as u32 == limit {
        println!("({limit} shown; --limit for more)");
    }
    Ok(())
}

/// The work that went into one version.
fn why(project: &str, version: &str, json: bool) -> Result<()> {
    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 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);
    }

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

    if waiting.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();
    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(", "));
        }
    }
    println!(
        "
Answer one with: rigger resolve <project> <id> \"<answer>\""
    );
    Ok(())
}

/// 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 })
}

fn backup() -> Result<()> {
    let db = Db::open(&paths::db_path()?)?;
    let target = db.backup()?;
    println!("Copied to {}", target.display());
    Ok(())
}

fn init() -> Result<()> {
    let path = paths::db_path()?;
    if path.exists() {
        Db::open(&path)?;
        println!("Already initialised: {}", path.display());
        return Ok(());
    }
    let db = Db::create(&path)?;
    println!("Created {} (schema version {})", db.path().display(), db.schema_version()?);
    println!("Next: rigger project add <path>");
    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)"),
    }
    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);
    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>,
    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),
        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,
        ..
    } = 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,
            }))?
        );
        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);
    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),
        },
    }
}

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,
            }))?
        );
        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);
    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);

    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(),
                "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);
        }
    }

    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(())
}

/// 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)?;

    let written = match diary {
        Some(path) => Some(write_diary(path, &summary, heading)?),
        None => None,
    };

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "session": summary,
                "missing": summary.missing(),
                "diary": written,
            }))?
        );
        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 {
        let missing = summary.missing();
        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));
    }

    let missing = summary.missing();
    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, 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());
    }

    let mut files = Vec::new();
    for name in export::GENERATED {
        files.push((name, generate(&db, &project, name)?));
    }
    if !check {
        db.set_hub_path(project.id, hub_dir)?;
    }

    let mut written = Vec::new();
    for (name, text) in &files {
        let path = hub_dir.join(name);
        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 && !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 {
            std::fs::write(&path, text).with_context(|| format!("cannot write {}", path.display()))?;
        }
        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);
    }
    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(())
}

/// 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;
        }
        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) {
                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"));
            }
        }
    }
    Ok(out)
}

fn doctor(hubs: bool, json: bool) -> Result<()> {
    let path = paths::db_path()?;
    if !path.exists() {
        if json {
            println!("{}", serde_json::json!({ "database": path, "initialised": false }));
        } else {
            println!("database:  {} (missing - run `rigger init`)", path.display());
        }
        return Ok(());
    }
    let db = Db::open(&path)?;
    let schema = db.schema_version()?;
    let counts = db.counts()?;

    // 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!({
                "database": path,
                "initialised": true,
                "schema_version": schema,
                "counts": counts,
                "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,
            }))?
        );
        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);

    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");
    }

    // 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, _)| file != "-") {
                println!("  edited: `rigger import` takes the edit into the record; `rigger export` discards it");
            }
        }
    }
    Ok(())
}