hird 0.2.2

Cross-harness agent work queue and shared assertion memory, backed by one local SQLite database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
//! The command line: `hird add`, `ls`, `show`, `cancel`, `reopen`, `mem …`.
//!
//! Everything a human does here is recorded with `actor = "cli"`, so the TUI's
//! history pane shows who did what.

use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};

use anyhow::Context;
use chrono::Utc;
use clap::{Args, Parser, Subcommand};

use crate::config::{self, Config};
use crate::db::Db;
use crate::exhibit;
use crate::fmt;
use crate::footing;
use crate::glob;
// The two announcement helpers live with the herald because the rule they
// encode — a sweep must announce what it collects — binds every reader that
// polls, not just this one.
use crate::herald::{announce_claimable, sweep_announcing, Cause, Herald};
use crate::identity::{self, ACTOR_CLI};
use crate::model::{Footprint, Standing, Status, TaskSummary};
use crate::plan;
use crate::register::{self, Registration};
use crate::repo::{dispatch_waves, Called, MemoryQuery, NewAssertion, OnConflict, ProjectScope};
use crate::witness;

/// Coordinate AI coding agents across harnesses through a shared work queue
/// and a shared assertion memory, all in one local SQLite database.
#[derive(Debug, Parser)]
#[command(
    name = "hird",
    version,
    about,
    long_about = None,
    arg_required_else_help = true
)]
pub struct Cli {
    /// Database file to use. Overrides HIRD_DB and the default location.
    #[arg(long, global = true, value_name = "PATH")]
    pub db: Option<PathBuf>,

    /// Copy this hird binary into ~/.local/bin.
    #[arg(long)]
    pub install: bool,

    /// Install the hird skill for Codex, Claude Code, Copilot, Gemini, and
    /// OpenCode.
    #[arg(long)]
    pub install_skill: bool,

    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Debug, Subcommand)]
pub enum Command {
    /// Add a task to the queue and print its number.
    Add(AddArgs),
    /// List tasks.
    #[command(visible_alias = "list")]
    Ls(LsArgs),
    /// Show one task in full, with its history.
    Show { seq: i64 },
    /// Explain whether a task is claimable right now, and if not, everything
    /// standing in the way.
    ///
    /// The claim gates, asked out loud in the order dispatch applies them: a
    /// live lease, unfinished dependencies, an unanswered question, recusals,
    /// capability requirements, and file-scope overlap with live work. `hird
    /// show` says everything about a task; this answers the one question a
    /// silent queue raises — why is nobody getting this handed to them?
    Why { seq: i64 },
    /// The history of one file across the queue: who declared it, whose
    /// hands the witness saw in it, and what the memory says about it.
    ///
    /// `hird show` answers for a task; this answers for a file — the question
    /// a reader asks before editing something the swarm has been through.
    /// Every line comes from what is already recorded: declared scopes,
    /// witnessed changes across every round a task was held, and the
    /// assertions anchored there, with whether they still stand.
    Blame {
        /// Project-relative path, as `hird show` lists it.
        path: String,
    },
    /// What happened on the board since you last looked, folded into news.
    ///
    /// The trail says everything; this says the difference. Reading it moves
    /// the bookmark, so the next digest starts where this one ended — unless
    /// `--peek` says not to. `--since` reads a window instead, and leaves the
    /// bookmark alone.
    Digest {
        /// From this moment instead of the bookmark: an RFC3339 UTC instant,
        /// prefixes welcome ("2026-08-14"), or how long ago ("90m", "2h").
        #[arg(long, value_name = "WHEN")]
        since: Option<String>,
        /// Read without moving the bookmark.
        #[arg(long)]
        peek: bool,
        #[command(flatten)]
        scope: ScopeFilterArgs,
    },
    /// A brief for one task as Markdown: everything a claim would hand an
    /// agent, on paper, for a session that cannot reach the queue.
    ///
    /// Instructions, the ground it builds on, questions and their answers,
    /// declared files, what has already moved under it, the findings it was
    /// sent back with, and what earlier work learned about the same files.
    /// Paste it into a cloud harness, a fresh clone, or a session with no
    /// MCP at all.
    Handoff { seq: i64 },
    /// The diff of what moved under a task, from the versions the witness kept.
    Diff {
        seq: i64,
        /// Only this file, project-relative.
        #[arg(long)]
        path: Option<String>,
        /// An archived holding instead of the current record: what round N
        /// changed, as `hird show` numbers the rounds.
        #[arg(long, value_name = "N")]
        tenure: Option<i64>,
    },
    /// Recover a version of a file as it stood under a task.
    Salvage {
        seq: i64,
        /// Project-relative path, as `hird show` lists it.
        path: String,
        /// The version the task started from, instead of the last one seen.
        #[arg(long)]
        baseline: bool,
        /// Reach an archived holding instead of the current record: the last
        /// version round N saw, as `hird show` numbers the rounds.
        #[arg(long, value_name = "N")]
        tenure: Option<i64>,
        /// Write to this file instead of stdout.
        #[arg(long, value_name = "FILE")]
        out: Option<PathBuf>,
        /// Overwrite an existing --out file.
        #[arg(long)]
        force: bool,
    },
    /// Abandon a task.
    Cancel {
        seq: i64,
        /// Why, for the record.
        #[arg(long, default_value = "")]
        reason: String,
    },
    /// Put a finished or cancelled task back in the pool.
    Reopen {
        seq: i64,
        /// Why, for the record.
        #[arg(long, default_value = "")]
        reason: String,
    },
    /// Answer the question keeping an open task out of dispatch.
    Answer {
        seq: i64,
        /// The decision or information the next agent should proceed with.
        answer: String,
    },
    /// Stand this project's queue down: nothing new is handed out until
    /// `hird resume` lifts it.
    ///
    /// Named claims and `task_next` alike are refused, carrying the reason,
    /// and the dispatch hook stays quiet. Work already claimed is untouched —
    /// leases run, check-ins and completions land — because a recess stops
    /// the hand-out, not the work. Calling it again refreshes the reason.
    Recess {
        /// Why, in your words. Carried on every refused claim.
        #[arg(default_value = "")]
        reason: String,
        /// Another project's queue instead of the one this directory is in.
        #[arg(long, value_name = "PATH")]
        project: Option<PathBuf>,
    },
    /// Lift the recess: claims resume at once, and the dispatch hook is
    /// woken for everything that became claimable while the queue stood down.
    Resume {
        /// Another project's queue instead of the one this directory is in.
        #[arg(long, value_name = "PATH")]
        project: Option<PathBuf>,
    },
    /// Add or remove dependencies between tasks.
    #[command(subcommand)]
    Dep(DepCommand),
    /// File a whole dependency graph from a plan file, or read it first.
    #[command(subcommand)]
    Plan(PlanCommand),
    /// Print the queue as dispatch waves: what can be worked now, and what
    /// each later wave is waiting for.
    Graph(GraphArgs),
    /// Show or set the files a task is expected to touch.
    Scope(ScopeArgs),
    /// Show or set the capabilities a claimant must advertise.
    Require(RequireArgs),
    /// Show which agent is working what, and where they overlap.
    Agents(ScopeFilterArgs),
    /// Bar whoever worked one task from working another, or lift the bar.
    ///
    /// This is what makes a review a review: the queue refuses the claim from
    /// the harness that did the work, and dispatch routes around it.
    Recuse(RecuseArgs),
    /// Show each harness's track record under review: verdicts received on
    /// its work, its first-pass rate, and the verdicts it has handed out.
    ///
    /// Derived entirely from delivered verdicts, so it measures the one thing
    /// the queue can measure — whose work survives a reading by a different
    /// model. A report, not a scheduler: nothing routes work by it.
    Record(ScopeFilterArgs),
    /// Tail the append-only event trail across every task, oldest first:
    /// claims, check-ins, completions, verdicts, witnessed changes, expiries.
    ///
    /// This is the queue's own log — what the TUI shows, without the terminal
    /// UI, so a swarm can be watched from a second terminal, a tmux pane, or
    /// a script. `--follow` keeps reading as events land, and `--json` makes
    /// each line one machine-readable object for whatever wants to build on
    /// the feed.
    Events(EventsArgs),
    /// The board as it stood at a past moment, folded from the event trail.
    ///
    /// The trail is append-only so that no question about the past becomes
    /// unanswerable; this is the command that asks one. "Show me the queue at
    /// the moment task 23 was sent back" is a fold over events that already
    /// exist — who held what, which wave was live, what was parked on a
    /// question — read-only, from the same trail `hird events` prints.
    /// Statuses are yesterday's; titles are today's, since the trail does not
    /// version them.
    Replay {
        /// When: an RFC3339 UTC instant, prefixes welcome ("2026-08-14",
        /// "2026-08-14T10:00"), or how long ago ("90m", "2h", "3d").
        when: String,
        #[command(flatten)]
        scope: ScopeFilterArgs,
    },
    /// Show what earlier work already learned about a task, and why it is
    /// relevant. This is what an agent is handed when it claims the task.
    Recall {
        seq: i64,
        /// How many assertions at most. Defaults to the configured
        /// `recall_limit`.
        #[arg(long, value_name = "N")]
        limit: Option<usize>,
    },
    /// Store and search assertions.
    #[command(subcommand)]
    Mem(MemCommand),
    /// Watch and drive the queue in a terminal UI.
    Tui,
    /// Watch the queue as a picture in a browser: the dependency graph by
    /// wave, who holds what, the feed as it lands, and a scrubber over the
    /// trail.
    ///
    /// A viewer, not a transport: it listens on loopback, is read-only, and
    /// dies with the terminal like `hird tui`. No agent talks to it.
    Web(WebArgs),
    /// Serve the Model Context Protocol on stdio. Harnesses run this.
    Mcp,
    /// Write this binary's MCP registration into a harness's config file.
    Register(RegisterArgs),
    /// Print the database path this invocation would use.
    DbPath,
}

#[derive(Debug, Args)]
pub struct EventsArgs {
    /// Keep watching: print each new event as it lands. On the way it sweeps
    /// expired leases and the working tree, the same way the TUI does, so
    /// expiries and witnessed changes appear even while no agent is calling.
    #[arg(long, short = 'f')]
    pub follow: bool,
    /// One JSON object per line instead of columns, for piping into tools.
    #[arg(long)]
    pub json: bool,
    /// Only these kinds, comma-separated — e.g. claimed,completed,witnessed.
    #[arg(long = "kind", value_name = "KIND", value_delimiter = ',')]
    pub kinds: Vec<crate::model::EventKind>,
    /// Only events on this task.
    #[arg(long, value_name = "SEQ")]
    pub task: Option<i64>,
    /// Only events recorded by this actor, exactly as the board names it —
    /// e.g. codex:9f2c, or cli.
    #[arg(long, value_name = "NAME")]
    pub actor: Option<String>,
    /// How many recent events to print — the backlog, before any following.
    #[arg(long, value_name = "N", default_value_t = 30)]
    pub limit: usize,
    /// Every project in the database, not just this one.
    #[arg(long)]
    pub all_projects: bool,
}

#[derive(Debug, Args)]
pub struct RegisterArgs {
    /// Which harness to register with. Each has one config file, and this
    /// writes to that one.
    pub harness: register::Harness,
    /// Name the server something other than `hird` — for a second
    /// registration alongside the first, usually with its own `--db`.
    #[arg(long, default_value = "hird", value_name = "NAME")]
    pub name: String,
    /// Print what would be written and write nothing.
    #[arg(long)]
    pub print: bool,
    /// Replace an entry of the same name that says something else.
    #[arg(long, conflicts_with = "print")]
    pub force: bool,
    /// Capability this harness can satisfy, e.g. browser or network.
    /// Repeatable, or comma-separated.
    #[arg(long = "capability", value_name = "NAME", value_delimiter = ',')]
    pub capabilities: Vec<String>,
}

#[derive(Debug, Args)]
pub struct AddArgs {
    /// Short title, as the human will refer to it.
    pub title: String,
    /// Full instructions for the agent, as markdown.
    #[arg(long, conflicts_with = "body_file")]
    pub body: Option<String>,
    /// Read the instructions from a file ("-" for stdin).
    #[arg(long, value_name = "PATH")]
    pub body_file: Option<PathBuf>,
    /// Higher sorts first. Informational only.
    #[arg(long, default_value_t = 0, allow_negative_numbers = true)]
    pub priority: i64,
    /// Project root to file this under. Defaults to the current project.
    #[arg(long, value_name = "PATH")]
    pub project: Option<PathBuf>,
    /// Task numbers this one must wait for. Repeatable, or comma-separated.
    #[arg(long = "needs", value_name = "SEQ", value_delimiter = ',')]
    pub needs: Vec<i64>,
    /// A file or glob this task is expected to touch, relative to the project
    /// root. Repeatable. Declaring these lets the queue keep two agents out of
    /// the same file.
    #[arg(long = "path", value_name = "GLOB")]
    pub paths: Vec<String>,
    /// Capability a claimant must advertise, e.g. browser or network.
    /// Repeatable, or comma-separated.
    #[arg(long = "requires", value_name = "CAPABILITY", value_delimiter = ',')]
    pub requirements: Vec<String>,
    /// When this task finishes, file a review of what it changed — scoped to
    /// the files that actually moved, and barred to the harness that moved
    /// them.
    #[arg(long)]
    pub review: bool,
}

#[derive(Debug, Subcommand)]
pub enum PlanCommand {
    /// File every task in a plan file, with its dependencies and file scopes.
    ///
    /// The whole plan lands in one transaction, or none of it does. Applying
    /// the same plan again files only what the file has gained since, so a
    /// plan is something to edit and re-run rather than a one-shot script.
    Apply {
        /// The plan file, as TOML ("-" for stdin).
        file: PathBuf,
        /// Work out what would be filed — waves, overlaps and all — and write
        /// nothing.
        #[arg(long)]
        dry_run: bool,
        /// Project root to file under. Defaults to the current project.
        #[arg(long, value_name = "PATH")]
        project: Option<PathBuf>,
    },
    /// Write the board back out as a plan file: the round trip.
    ///
    /// Everything the queue stores about its unfinished tasks — titles,
    /// bodies, priorities, files, capabilities, review marks and the
    /// dependencies between them — as the TOML `hird plan apply` reads.
    /// Tasks filed from a plan keep the names that plan gave them; the rest
    /// are named from their titles. A dependency on a task the export leaves
    /// out is dropped and said so in a comment, so what comes out always
    /// files.
    Export {
        /// Only the tasks one plan filed, under that plan's name.
        #[arg(long, value_name = "NAME")]
        plan: Option<String>,
        /// What to call the exported plan. Defaults to `--plan`, or to the
        /// project directory's name.
        #[arg(long, value_name = "NAME")]
        name: Option<String>,
        /// Include finished, failed and cancelled tasks too.
        #[arg(long)]
        all: bool,
        /// Project root to export. Defaults to the current project.
        #[arg(long, value_name = "PATH")]
        project: Option<PathBuf>,
    },
    /// Read a plan for trouble before filing it, and write nothing.
    ///
    /// Parsing is already the hard gate — cycles, dangling needs, bad globs
    /// and bad capability labels all refuse to parse, here and at apply
    /// alike — so what this adds is the trouble a fileable plan can still
    /// carry: unordered tasks declaring the same files, tasks the conflict
    /// radar cannot see, reviews that will never be filed or that nobody on
    /// this board could claim. Advisories, not refusals: the plan files
    /// either way. The exit code is nonzero only when the plan itself is
    /// unfileable.
    Lint {
        /// The plan file, as TOML ("-" for stdin).
        file: PathBuf,
        /// Project root to lint against. Defaults to the current project.
        #[arg(long, value_name = "PATH")]
        project: Option<PathBuf>,
    },
}

#[derive(Debug, Subcommand)]
pub enum DepCommand {
    /// Make a task wait for one or more others.
    Add {
        seq: i64,
        /// Task numbers it must wait for.
        #[arg(
            long = "needs",
            value_name = "SEQ",
            required = true,
            value_delimiter = ','
        )]
        needs: Vec<i64>,
    },
    /// Stop a task waiting for one or more others.
    #[command(visible_alias = "remove")]
    Rm {
        seq: i64,
        /// Task numbers it should no longer wait for.
        #[arg(
            long = "needs",
            value_name = "SEQ",
            required = true,
            value_delimiter = ','
        )]
        needs: Vec<i64>,
    },
}

#[derive(Debug, Args)]
pub struct ScopeArgs {
    pub seq: i64,
    /// A file or glob to add to the task's scope. Repeatable.
    #[arg(long = "path", value_name = "GLOB")]
    pub paths: Vec<String>,
    /// Forget everything the task had declared.
    #[arg(long, conflicts_with = "paths")]
    pub clear: bool,
}

#[derive(Debug, Args)]
pub struct RecuseArgs {
    /// The task to put under the bar.
    pub seq: i64,
    /// Task numbers whose worker must not take it. Repeatable, or
    /// comma-separated.
    #[arg(long = "from", value_name = "SEQ", value_delimiter = ',')]
    pub from: Vec<i64>,
    /// Why, for the record and for the refusal message.
    #[arg(long, default_value = "")]
    pub reason: String,
    /// Lift every bar on the task instead.
    #[arg(long, conflicts_with = "from")]
    pub clear: bool,
}

#[derive(Debug, Args)]
pub struct ScopeFilterArgs {
    /// Span every project rather than just the current one.
    #[arg(long)]
    pub all_projects: bool,
}

#[derive(Debug, Args)]
pub struct WebArgs {
    /// Port to listen on; 0 lets the system pick one, which the banner
    /// reports.
    #[arg(long, default_value_t = 7473)]
    pub port: u16,
    /// Address to listen on. Loopback unless you know why not.
    #[arg(long, default_value = "127.0.0.1", value_name = "ADDR")]
    pub bind: String,
    #[command(flatten)]
    pub scope: ScopeFilterArgs,
}

#[derive(Debug, Args)]
pub struct GraphArgs {
    #[command(flatten)]
    pub scope: ScopeFilterArgs,
    /// Render as Graphviz DOT instead of waves — pipe it into `dot -Tsvg`.
    #[arg(long, conflicts_with_all = ["mermaid", "json"])]
    pub dot: bool,
    /// Render as a Mermaid flowchart instead of waves — paste it into a
    /// README or a pull request.
    #[arg(long, conflicts_with = "json")]
    pub mermaid: bool,
    /// The whole graph as one JSON object — tasks, edges, waves, holders,
    /// what each task waits for and feeds — for anything that draws it.
    ///
    /// This is what `hird web` serves; finished tasks are included so a
    /// picture can show how far a plan has got.
    #[arg(long)]
    pub json: bool,
    /// Only the tasks one plan filed, and the dependencies between them.
    #[arg(long, value_name = "NAME")]
    pub plan: Option<String>,
}

#[derive(Debug, Args)]
pub struct RequireArgs {
    /// The task whose requirements to show or replace.
    pub seq: i64,
    /// Required capabilities. Repeatable, or comma-separated. Supplying any
    /// replaces the existing set.
    #[arg(long = "capability", value_name = "NAME", value_delimiter = ',')]
    pub capabilities: Vec<String>,
    /// Remove every capability requirement.
    #[arg(long, conflicts_with = "capabilities")]
    pub clear: bool,
}

#[derive(Debug, Args)]
pub struct LsArgs {
    /// Only tasks in this status.
    #[arg(long, value_name = "STATUS")]
    pub status: Option<String>,
    /// List tasks from every project.
    #[arg(long)]
    pub all_projects: bool,
}

#[derive(Debug, Subcommand)]
pub enum MemCommand {
    /// Record one factual assertion.
    ///
    /// Recording something already on file word for word does not duplicate it:
    /// it re-anchors that assertion to the code as it stands now and records
    /// another voice for it.
    Add {
        /// The assertion, in plain prose.
        content: String,
        /// Comma-separated tags.
        #[arg(long, default_value = "")]
        tags: String,
        /// Link it to the task it was learned on.
        #[arg(long, value_name = "SEQ")]
        task: Option<i64>,
        /// The file this fact is about. Repeatable. hird records what it says
        /// now, so a later reader can be told when it has moved.
        #[arg(long = "path", value_name = "PATH")]
        paths: Vec<String>,
    },
    /// Search assertions.
    Search {
        /// Full-text query. Plain words are fine.
        #[arg(default_value = "")]
        query: String,
        #[arg(long, default_value_t = 20)]
        limit: usize,
        /// Search every project.
        #[arg(long)]
        all_projects: bool,
        /// Include assertions that have been replaced.
        #[arg(long)]
        include_superseded: bool,
    },
    /// Audit what the memory still stands on.
    ///
    /// Every anchored assertion against the files it was learned from, oldest
    /// first: which are still exactly what they were, which have moved, and
    /// which were about code that no longer exists.
    Standing {
        /// Only the assertions worth re-reading — shaky and orphaned.
        #[arg(long)]
        shaky: bool,
        /// Audit every project.
        #[arg(long)]
        all_projects: bool,
    },
    /// Write this project's recorded facts as Markdown, ready to paste into
    /// a CLAUDE.md or AGENTS.md.
    ///
    /// The memory reaches agents through claims and searches, which only
    /// helps a session that can reach the queue. Exporting gives the same
    /// facts a second life on paper: a cloud harness, a fresh clone, a
    /// session with no MCP at all still inherits what the swarm learned. The
    /// export stays footing-aware — a fact whose ground has been rewritten
    /// since it was recorded goes out marked for a re-read, not dressed as
    /// this morning's.
    Export {
        /// Only facts anchored to files this glob names.
        #[arg(long, value_name = "GLOB")]
        path: Option<String>,
        /// Only facts whose anchors still match the tree exactly; the shaky,
        /// the orphaned and the never-anchored stay home.
        #[arg(long)]
        firm: bool,
    },
}

/// Run a parsed command, writing human-readable output to `out`.
///
/// `Command::Tui`, `Command::Web` and `Command::Mcp` are handled by the binary, which owns the
/// terminal and the async runtime; they are rejected here.
pub fn run(cli: &Cli, out: &mut impl Write) -> anyhow::Result<()> {
    // Registering is the one thing a human does before there is anything to
    // open, so it happens without touching the database.
    if let Some(Command::Register(args)) = &cli.command {
        return register_cmd(args, cli.db.as_deref(), out);
    }

    let db_path = config::resolve_db_path(cli.db.as_deref());

    if let Some(Command::DbPath) = &cli.command {
        writeln!(out, "{}", db_path.display())?;
        return Ok(());
    }

    let config = Config::load_default()?;
    let db = Db::open(&db_path).with_context(|| format!("opening {}", db_path.display()))?;
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let project = identity::resolve_project(&cwd);
    let herald = config.herald(&db_path);
    // Every queue verb below sweeps expired leases anyway; sweeping here
    // first keeps the outcome, so an expiry is announced by whichever
    // invocation notices it — `hird ls` glanced at by a human included.
    sweep_announcing(&db, &config, herald.as_ref());

    match cli
        .command
        .as_ref()
        .context("a command or installer option is required")?
    {
        Command::DbPath | Command::Register(_) => unreachable!("handled above"),
        Command::Tui | Command::Mcp | Command::Web(_) => {
            anyhow::bail!(
                "`hird {}` is served by the binary, not the command dispatcher",
                match &cli.command {
                    Some(Command::Tui) => "tui",
                    Some(Command::Web(_)) => "web",
                    _ => "mcp",
                }
            )
        }
        Command::Add(args) => {
            let seq = add(&db, &project, args, out)?;
            // Filed ready to work — unless `--needs` queued it behind
            // something, in which case the finish that clears it will speak.
            announce_claimable(herald.as_ref(), &db, &config, Cause::Filed, seq);
            Ok(())
        }
        Command::Ls(args) => {
            // The listing now says whether each task has changed anything, and
            // a stale answer to that is worse than none: a task that has been
            // writing since the last sweep would be listed as read-only.
            look(&db, &config, &project);
            ls(&db, &project, &config, args, out)
        }
        Command::Show { seq } => {
            look(&db, &config, &project);
            show(&db, *seq, &config, out)
        }
        Command::Why { seq } => why(&db, *seq, &config, out),
        Command::Diff { seq, path, tenure } => {
            diff(&db, *seq, path.as_deref(), *tenure, &config, out)
        }
        Command::Salvage {
            seq,
            path,
            baseline,
            tenure,
            out: to,
            force,
        } => salvage(
            &db,
            *seq,
            path,
            *baseline,
            *tenure,
            to.as_deref(),
            *force,
            &config,
            out,
        ),
        Command::Recall { seq, limit } => recall(
            &db,
            &config,
            &project,
            *seq,
            limit.map(|n| n.min(200)).unwrap_or(config.recall_limit()),
            out,
        ),
        Command::Cancel { seq, reason } => {
            let task = db.tasks().cancel(*seq, ACTOR_CLI, reason)?;
            writeln!(out, "task {} cancelled", task.seq)?;
            Ok(())
        }
        Command::Reopen { seq, reason } => {
            let task = db.tasks().reopen(*seq, ACTOR_CLI, reason)?;
            writeln!(out, "task {} reopened", task.seq)?;
            announce_claimable(herald.as_ref(), &db, &config, Cause::Reopened, task.seq);
            Ok(())
        }
        Command::Answer { seq, answer } => {
            let answered = db.questions().answer(*seq, ACTOR_CLI, answer)?;
            writeln!(out, "task {} answered", seq)?;
            writeln!(out, "  question  {}", answered.question)?;
            writeln!(
                out,
                "  answer    {}",
                answered.answer.as_deref().unwrap_or("")
            )?;
            announce_claimable(herald.as_ref(), &db, &config, Cause::Answered, *seq);
            Ok(())
        }
        Command::Recess {
            reason,
            project: explicit,
        } => recess_cmd(&db, &named_project(explicit, &project), reason, out),
        Command::Resume { project: explicit } => resume_cmd(
            &db,
            &config,
            herald.as_ref(),
            &named_project(explicit, &project),
            out,
        ),
        Command::Mem(cmd) => mem(&db, &project, &config, cmd, out),
        Command::Dep(cmd) => dep(&db, &config, herald.as_ref(), cmd, out),
        Command::Plan(cmd) => plan_cmd(&db, &project, &config, herald.as_ref(), cmd, out),
        Command::Graph(args) => {
            let scope = scope_of(&project, &config, args.scope.all_projects);
            let plan = args.plan.as_deref();
            if args.json {
                let snapshot = crate::graph::Snapshot::live(&db, &scope, plan)?;
                writeln!(out, "{}", serde_json::to_string_pretty(&snapshot)?)?;
                Ok(())
            } else if args.dot || args.mermaid {
                graph_render(&db, &scope, plan, args.mermaid, out)
            } else {
                graph(&db, &scope, plan, out)
            }
        }
        Command::Blame { path } => {
            look(&db, &config, &project);
            blame(&db, &config, &project, path, out)
        }
        Command::Digest { since, peek, scope } => {
            look(&db, &config, &project);
            digest_cmd(
                &db,
                &scope_of(&project, &config, scope.all_projects),
                since.as_deref(),
                *peek,
                out,
            )
        }
        Command::Handoff { seq } => {
            look(&db, &config, &project);
            handoff(&db, &config, *seq, out)
        }
        Command::Scope(args) => scope_cmd(&db, args, out),
        Command::Require(args) => require_cmd(&db, args, out),
        Command::Agents(args) => {
            look(&db, &config, &project);
            agents(&db, &scope_of(&project, &config, args.all_projects), out)
        }
        Command::Recuse(args) => recuse(&db, args, out),
        Command::Record(args) => record(&db, &scope_of(&project, &config, args.all_projects), out),
        Command::Replay { when, scope } => replay(
            &db,
            &scope_of(&project, &config, scope.all_projects),
            when,
            out,
        ),
        Command::Events(args) => events_cmd(&db, &project, &config, herald.as_ref(), args, out),
    }
}

/// `hird register`: put this binary in a harness's MCP config.
///
/// `--db` is honoured here as the database the *registered session* should use,
/// not the one this command reads — it reads none. Passing it is how a second
/// registration ends up pointed at a scratch board.
fn register_cmd(
    args: &RegisterArgs,
    db: Option<&Path>,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let harness = args.harness;
    let registration =
        Registration::new(harness, &args.name, db).with_capabilities(&args.capabilities)?;
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

    if args.print {
        writeln!(
            out,
            "# {} — {}",
            harness.label(),
            harness.config_path(&cwd).display()
        )?;
        write!(out, "{}", registration.render(harness))?;
        return Ok(());
    }

    let (path, outcome) = register::apply(harness, &registration, &cwd, args.force)?;

    writeln!(out, "{}", outcome.describe(&registration.name, &path))?;
    writeln!(
        out,
        "  command  {} {}",
        registration.command,
        registration.args.join(" ")
    )?;
    let env: Vec<String> = registration
        .env
        .iter()
        .map(|(key, value)| format!("{key}={value}"))
        .collect();
    writeln!(out, "  env      {}", env.join("  "))?;
    // The registration is only half of it, and the other half is the half
    // people miss — so it is the last line either way.
    writeln!(out, "next: {}", harness.next_step())?;
    Ok(())
}

/// Bring the witness's record of the current project up to date.
///
/// The human is reading the board, not working a task, so this confirms nothing
/// on any agent's behalf: it can only add to what is known, never make an
/// agent's copy of a file look fresher than it is. Failure is silence — an
/// unreadable working tree is not a reason to refuse to print the queue.
fn look(db: &Db, config: &Config, project: &str) {
    let Some(witness) = config.witness(Path::new(project)) else {
        return;
    };
    let _ = witness::sweep(db, &witness, project, ACTOR_CLI);
}

fn scope_of(project: &str, config: &Config, all_projects: bool) -> ProjectScope {
    ProjectScope::resolve(project, config.all_projects(Some(all_projects)))
}

/// The project a recess verb aims at: `--project` when given, else the one
/// this directory resolves to.
fn named_project(explicit: &Option<PathBuf>, resolved: &str) -> String {
    match explicit {
        Some(root) => identity::canonical_project(root),
        None => resolved.to_string(),
    }
}

/// `hird recess`: stand this project's queue down.
fn recess_cmd(db: &Db, project: &str, reason: &str, out: &mut impl Write) -> anyhow::Result<()> {
    match db.recesses().call(project, reason, ACTOR_CLI)? {
        Called::Began(recess) => {
            writeln!(
                out,
                "queue for {project} in recess{}",
                recess.quoted_reason()
            )?;
            writeln!(
                out,
                "  nothing new is handed out; work already claimed continues"
            )?;
            writeln!(out, "  hird resume lifts it")?;
        }
        Called::AlreadyStanding {
            recess,
            reason_changed,
        } => {
            let note = if reason_changed {
                "; reason updated"
            } else {
                ""
            };
            writeln!(
                out,
                "already in recess since {}{note}",
                fmt::age_phrase(&recess.at, Utc::now())
            )?;
        }
    }
    Ok(())
}

/// `hird resume`: lift the recess and summon hands to what waited behind it.
fn resume_cmd(
    db: &Db,
    config: &Config,
    herald: Option<&Herald>,
    project: &str,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    match db.recesses().lift(project)? {
        None => writeln!(
            out,
            "the queue for {project} was not in recess; nothing to lift"
        )?,
        Some(_) => {
            writeln!(out, "recess lifted for {project} — claims resume")?;
            // Everything that became claimable while the queue stood down was
            // deliberately never announced; announce it now, task by task, so
            // the dispatch hook summons hands to the backlog. The claimable
            // check inside `announce_claimable` keeps blocked and parked work
            // quiet, exactly as it does everywhere else.
            let scope = ProjectScope::Only(project.to_string());
            for task in db.tasks().list(&scope, Some(Status::Open))? {
                announce_claimable(herald, db, config, Cause::Resumed, task.seq);
            }
        }
    }
    Ok(())
}

/// The banner `hird ls` and `hird graph` open with while a recess stands.
fn recess_banner(recess: &crate::model::Recess, now: chrono::DateTime<Utc>) -> String {
    format!(
        "in recess{} — called {}; nothing new is handed out, hird resume lifts it",
        recess.quoted_reason(),
        fmt::age_phrase(&recess.at, now)
    )
}

/// `hird events`: the trail across tasks, as a log — and, with `--follow`,
/// as a live one.
///
/// Follow mode makes this command a monitor in the same sense the TUI is one:
/// it polls the same SQLite file at the same cadence, sweeps expired leases so
/// their announcements are not waiting on somebody else to glance at the
/// board, and looks at the working tree so witnessed changes land in the feed
/// while they are still news. There is still no daemon — stopping the tail
/// costs nothing and forgets nothing, because the cursor is the trail itself.
fn events_cmd(
    db: &Db,
    project: &str,
    config: &Config,
    herald: Option<&Herald>,
    args: &EventsArgs,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let scope = scope_of(project, config, args.all_projects);
    let filter = crate::repo::FeedFilter {
        kinds: args.kinds.clone(),
        task_seq: args.task,
        actor: args.actor.clone(),
    };
    // The trail only carries what somebody enforced; the reader is now that
    // somebody, so the backlog it prints is current rather than as-of the
    // last time an agent called.
    look(db, config, project);
    let backlog = db.events().tail(&scope, &filter, args.limit)?;
    let mut cursor = backlog.last().map(|e| e.cursor).unwrap_or(0);
    if backlog.is_empty() && !args.follow && !args.json {
        writeln!(out, "nothing on the record yet")?;
    }
    for event in &backlog {
        write_event(out, event, args.json, scope.is_all())?;
    }
    if !args.follow {
        return Ok(());
    }
    out.flush()?;
    let mut last_look = Utc::now();
    loop {
        std::thread::sleep(crate::tui::app::POLL_INTERVAL);
        // Expiry is enforced lazily by whoever reads the table next, and
        // while a tail is running that is this loop — with the herald told,
        // exactly as if a human had glanced at the board.
        if let Ok(outcome) = db.tasks().sweep_leases() {
            for seq in outcome.expired {
                announce_claimable(herald, db, config, Cause::LeaseExpired, seq);
            }
        }
        let now = Utc::now();
        if now - last_look >= crate::tui::app::WITNESS_INTERVAL {
            last_look = now;
            look(db, config, project);
        }
        for event in db.events().since(&scope, &filter, cursor)? {
            cursor = event.cursor;
            write_event(out, &event, args.json, scope.is_all())?;
        }
        out.flush()?;
    }
}

/// One event, one line: columns for a human, an object for a pipe.
fn write_event(
    out: &mut impl Write,
    event: &crate::repo::FeedEvent,
    json: bool,
    all_projects: bool,
) -> anyhow::Result<()> {
    if json {
        writeln!(
            out,
            "{}",
            serde_json::json!({
                "cursor": event.cursor,
                "at": event.at,
                "project": event.project,
                "task": event.task_seq,
                "title": event.task_title,
                "actor": event.actor,
                "kind": event.kind.as_str(),
                "detail": event.detail,
            })
        )?;
        return Ok(());
    }
    let clock = crate::model::parse_ts(&event.at)
        .map(|at| at.format("%H:%M:%S").to_string())
        .unwrap_or_else(|| "??:??:??".into());
    // The detail is the news; where a kind carries none, the title says what
    // the event happened to.
    let what = if event.detail.is_empty() {
        fmt::truncate(&event.task_title, 76)
    } else {
        fmt::truncate(&event.detail, 76)
    };
    let task = format!("#{}", event.task_seq);
    if all_projects {
        writeln!(
            out,
            "{clock}  {task:>4}  {:<14} {:<18} {what}  [{}]",
            event.kind, event.actor, event.project
        )?;
    } else {
        writeln!(
            out,
            "{clock}  {task:>4}  {:<14} {:<18} {what}",
            event.kind, event.actor
        )?;
    }
    Ok(())
}

fn add(db: &Db, project: &str, args: &AddArgs, out: &mut impl Write) -> anyhow::Result<i64> {
    let body = match (&args.body, &args.body_file) {
        (Some(body), _) => body.clone(),
        (None, Some(path)) => read_text(path)?,
        (None, None) => String::new(),
    };
    let project = match &args.project {
        Some(explicit) => identity::canonical_project(explicit),
        None => project.to_string(),
    };
    let task = db
        .tasks()
        .create(&project, &args.title, &body, args.priority, ACTOR_CLI)?;
    // Dependencies and scope go on after creation, so a bad `--needs` leaves a
    // real task behind rather than losing the title the human just typed.
    for needed in &args.needs {
        db.deps().add(task.seq, *needed, ACTOR_CLI)?;
    }
    if !args.paths.is_empty() {
        db.scopes()
            .declare(task.seq, &args.paths, ACTOR_CLI, OnConflict::Report)?;
    }
    if !args.requirements.is_empty() {
        db.requirements()
            .set(task.seq, &args.requirements, ACTOR_CLI)?;
    }
    if args.review {
        db.tasks().set_review(task.seq, true, ACTOR_CLI)?;
    }
    writeln!(out, "{}", task.seq)?;
    Ok(task.seq)
}

fn dep(
    db: &Db,
    config: &Config,
    herald: Option<&Herald>,
    cmd: &DepCommand,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    match cmd {
        DepCommand::Add { seq, needs } => {
            for needed in needs {
                if db.deps().add(*seq, *needed, ACTOR_CLI)? {
                    writeln!(out, "task {seq} now waits for task {needed}")?;
                } else {
                    writeln!(out, "task {seq} already waited for task {needed}")?;
                }
            }
        }
        DepCommand::Rm { seq, needs } => {
            for needed in needs {
                if db.deps().remove(*seq, *needed, ACTOR_CLI)? {
                    writeln!(out, "task {seq} no longer waits for task {needed}")?;
                } else {
                    writeln!(out, "task {seq} was not waiting for task {needed}")?;
                }
            }
            // Removing an edge is a human re-plan, and it can be the thing
            // that leaves the task waiting for nothing.
            announce_claimable(herald, db, config, Cause::Unblocked, *seq);
        }
    }
    Ok(())
}

/// File a plan, or work out what filing it would do.
fn plan_cmd(
    db: &Db,
    project: &str,
    config: &Config,
    herald: Option<&Herald>,
    cmd: &PlanCommand,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let (file, explicit) = match cmd {
        PlanCommand::Apply { file, project, .. } | PlanCommand::Lint { file, project } => {
            (file, project)
        }
        PlanCommand::Export {
            plan: only,
            name,
            all,
            project: explicit,
        } => {
            let project = match explicit {
                Some(root) => identity::canonical_project(root),
                None => project.to_string(),
            };
            return plan_export(db, &project, only.as_deref(), name.as_deref(), *all, out);
        }
    };
    let source = read_text(file)?;
    let parsed =
        plan::parse(&source).with_context(|| format!("reading the plan in {}", file.display()))?;
    let project = match explicit {
        Some(root) => identity::canonical_project(root),
        None => project.to_string(),
    };

    let dry_run = match cmd {
        PlanCommand::Lint { .. } => return lint(db, &project, &parsed, out),
        PlanCommand::Apply { dry_run, .. } => *dry_run,
        PlanCommand::Export { .. } => unreachable!("handled above"),
    };
    if dry_run {
        return preview(db, &project, &parsed, out);
    }

    let applied = db.plans().apply(&project, &parsed, ACTOR_CLI)?;
    // The first wave is workable the moment the plan commits; the claimable
    // check inside `announce` is what keeps the later waves quiet.
    for placed in &applied.created {
        announce_claimable(herald, db, config, Cause::Filed, placed.seq);
    }
    if applied.created.is_empty() {
        writeln!(
            out,
            "plan {:?} is already filed in full; nothing to do",
            parsed.plan
        )?;
    } else {
        writeln!(
            out,
            "filed {} from plan {:?}",
            count(applied.created.len(), "task"),
            parsed.plan
        )?;
        for placed in &applied.created {
            writeln!(
                out,
                "  #{:<4} {:<14} {}",
                placed.seq,
                fmt::truncate(&placed.name, 14),
                fmt::truncate(&placed.title, 44)
            )?;
        }
    }
    if !applied.reused.is_empty() && !applied.created.is_empty() {
        // Only worth saying next to what was filed: on a re-apply that files
        // nothing, the line above has already said the whole plan was there.
        let numbers: Vec<String> = applied
            .reused
            .iter()
            .map(|p| format!("#{}", p.seq))
            .collect();
        writeln!(
            out,
            "{} already filed: {}",
            count(applied.reused.len(), "task"),
            numbers.join(", ")
        )?;
    }
    if applied.edges_added > 0 {
        writeln!(out, "{} recorded", count(applied.edges_added, "dependency"))?;
    }
    for drift in &applied.drifted {
        writeln!(out, "note: {}", drift.describe())?;
    }
    for conflict in &applied.conflicts {
        writeln!(out, "warning: {}", conflict.describe())?;
    }
    Ok(())
}

/// What this plan would become, printed and not written.
///
/// The waves come from the same function `hird graph` prints, so what a human
/// reads here is what the board will say once the plan is filed.
fn preview(
    db: &Db,
    project: &str,
    parsed: &plan::Plan,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let preview = parsed.preview();
    let filed: BTreeMap<String, i64> = db
        .plans()
        .nodes(project, &parsed.plan)?
        .into_iter()
        .collect();

    writeln!(
        out,
        "plan {:?} — {}, {}, at most {} at once",
        parsed.plan,
        count(parsed.tasks.len(), "task"),
        count(preview.waves.len(), "wave"),
        preview.widest()
    )?;

    for (index, wave) in preview.waves.iter().enumerate() {
        let label = match index {
            0 => "wave 1  (workable now)".to_string(),
            n => format!("wave {}  (after wave {n})", n + 1),
        };
        writeln!(out, "\n{label}")?;
        for name in wave {
            let Some(task) = parsed.task(name) else {
                continue;
            };
            let number = match filed.get(name) {
                Some(seq) => format!("#{seq}"),
                None => "new".to_string(),
            };
            let mut line = format!(
                "  {:<5} {:<14} {}",
                number,
                fmt::truncate(name, 14),
                fmt::truncate(&task.title, 40)
            );
            if !task.needs.is_empty() {
                line.push_str(&format!("   waits for {}", task.needs.join(", ")));
            }
            writeln!(out, "{line}")?;
            if !task.paths.is_empty() {
                writeln!(out, "      files  {}", task.paths.join(", "))?;
            }
            if !task.requires.is_empty() {
                writeln!(out, "      requires {}", task.requires.join(", "))?;
            }
        }
    }

    if !preview.collisions.is_empty() {
        writeln!(
            out,
            "\nsame files, nothing ordering them — the queue hands these out one \
             at a time, so the waves above are wider than the work really is"
        )?;
        for collision in &preview.collisions {
            writeln!(out, "  {}", collision.describe())?;
        }
    }
    if !preview.unscoped.is_empty() {
        writeln!(
            out,
            "\ndeclaring no files: {}\n  the queue cannot keep another agent out \
             of what these touch, and what earlier work learned reaches them by \
             title alone",
            preview.unscoped.join(", ")
        )?;
    }

    let already = filed.len();
    if already == 0 {
        writeln!(out, "\nnothing was written; drop --dry-run to file it")?;
    } else {
        writeln!(
            out,
            "\nnothing was written; {} of these already filed, so applying would \
             file the other {}",
            already,
            parsed.tasks.len() - already
        )?;
    }
    Ok(())
}

/// `hird mem export`: the project's current facts, as Markdown on stdout.
///
/// One fact per bullet, its files and footing on the line below — enough for
/// a reader with no queue to know what was learned and whether the code it
/// was learned from still stands. Oldest first, so re-exporting after new
/// work appends rather than reshuffles.
fn mem_export(
    db: &Db,
    project: &str,
    witness: Option<&witness::Witness>,
    path: Option<&str>,
    firm_only: bool,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let wanted = match path {
        Some(raw) => Some(glob::normalize(raw).ok_or_else(|| {
            anyhow::anyhow!("--path {raw:?} is not a usable glob; try src/**, or a literal path")
        })?),
        None => None,
    };
    if firm_only && witness.is_none() {
        anyhow::bail!(
            "--firm needs a watched tree to check anchors against; run inside the \
             project's git checkout, or export without it"
        );
    }

    let scope = ProjectScope::Only(project.to_string());
    let mut facts = db
        .memory()
        .search(&MemoryQuery::new("", scope).limit(10_000))?;
    // Recency is search's order; an export wants the stable one.
    facts.sort_by(|a, b| (&a.created_at, &a.id).cmp(&(&b.created_at, &b.id)));
    let ids: Vec<String> = facts.iter().map(|a| a.id.clone()).collect();
    let anchors = db.footings().anchors_for(Some(project), &ids)?;
    let standings = footing::standings(db, witness, project, &ids);

    let kept: Vec<&crate::model::Assertion> = facts
        .iter()
        .filter(|fact| match &wanted {
            Some(glob) => anchors
                .get(&fact.id)
                .is_some_and(|list| list.iter().any(|a| crate::glob::intersects(glob, &a.path))),
            None => true,
        })
        .filter(|fact| !firm_only || matches!(standings.get(&fact.id), Some(Standing::Firm { .. })))
        .collect();

    if kept.is_empty() {
        writeln!(out, "nothing to export; hird mem add is how facts get here")?;
        return Ok(());
    }

    writeln!(out, "## What earlier work here learned")?;
    writeln!(out)?;
    writeln!(
        out,
        "<!-- hird mem export, {}. Facts recorded by agents working this\n\
         project, each anchored to the files it was read off. One marked\n\
         \"re-check\" has had that ground rewritten since it was learned. -->",
        Utc::now().format("%Y-%m-%d")
    )?;
    writeln!(out)?;
    for fact in kept {
        writeln!(out, "- {}", fact.content.trim())?;
        let mut notes: Vec<String> = Vec::new();
        if let Some(list) = anchors.get(&fact.id).filter(|l| !l.is_empty()) {
            let paths: Vec<String> = list.iter().map(|a| format!("`{}`", a.path)).collect();
            notes.push(paths.join(", "));
        }
        match standings.get(&fact.id) {
            Some(Standing::Shaky { .. }) => {
                notes.push("re-check: the ground under this has moved since".to_string());
            }
            Some(Standing::Orphaned { .. }) => {
                notes.push("re-check: the files this was read off are gone".to_string());
            }
            _ => {}
        }
        if let Some(spoken) = footing::corroboration(db, fact) {
            notes.push(spoken);
        }
        if !notes.is_empty() {
            writeln!(out, "  — {}", notes.join("; "))?;
        }
    }
    Ok(())
}

/// `hird plan export`: the board, written back down as the file that would
/// file it.
///
/// Plans are data, and the queue is the same data with numbers instead of
/// names; this is the direction `plan apply` does not go. What comes out is
/// re-parsed before it is printed, so it is a plan the queue has already
/// agreed to take.
fn plan_export(
    db: &Db,
    project: &str,
    only: Option<&str>,
    name: Option<&str>,
    all: bool,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let scope = ProjectScope::Only(project.to_string());
    let origins = db.plans().origins(project)?;
    let mut tasks: Vec<TaskSummary> = db
        .tasks()
        .list(&scope, None)?
        .into_iter()
        .filter(|t| all || !t.status.is_terminal())
        .filter(|t| match only {
            Some(plan) => origins.get(&t.seq).is_some_and(|(p, _)| p == plan),
            None => true,
        })
        .collect();
    tasks.sort_by_key(|t| t.seq);
    if tasks.is_empty() {
        match only {
            Some(plan) => writeln!(out, "# plan {plan:?} has filed nothing here to export")?,
            None if all => writeln!(out, "# nothing filed in this project to export")?,
            None => writeln!(
                out,
                "# no unfinished tasks to export; --all includes the finished ones"
            )?,
        }
        return Ok(());
    }

    // Names: what the plan called it, else what the title says, and never two
    // the same — a name that resolves to the wrong task is worse than an ugly
    // one, so a clash gets its queue number.
    let mut taken: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    let mut names: BTreeMap<i64, String> = BTreeMap::new();
    for task in &tasks {
        let wanted = match origins.get(&task.seq) {
            Some((plan, node)) if only.is_none_or(|p| p == plan) => node.clone(),
            _ => slug(&task.title),
        };
        let name = if taken.insert(wanted.clone()) {
            wanted
        } else {
            let numbered = format!("{wanted}-{}", task.seq);
            taken.insert(numbered.clone());
            numbered
        };
        names.insert(task.seq, name);
    }

    let mut dropped: Vec<String> = Vec::new();
    let mut needs: BTreeMap<i64, Vec<String>> = BTreeMap::new();
    for (task, on) in db.deps().edges(&scope)? {
        let Some(from) = names.get(&task) else {
            continue;
        };
        match names.get(&on) {
            Some(to) => needs.entry(task).or_default().push(to.clone()),
            None => dropped.push(format!("{from} waited for #{on}")),
        }
    }

    let plan_name = name
        .map(str::to_string)
        .or_else(|| only.map(str::to_string))
        .unwrap_or_else(|| {
            Path::new(project)
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .filter(|n| !n.is_empty())
                .unwrap_or_else(|| "board".to_string())
        });
    let mut exported = plan::Plan {
        plan: plan_name,
        tasks: Vec::new(),
    };
    for summary in &tasks {
        let task = db.tasks().get(summary.seq)?;
        exported.tasks.push(plan::PlanTask {
            name: names[&task.seq].clone(),
            title: task.title.clone(),
            body: task.body.trim().to_string(),
            priority: task.priority,
            paths: db.scopes().for_task(task.seq)?,
            requires: db.requirements().for_task(task.seq)?,
            needs: needs.remove(&task.seq).unwrap_or_default(),
            review: task.review,
        });
    }
    let toml = exported.to_toml();
    // The one guarantee this command makes is that its output files; the
    // cheapest way to keep it is to read it back the way `apply` will.
    plan::parse(&toml).context("the exported plan does not read back; this is a bug in hird")?;

    writeln!(
        out,
        "# hird plan export, {}: {} from {project}",
        Utc::now().format("%Y-%m-%d"),
        count(tasks.len(), "task")
    )?;
    for (seq, name) in &names {
        writeln!(out, "#   {name} was #{seq}")?;
    }
    for line in &dropped {
        writeln!(out, "# dropped: {line}, which is not in this export")?;
    }
    writeln!(out)?;
    write!(out, "{toml}")?;
    Ok(())
}

/// A plan-file name out of a title: lowercase words joined by hyphens, cut
/// to something a `needs` line can hold.
fn slug(title: &str) -> String {
    let mut name = String::new();
    let mut gap = false;
    for c in title.chars() {
        if c.is_ascii_alphanumeric() {
            if gap && !name.is_empty() {
                name.push('-');
            }
            name.push(c.to_ascii_lowercase());
            gap = false;
        } else {
            gap = true;
        }
    }
    let cut: String = name.chars().take(40).collect();
    let cut = cut.trim_end_matches('-').to_string();
    if cut.is_empty() {
        "task".to_string()
    } else {
        cut
    }
}

/// `hird graph --dot` / `--mermaid`: the dependency graph for a renderer.
///
/// Waves become ranks, statuses become colours, and every edge points the
/// way the work flows — from what must finish to what waits for it. Finished
/// tasks appear only where something unfinished still waits on them, so a
/// long-lived board does not render its whole history every time.
fn graph_render(
    db: &Db,
    scope: &ProjectScope,
    plan: Option<&str>,
    mermaid: bool,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let (tasks, edges) = graph_inputs(db, scope, plan)?;
    let waves = dispatch_waves(&tasks, &edges);
    let by_seq: BTreeMap<i64, &TaskSummary> = tasks.iter().map(|t| (t.seq, t)).collect();
    let pending: std::collections::BTreeSet<i64> = waves.iter().flatten().copied().collect();
    // A finished task earns a node only as the ground under something live.
    let shown: std::collections::BTreeSet<i64> = pending
        .iter()
        .copied()
        .chain(
            edges
                .iter()
                .filter(|(t, _)| pending.contains(t))
                .map(|(_, on)| *on),
        )
        .collect();
    let drawn: Vec<&(i64, i64)> = edges
        .iter()
        .filter(|(t, on)| shown.contains(t) && shown.contains(on))
        .collect();

    let label = |t: &TaskSummary| {
        let title = fmt::truncate(&t.title, 40).replace('"', "'");
        match &t.claimed_by {
            Some(holder) => format!("#{} {title}\\n{} · {holder}", t.seq, t.status),
            None => format!("#{} {title}\\n{}", t.seq, t.status),
        }
    };

    if mermaid {
        writeln!(out, "flowchart LR")?;
        for (index, wave) in waves.iter().enumerate() {
            writeln!(out, "  subgraph wave{} [\"wave {}\"]", index + 1, index + 1)?;
            for seq in wave {
                if let Some(t) = by_seq.get(seq) {
                    writeln!(out, "    t{seq}[\"{}\"]", label(t).replace("\\n", "<br/>"))?;
                }
            }
            writeln!(out, "  end")?;
        }
        for seq in shown.difference(&pending) {
            if let Some(t) = by_seq.get(seq) {
                writeln!(out, "  t{seq}([\"{}\"])", label(t).replace("\\n", "<br/>"))?;
            }
        }
        for (task, on) in drawn {
            writeln!(out, "  t{on} --> t{task}")?;
        }
        for seq in &shown {
            if let Some(t) = by_seq.get(seq) {
                writeln!(
                    out,
                    "  style t{seq} fill:{},stroke:#555",
                    status_colour(t.status)
                )?;
            }
        }
        return Ok(());
    }

    writeln!(out, "digraph hird {{")?;
    writeln!(out, "  rankdir=LR;")?;
    writeln!(
        out,
        "  node [shape=box, style=\"rounded,filled\", fontname=\"Helvetica\"];"
    )?;
    for (index, wave) in waves.iter().enumerate() {
        writeln!(out, "  subgraph cluster_wave{} {{", index + 1)?;
        writeln!(out, "    label=\"wave {}\"; color=\"#999999\";", index + 1)?;
        for seq in wave {
            if let Some(t) = by_seq.get(seq) {
                writeln!(
                    out,
                    "    t{seq} [label=\"{}\", fillcolor=\"{}\"];",
                    label(t),
                    status_colour(t.status)
                )?;
            }
        }
        writeln!(out, "  }}")?;
    }
    for seq in shown.difference(&pending) {
        if let Some(t) = by_seq.get(seq) {
            writeln!(
                out,
                "  t{seq} [label=\"{}\", fillcolor=\"{}\", style=\"rounded,filled,dashed\"];",
                label(t),
                status_colour(t.status)
            )?;
        }
    }
    for (task, on) in drawn {
        writeln!(out, "  t{on} -> t{task};")?;
    }
    writeln!(out, "}}")?;
    Ok(())
}

fn status_colour(status: Status) -> &'static str {
    match status {
        Status::Open => "#ffffff",
        Status::Claimed => "#fff3b0",
        Status::InProgress => "#ffe066",
        Status::Done => "#c7f0c2",
        Status::Failed => "#f5b7b1",
        Status::Cancelled => "#dddddd",
    }
}

/// `hird blame`: one file's history across the queue.
fn blame(
    db: &Db,
    config: &Config,
    project: &str,
    raw: &str,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let path = raw.trim().trim_start_matches("./").trim_end_matches('/');
    if path.is_empty() {
        anyhow::bail!("blame wants a project-relative path, as `hird show` lists them");
    }
    let now = Utc::now();
    let scope = ProjectScope::Only(project.to_string());
    let mut lines = 0usize;

    writeln!(out, "{path}")?;

    // Intent: every task that said it would be here, live ones first.
    let declared: Vec<_> = db
        .scopes()
        .declared(&scope, false)?
        .into_iter()
        .filter_map(|task| {
            let via: Vec<&str> = task
                .patterns
                .iter()
                .filter(|p| glob::matches(p, path))
                .map(String::as_str)
                .collect();
            (!via.is_empty()).then(|| {
                let holder = task
                    .holder
                    .as_deref()
                    .map(|h| format!(", {h}"))
                    .unwrap_or_default();
                format!(
                    "  #{:<4} {:<12} {}{holder}   via {}",
                    task.seq,
                    task.status,
                    fmt::truncate(&task.title, 40),
                    via.join(", ")
                )
            })
        })
        .collect();
    if !declared.is_empty() {
        writeln!(out, "declared by")?;
        for line in &declared {
            writeln!(out, "{line}")?;
        }
        lines += declared.len();
    }

    // Reality: every hand the witness saw in it, oldest first.
    let touches = db.witnessed().history_of(project, path)?;
    if !touches.is_empty() {
        writeln!(out, "changed under")?;
        for touch in &touches {
            let round = match touch.round {
                Some(n) => format!(" round {n}"),
                None => String::new(),
            };
            let holder = touch
                .holder
                .as_deref()
                .map(|h| format!(", {h}"))
                .unwrap_or_default();
            writeln!(
                out,
                "  #{:<4} {:<12} {}{round}{holder}   {}, {}",
                touch.seq,
                touch.status,
                fmt::truncate(&touch.title, 40),
                touch.kind,
                fmt::age_phrase(&touch.last_seen, now)
            )?;
        }
        lines += touches.len();
    }

    // Memory: what was learned here, and whether the ground still holds it.
    let anchored = db.footings().anchored_to(project, path)?;
    if !anchored.is_empty() {
        let discovered = config.witness(Path::new(project));
        let ids: Vec<String> = anchored.iter().map(|(a, _)| a.id.clone()).collect();
        let standings = footing::standings(db, config.footing(discovered.as_ref()), project, &ids);
        writeln!(out, "on record")?;
        for (fact, anchor) in &anchored {
            let standing = standings
                .get(&fact.id)
                .map(|s| s.as_str())
                .unwrap_or("unchecked");
            writeln!(out, "  - {}", fmt::truncate(&fact.content, 88))?;
            writeln!(
                out,
                "    {standing}; {} recorded it {}",
                fact.actor,
                fmt::age_phrase(&anchor.at, now)
            )?;
        }
        lines += anchored.len();
    }

    if lines == 0 {
        writeln!(
            out,
            "  nothing on record: no task declared it, the witness never saw it move, \
             and no assertion is anchored to it"
        )?;
    }
    Ok(())
}

/// `hird digest`: the trail since the bookmark, as news.
fn digest_cmd(
    db: &Db,
    scope: &ProjectScope,
    since: Option<&str>,
    peek: bool,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    const BOOKMARK: &str = "digest";
    let now = Utc::now();
    let filter = crate::repo::FeedFilter::default();
    // A bookmark is per project; the every-project view has none, and reads
    // from a window or from the start.
    let mark = match scope {
        ProjectScope::Only(project) => Some(project.as_str()),
        _ => None,
    };
    let (events, window) = match since {
        Some(raw) => {
            let cutoff = parse_when(raw, now)?;
            let events = db.events().after(scope, &filter, &cutoff)?;
            (events, format!("since {}", fmt::age_phrase(&cutoff, now)))
        }
        None => {
            let cursor = match mark {
                Some(project) => db.bookmarks().get(BOOKMARK, project)?,
                None => None,
            };
            let events = db.events().since(scope, &filter, cursor.unwrap_or(0))?;
            let window = match (cursor, events.first()) {
                (Some(_), Some(first)) => {
                    format!("since you last looked, {}", fmt::age_phrase(&first.at, now))
                }
                (Some(_), None) => "since you last looked".to_string(),
                (None, _) => "since the board began".to_string(),
            };
            (events, window)
        }
    };

    let digest = crate::digest::fold(&events);
    if events.is_empty() {
        writeln!(out, "nothing has happened {window}")?;
    } else {
        writeln!(
            out,
            "{} on {} {window}",
            count(digest.events, "event"),
            count(digest.tasks.len(), "task")
        )?;
        for section in digest.render(scope.is_all()) {
            writeln!(out, "\n{section}")?;
        }
    }
    // The bookmark moves on a plain read and stays put on a window or a
    // peek, so `hird digest --since 2h` is a question and `hird digest` is
    // the act of catching up.
    if let (Some(project), None, false, Some(cursor)) = (mark, since, peek, digest.cursor) {
        db.bookmarks().set(BOOKMARK, project, cursor)?;
    }
    Ok(())
}

/// `hird handoff`: the claim brief, as a document.
fn handoff(db: &Db, config: &Config, seq: i64, out: &mut impl Write) -> anyhow::Result<()> {
    let task = db.tasks().get(seq)?;
    let now = Utc::now();
    writeln!(out, "# Task #{}: {}", task.seq, task.title)?;
    writeln!(out)?;
    writeln!(
        out,
        "<!-- hird handoff, {}. Everything the queue would hand an agent on\n\
         claiming this task. Report back through any harness registered with\n\
         hird, or hand the result to whoever can. -->",
        now.format("%Y-%m-%d")
    )?;
    writeln!(out)?;
    let mut facts: Vec<String> = vec![format!("**status** {}", task.status)];
    if let Some(holder) = &task.claimed_by {
        facts.push(format!("**held by** {holder}"));
    }
    if task.priority != 0 {
        facts.push(format!("**priority** {}", task.priority));
    }
    let requires = db.requirements().for_task(seq)?;
    if !requires.is_empty() {
        facts.push(format!("**requires** {}", requires.join(", ")));
    }
    if task.review {
        facts.push("**review** on finishing, by another harness".to_string());
    }
    for recusal in db.recusals().for_task(seq)? {
        facts.push(format!("**recused** {}", recusal.describe()));
    }
    writeln!(out, "{}", facts.join("  \n"))?;

    writeln!(out, "\n## Instructions\n")?;
    if task.body.trim().is_empty() {
        writeln!(out, "_No body beyond the title._")?;
    } else {
        writeln!(out, "{}", task.body.trim())?;
    }

    let (blockers, _) = db.tasks().readiness(seq, config.clearance())?;
    if !blockers.is_empty() {
        writeln!(out, "\n## Still waiting for\n")?;
        for b in &blockers {
            match b.pending_review {
                Some(review) if b.status == Status::Done => writeln!(
                    out,
                    "- #{} {} (done, under review {review})",
                    b.seq, b.title
                )?,
                _ => writeln!(out, "- #{} {} ({})", b.seq, b.title, b.status)?,
            }
        }
    }
    let ground = db.deps().ground(seq)?;
    if !ground.is_empty() {
        writeln!(out, "\n## Builds on\n")?;
        for g in &ground {
            writeln!(
                out,
                "- **#{} {}** — {}",
                g.seq,
                g.title,
                g.standing.describe()
            )?;
            if let Some(result) = g.result.as_deref().filter(|r| !r.trim().is_empty()) {
                writeln!(out, "  {}", result.trim().replace('\n', "\n  "))?;
            }
        }
    }

    let questions = db.questions().for_task(seq)?;
    if !questions.is_empty() {
        writeln!(out, "\n## Questions\n")?;
        for q in &questions {
            writeln!(out, "- **Q** {}", q.question.trim())?;
            match &q.answer {
                Some(a) => writeln!(out, "  **A** {}", a.trim())?,
                None => writeln!(out, "  _unanswered — `hird answer {seq} <ANSWER>`_")?,
            }
        }
    }

    let judged = db.verdicts().for_task(seq)?;
    if let Some(latest) = judged.last() {
        writeln!(out, "\n## Verdict\n")?;
        writeln!(out, "{}", latest.describe())?;
    }

    let patterns = db.scopes().for_task(seq)?;
    let touched = db.witnessed().touched(seq).unwrap_or_default();
    if !patterns.is_empty() || !touched.is_empty() {
        writeln!(out, "\n## Files\n")?;
        if !patterns.is_empty() {
            writeln!(out, "Declared:")?;
            for p in &patterns {
                writeln!(out, "- `{p}`")?;
            }
        }
        if !touched.is_empty() {
            let footprint = db.witnessed().footprint(seq).unwrap_or_default();
            match footprint.describe(task.status.is_active()) {
                Some(sentence) => writeln!(out, "\nAlready moved under this task ({sentence}):")?,
                None => writeln!(out, "\nAlready moved under this task:")?,
            }
            for o in &touched {
                writeln!(out, "- `{}` ({})", o.path, o.kind)?;
            }
        }
        for c in db.witnessed().contention(seq).unwrap_or_default() {
            writeln!(out, "\n> {}", c.describe())?;
        }
    }

    let discovered = config.witness(Path::new(&task.project));
    let recalled = footing::decorate(
        db,
        config.footing(discovered.as_ref()),
        db.recall().for_task(seq, config.recall_limit())?,
    );
    if !recalled.is_empty() {
        writeln!(out, "\n## What earlier work learned\n")?;
        for item in &recalled {
            writeln!(out, "- {}", item.assertion.content.trim())?;
            let mut notes = vec![item.reason.describe()];
            if let Some(why) = item
                .standing
                .as_ref()
                .filter(|s| s.needs_checking())
                .and_then(Standing::describe)
            {
                notes.push(format!("re-check: {why}"));
            }
            if let Some(voices) = &item.corroboration {
                notes.push(voices.clone());
            }
            writeln!(out, "  — {}", notes.join("; "))?;
        }
    }

    writeln!(out, "\n## Reporting back\n")?;
    writeln!(
        out,
        "Through a harness that has hird: `task_claim {seq}`, then `task_complete {seq}` \
         with a result, or `task_release {seq}` with a question. Facts worth keeping go in \
         with `mem_store`, naming the files they were read off."
    )?;
    Ok(())
}

/// `hird replay`: the board as it stood at a past moment.
fn replay(db: &Db, scope: &ProjectScope, when: &str, out: &mut impl Write) -> anyhow::Result<()> {
    let now = Utc::now();
    let cutoff = parse_when(when, now)?;
    let board = db.events().board_at(scope, &cutoff)?;

    // The age is only worth saying when the cutoff is a full instant; a
    // prefix like "2026-08-14" already reads as itself.
    let age = crate::model::parse_ts(&cutoff)
        .map(|_| format!(" — {}", fmt::age_phrase(&cutoff, now)))
        .unwrap_or_default();
    writeln!(out, "the board as of {cutoff}{age}")?;
    if board.is_empty() {
        writeln!(out, "nothing had been filed yet")?;
        return Ok(());
    }
    for task in &board {
        let mut line = format!(
            "#{:<4} {:<11}  {}",
            task.seq,
            task.status,
            fmt::truncate(&task.title, 48)
        );
        if let Some(holder) = &task.holder {
            line.push_str(&format!("  [{holder}]"));
        }
        if task.awaiting_answer {
            line.push_str("  awaits answer");
        }
        if scope.is_all() {
            line.push_str(&format!("  ({})", task.project));
        }
        writeln!(out, "{}", line.trim_end())?;
    }
    Ok(())
}

/// A moment from the command line: an age like `2h`, or an RFC3339 instant —
/// a prefix of one included, since stored timestamps are fixed-width UTC and
/// compare correctly as strings.
pub(crate) fn parse_when(raw: &str, now: chrono::DateTime<Utc>) -> anyhow::Result<String> {
    let raw = raw.trim();
    if let Some(digits) = raw.strip_suffix(['s', 'm', 'h', 'd']) {
        if !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()) {
            let n: i64 = digits.parse()?;
            let delta = match raw.chars().last() {
                Some('s') => chrono::Duration::seconds(n),
                Some('m') => chrono::Duration::minutes(n),
                Some('h') => chrono::Duration::hours(n),
                _ => chrono::Duration::days(n),
            };
            return Ok(crate::model::fmt_ts(now - delta));
        }
    }
    let looks_absolute = raw.len() >= 4
        && raw.starts_with(|c: char| c.is_ascii_digit())
        && raw
            .chars()
            .all(|c| c.is_ascii_digit() || matches!(c, '-' | ':' | 'T' | '.' | 'Z' | '+'));
    if looks_absolute {
        return Ok(raw.to_string());
    }
    anyhow::bail!(
        "replay wants a moment: an RFC3339 UTC instant (\"2026-08-14T10:00\", prefixes \
         welcome) or how long ago (\"90m\", \"2h\", \"3d\"), not {raw:?}"
    )
}

/// `hird plan lint`: the trouble a fileable plan can still carry.
///
/// Everything fatal is already `parse`'s job, and re-litigating it here would
/// let the two drift. What lint reads for is the plan that files cleanly and
/// then disappoints: waves wider on paper than the queue will run them,
/// tasks the collision radar cannot see, reviews that will never exist or
/// that nobody present may claim.
fn lint(db: &Db, project: &str, parsed: &plan::Plan, out: &mut impl Write) -> anyhow::Result<()> {
    let preview = parsed.preview();
    let mut advisories = 0usize;

    writeln!(
        out,
        "plan {:?} parses — {}, {}, at most {} at once",
        parsed.plan,
        count(parsed.tasks.len(), "task"),
        count(preview.waves.len(), "wave"),
        preview.widest()
    )?;

    for collision in &preview.collisions {
        advisories += 1;
        writeln!(out, "collision {}", collision.describe())?;
        writeln!(
            out,
            "          nothing orders them, so the queue hands them out one at a time"
        )?;
    }
    if !preview.unscoped.is_empty() {
        advisories += 1;
        writeln!(out, "unscoped  {}", preview.unscoped.join(", "))?;
        writeln!(
            out,
            "          declaring no files, the queue cannot keep another agent out \
             of what these touch"
        )?;
    }

    // The reviews: work marked `review = true` files one on finishing — but
    // only when there is something to read, and only usefully when a second
    // harness exists to read it.
    let reviewed: Vec<&plan::PlanTask> = parsed.tasks.iter().filter(|t| t.review).collect();
    for task in reviewed.iter().filter(|t| t.paths.is_empty()) {
        advisories += 1;
        writeln!(
            out,
            "review    {} declares no files — if the witness sees nothing move, \
             finishing it files no review",
            task.name
        )?;
    }
    if !reviewed.is_empty() {
        let seen = db
            .events()
            .harnesses_seen(&ProjectScope::Only(project.to_string()))?;
        if seen.len() < 2 {
            advisories += 1;
            let present = match seen.as_slice() {
                [] => "none has acted here yet".to_string(),
                only => format!("this board has only seen {}", only.join(", ")),
            };
            writeln!(
                out,
                "review    a review is refused to the harness that did the work, and \
                 {present} — a second harness is what makes these claimable",
            )?;
        }
    }

    match advisories {
        0 => writeln!(out, "\nnothing to flag; hird plan apply files it")?,
        n => writeln!(out, "\n{}; the plan files either way", count(n, "advisory"))?,
    }
    Ok(())
}

/// `1 task` / `3 tasks`, so the sentence around it does not have to agree.
fn count(n: usize, noun: &str) -> String {
    if n == 1 {
        return format!("{n} {noun}");
    }
    match noun.strip_suffix('y') {
        Some(stem) => format!("{n} {stem}ies"),
        None => format!("{n} {noun}s"),
    }
}

/// `hird recuse`: who must not work a task, and why.
fn recuse(db: &Db, args: &RecuseArgs, out: &mut impl Write) -> anyhow::Result<()> {
    if args.clear {
        let removed = db.recusals().clear(args.seq, ACTOR_CLI)?;
        writeln!(out, "lifted {removed} recusal(s) from task {}", args.seq)?;
        return Ok(());
    }
    for from in &args.from {
        db.recusals()
            .add(args.seq, *from, &args.reason, ACTOR_CLI)?;
    }
    let recusals = db.recusals().for_task(args.seq)?;
    if recusals.is_empty() {
        writeln!(out, "task {} is recused from nothing", args.seq)?;
        return Ok(());
    }
    for recusal in &recusals {
        writeln!(out, "{}", recusal.describe())?;
    }
    Ok(())
}

/// `hird record`: each harness's standing in the verdict record.
fn record(db: &Db, scope: &ProjectScope, out: &mut impl Write) -> anyhow::Result<()> {
    let records = db.verdicts().record(scope)?;
    let workers: Vec<_> = records.iter().filter(|r| r.judged > 0).collect();
    let reviewers: Vec<_> = records
        .iter()
        .filter(|r| r.upheld_given + r.sent_back_given > 0)
        .collect();
    if workers.is_empty() && reviewers.is_empty() {
        writeln!(
            out,
            "no verdicts on record — file work with `hird add --review` and the reviews \
             that finishing it files will deliver them"
        )?;
        return Ok(());
    }
    if !workers.is_empty() {
        writeln!(
            out,
            "{:<14} {:>7} {:>7} {:>10} {:>11}",
            "as worker", "judged", "upheld", "sent back", "first pass"
        )?;
        for r in workers {
            writeln!(
                out,
                "{:<14} {:>7} {:>7} {:>10} {:>11}",
                r.harness,
                r.judged,
                r.upheld,
                r.sent_back,
                format!("{}/{}", r.first_pass, r.tasks_judged)
            )?;
        }
    }
    if !reviewers.is_empty() {
        writeln!(
            out,
            "\n{:<14} {:>7} {:>10}",
            "as reviewer", "upheld", "sent back"
        )?;
        for r in reviewers {
            writeln!(
                out,
                "{:<14} {:>7} {:>10}",
                r.harness, r.upheld_given, r.sent_back_given
            )?;
        }
    }
    Ok(())
}

fn scope_cmd(db: &Db, args: &ScopeArgs, out: &mut impl Write) -> anyhow::Result<()> {
    if args.clear {
        let removed = db.scopes().clear(args.seq, ACTOR_CLI)?;
        writeln!(out, "cleared {removed} pattern(s) from task {}", args.seq)?;
        return Ok(());
    }
    if !args.paths.is_empty() {
        let conflicts =
            db.scopes()
                .declare(args.seq, &args.paths, ACTOR_CLI, OnConflict::Report)?;
        for conflict in &conflicts {
            writeln!(out, "warning: {}", conflict.describe())?;
        }
    }
    let patterns = db.scopes().for_task(args.seq)?;
    if patterns.is_empty() {
        writeln!(out, "task {} declares no files", args.seq)?;
    } else {
        for pattern in patterns {
            writeln!(out, "{pattern}")?;
        }
    }
    Ok(())
}

fn require_cmd(db: &Db, args: &RequireArgs, out: &mut impl Write) -> anyhow::Result<()> {
    if args.clear {
        db.requirements().set(args.seq, &[], ACTOR_CLI)?;
    } else if !args.capabilities.is_empty() {
        db.requirements()
            .set(args.seq, &args.capabilities, ACTOR_CLI)?;
    }
    let required = db.requirements().for_task(args.seq)?;
    if required.is_empty() {
        writeln!(out, "task {} requires no capabilities", args.seq)?;
    } else {
        for capability in required {
            writeln!(out, "{capability}")?;
        }
    }
    Ok(())
}

/// Print the queue as dispatch waves.
///
/// A wave is everything that becomes workable once the previous wave is done,
/// which is the shape a human actually wants to see: not "who points at whom"
/// but "how much of this can run at once, and what is the critical path".
/// Tasks, and the (task, waits-for) edges between them.
type GraphInputs = (Vec<TaskSummary>, Vec<(i64, i64)>);

/// The tasks and edges a graph is drawn from, narrowed to one plan's when
/// asked. The waves are computed over the narrowed set, so a plan's task that
/// waits for work outside the plan reads as workable here; `--json` keeps the
/// queue's own waves, since it exists for readers that want the truth rather
/// than the picture.
fn graph_inputs(db: &Db, scope: &ProjectScope, plan: Option<&str>) -> anyhow::Result<GraphInputs> {
    let mut tasks = db.tasks().list(scope, None)?;
    let mut edges = db.deps().edges(scope)?;
    if let Some(name) = plan {
        let members: std::collections::BTreeSet<i64> = tasks
            .iter()
            .map(|t| t.project.clone())
            .collect::<std::collections::BTreeSet<_>>()
            .into_iter()
            .map(|project| db.plans().origins(&project))
            .collect::<Result<Vec<_>, _>>()?
            .into_iter()
            .flatten()
            .filter(|(_, (p, _))| p == name)
            .map(|(seq, _)| seq)
            .collect();
        if members.is_empty() {
            anyhow::bail!(
                "no task here was filed from plan {name:?}; `hird plan apply` records the \
                 plan a task came from, and `hird plan export` lists the names in use"
            );
        }
        tasks.retain(|t| members.contains(&t.seq));
        edges.retain(|(t, on)| members.contains(t) && members.contains(on));
    }
    Ok((tasks, edges))
}

fn graph(
    db: &Db,
    scope: &ProjectScope,
    plan: Option<&str>,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let (tasks, edges) = graph_inputs(db, scope, plan)?;
    let waves = dispatch_waves(&tasks, &edges);
    let questions = db.questions().unanswered_map(scope)?;
    // "Workable now" is not true while a recess stands, and this is the view
    // that says it — so the recess speaks first.
    if let ProjectScope::Only(project) = scope {
        if let Some(recess) = db.recesses().current(project)? {
            writeln!(out, "{}", recess_banner(&recess, Utc::now()))?;
        }
    }
    if waves.is_empty() {
        writeln!(out, "no unfinished tasks")?;
        return Ok(());
    }

    let waiting: BTreeMap<i64, Vec<i64>> = edges.iter().fold(BTreeMap::new(), |mut acc, (t, d)| {
        acc.entry(*t).or_default().push(*d);
        acc
    });
    let by_seq: BTreeMap<i64, &TaskSummary> = tasks.iter().map(|t| (t.seq, t)).collect();

    for (index, wave) in waves.iter().enumerate() {
        let label = match index {
            0 => "wave 1  (workable now)".to_string(),
            n => format!("wave {}  (after wave {n})", n + 1),
        };
        writeln!(out, "{label}")?;
        for seq in wave {
            let Some(task) = by_seq.get(seq) else {
                continue;
            };
            let mut line = format!(
                "  #{:<4} {:<12} {}",
                task.seq,
                task.status,
                fmt::truncate(&task.title, 44)
            );
            if let Some(needs) = waiting.get(seq) {
                let listed = needs
                    .iter()
                    .map(|s| format!("#{s}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                line.push_str(&format!("   waits for {listed}"));
            }
            if questions.contains_key(seq) {
                line.push_str("   awaits answer");
            }
            writeln!(out, "{line}")?;
        }
    }
    Ok(())
}

/// Who is working what, and where two of them are in the same files.
fn agents(db: &Db, scope: &ProjectScope, out: &mut impl Write) -> anyhow::Result<()> {
    db.tasks().sweep_leases()?;
    let tasks = db.tasks().list(scope, None)?;
    let live: Vec<&TaskSummary> = tasks.iter().filter(|t| t.status.is_active()).collect();
    if live.is_empty() {
        writeln!(out, "no agent is working anything right now")?;
        return Ok(());
    }

    let declared = db.scopes().declared(scope, true)?;
    let scopes: BTreeMap<i64, Vec<String>> =
        declared.into_iter().map(|s| (s.seq, s.patterns)).collect();
    let now = Utc::now();

    for task in &live {
        let holder = task.claimed_by.as_deref().unwrap_or("unknown");
        let lease = task
            .lease_expires_at
            .as_deref()
            .map(|e| format!("  {}", fmt::lease_remaining(e, now)))
            .unwrap_or_default();
        writeln!(
            out,
            "{holder}  #{} {}  {}{lease}",
            task.seq,
            task.status,
            fmt::truncate(&task.title, 40)
        )?;
        match scopes.get(&task.seq) {
            Some(patterns) => writeln!(out, "    files  {}", patterns.join(", "))?,
            None => writeln!(out, "    files  (undeclared)")?,
        }
        // What was said, then what happened. Kept on separate lines because
        // the gap between them is the most useful thing on this screen.
        let seen = db.witnessed().touched(task.seq).unwrap_or_default();
        if !seen.is_empty() {
            let listed: Vec<String> = seen.iter().map(|o| o.path.clone()).collect();
            writeln!(out, "    moved  {}", listed.join(", "))?;
        } else if db.witnessed().footprint(task.seq).unwrap_or_default() == Footprint::ReadOnly {
            // An agent that has been in the code for twenty minutes and moved
            // nothing is reading, or is stuck. Either way it is worth a line,
            // and a blank space where the line would be says neither.
            writeln!(out, "    moved  nothing yet")?;
        }
        for other in &live {
            // Both directions: an agent reading this wants to see who is in
            // its way, not only who it is in the way of.
            if other.seq == task.seq {
                continue;
            }
            for overlap in overlapping(&scopes, task.seq, other.seq) {
                writeln!(
                    out,
                    "    !!     {overlap} also claimed by {} on #{}",
                    other.claimed_by.as_deref().unwrap_or("unknown"),
                    other.seq
                )?;
            }
        }
        for found in db.witnessed().contention(task.seq).unwrap_or_default() {
            writeln!(out, "    !!!    {}", found.describe())?;
        }
        // Ground that moved while the agent was on it: a dependency that
        // stopped being done — sent back, reopened, cancelled — after this
        // task was let through. The agent hears at its next check-in; the
        // human deserves the same line without waiting for one.
        for shifted in db.deps().shifted(task.seq).unwrap_or_default() {
            writeln!(out, "    !!!    {}", shifted.describe())?;
        }
    }
    Ok(())
}

/// Patterns from `a` that can name the same path as something in `b`.
fn overlapping(scopes: &BTreeMap<i64, Vec<String>>, a: i64, b: i64) -> Vec<String> {
    let (Some(ours), Some(theirs)) = (scopes.get(&a), scopes.get(&b)) else {
        return Vec::new();
    };
    ours.iter()
        .filter(|pattern| theirs.iter().any(|other| glob::intersects(pattern, other)))
        .cloned()
        .collect()
}

/// Read a file argument, or standard input when it is "-".
fn read_text(path: &Path) -> anyhow::Result<String> {
    if path == Path::new("-") {
        let mut buf = String::new();
        std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)
            .context("reading from stdin")?;
        return Ok(buf);
    }
    std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))
}

fn ls(
    db: &Db,
    project: &str,
    config: &Config,
    args: &LsArgs,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let status = match args
        .status
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        Some(raw) => Some(raw.parse::<Status>()?),
        None => None,
    };
    let scope = ProjectScope::resolve(project, config.all_projects(Some(args.all_projects)));
    let tasks = db.tasks().list(&scope, status)?;

    // The recess leads the listing, because every row below it is a row
    // nobody is being handed. Only in the single-project view: a recess is
    // per project, and the all-projects listing has no one queue to speak for.
    if !scope.is_all() {
        if let Some(recess) = db.recesses().current(project)? {
            writeln!(out, "{}", recess_banner(&recess, Utc::now()))?;
        }
    }
    if tasks.is_empty() {
        writeln!(out, "no tasks")?;
        return Ok(());
    }
    let unmet = db.deps().unmet_map(&scope, config.clearance())?;
    let questions = db.questions().unanswered_map(&scope)?;
    // What each task did to the tree, which the row prints as one word. A
    // failure here costs the listing a column, not the listing.
    let footprints = db.witnessed().footprints(&scope).unwrap_or_default();
    let now = Utc::now();
    let width = tasks
        .iter()
        .map(|t| t.seq.to_string().len())
        .max()
        .unwrap_or(1);
    for task in &tasks {
        let blocked = unmet.get(&task.seq).map(Vec::as_slice).unwrap_or(&[]);
        let question = questions.get(&task.seq).map(|q| q.question.as_str());
        let footprint = footprints.get(&task.seq).copied().unwrap_or_default();
        writeln!(
            out,
            "{}",
            ls_line(
                task,
                width,
                scope.is_all(),
                now,
                blocked,
                question,
                footprint,
            )
        )?;
    }
    Ok(())
}

/// One `hird ls` row. Extracted so its layout can be tested directly.
fn ls_line(
    task: &TaskSummary,
    seq_width: usize,
    show_project: bool,
    now: chrono::DateTime<Utc>,
    blocked_by: &[i64],
    awaiting_answer: Option<&str>,
    footprint: Footprint,
) -> String {
    let mut line = format!(
        "#{seq:<width$}  {status:<11}  {title}",
        seq = task.seq,
        width = seq_width,
        status = task.status,
        title = fmt::truncate(&task.title, 48),
    );
    if let Some(holder) = &task.claimed_by {
        line.push_str(&format!("  [{holder}]"));
        if let Some(expires) = &task.lease_expires_at {
            line.push_str(&format!(" {}", fmt::lease_remaining(expires, now)));
        }
    }
    if !blocked_by.is_empty() {
        let listed = blocked_by
            .iter()
            .map(|s| format!("#{s}"))
            .collect::<Vec<_>>()
            .join(",");
        line.push_str(&format!("  waits {listed}"));
    }
    if awaiting_answer.is_some() {
        line.push_str("  awaits answer");
    }
    if task.priority != 0 {
        line.push_str(&format!("  p{}", task.priority));
    }
    if !task.requirements.is_empty() {
        line.push_str(&format!("  requires {}", task.requirements.join(",")));
    }
    // Whether the work left a mark. A task nobody watched says nothing here,
    // because "read-only" and "hird was not looking" are opposite claims and
    // only one of them is this column's to make.
    if let Some(label) = footprint.label(task.status.is_active()) {
        line.push_str(&format!("  {label}"));
    }
    if show_project {
        line.push_str(&format!("  ({})", task.project));
    }
    line
}

/// What the queue would tell an agent about this task before it starts.
///
/// The same view an agent gets on `task_claim`, so a human can see what their
/// swarm is being told — and notice when it is telling them something stale.
fn recall(
    db: &Db,
    config: &Config,
    project: &str,
    seq: i64,
    limit: usize,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let discovered = config.witness(Path::new(project));
    let recalled = footing::decorate(
        db,
        config.footing(discovered.as_ref()),
        db.recall().for_task(seq, limit)?,
    );
    if recalled.is_empty() {
        writeln!(out, "nothing recorded so far touches task {seq}")?;
        return Ok(());
    }
    let now = Utc::now();
    for item in recalled {
        writeln!(out, "{}", item.assertion.content)?;
        writeln!(
            out,
            "    {}  ({}, {})",
            item.reason.describe(),
            item.assertion.actor,
            fmt::age_phrase(&item.assertion.created_at, now)
        )?;
        // This is exactly what the agent will be handed on claiming, so the
        // human reading it should see the same hedge the agent will.
        if let Some(why) = item
            .standing
            .as_ref()
            .filter(|s| s.needs_checking())
            .and_then(Standing::describe)
        {
            writeln!(out, "    {why}")?;
        }
        if let Some(voices) = &item.corroboration {
            writeln!(out, "    {voices}")?;
        }
    }
    Ok(())
}

/// The uncommitted diff of what moved under a task, off the kept versions.
fn diff(
    db: &Db,
    seq: i64,
    only: Option<&str>,
    tenure: Option<i64>,
    config: &Config,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let task = db.tasks().get(seq)?;
    let Some(witness) = config.witness(Path::new(&task.project)) else {
        anyhow::bail!(
            "hird is not watching {} — no git repository there, or the witness is off — \
             so there is no diff to show",
            task.project
        );
    };
    // Bring the record up to the tree as it stands first: a diff that stops
    // at the last heartbeat shows less than the disk already knows. An
    // archived round is already over, so there is nothing to bring up to date.
    let mut shown = match tenure {
        Some(n) => exhibit::assemble_tenure(db, &witness, seq, n)?,
        None => {
            let _ = witness::sweep(db, &witness, &task.project, ACTOR_CLI);
            exhibit::assemble(db, &witness, seq)?
        }
    };
    let round = tenure
        .map(|n| format!(" in holding {n}"))
        .unwrap_or_default();
    if let Some(only) = only {
        shown.retain(|e| e.path == only);
        if shown.is_empty() {
            writeln!(
                out,
                "the witness saw nothing move at {only} under task {seq}{round}"
            )?;
            return Ok(());
        }
    }
    let text = exhibit::render(&shown);
    if text.trim().is_empty() {
        writeln!(
            out,
            "nothing moved under task {seq}{round} while the witness was watching"
        )?;
        return Ok(());
    }
    write!(out, "{text}")?;
    Ok(())
}

/// Recover a version of a file as it stood under a task.
#[allow(clippy::too_many_arguments)]
fn salvage(
    db: &Db,
    seq: i64,
    path: &str,
    baseline: bool,
    tenure: Option<i64>,
    to: Option<&Path>,
    force: bool,
    config: &Config,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let task = db.tasks().get(seq)?;
    let Some(witness) = config.witness(Path::new(&task.project)) else {
        anyhow::bail!(
            "hird is not watching {} — no git repository there, or the witness is off — \
             so nothing was kept to salvage",
            task.project
        );
    };
    if tenure.is_none() {
        let _ = witness::sweep(db, &witness, &task.project, ACTOR_CLI);
    }
    let bytes = exhibit::salvage(db, &witness, seq, path, baseline, tenure)?;
    let which = match (baseline, tenure) {
        (true, Some(n)) => format!("as it stood when holding {n} began"),
        (false, Some(n)) => format!("as the witness last saw it under holding {n}"),
        (true, None) => "as it stood when the task was claimed".to_string(),
        (false, None) => "as the witness last saw it under the task".to_string(),
    };
    match to {
        Some(dest) => {
            if dest.exists() && !force {
                anyhow::bail!(
                    "{} already exists; --force to say you meant to overwrite it",
                    dest.display()
                );
            }
            if let Some(parent) = dest.parent().filter(|p| !p.as_os_str().is_empty()) {
                std::fs::create_dir_all(parent)
                    .with_context(|| format!("creating {}", parent.display()))?;
            }
            std::fs::write(dest, &bytes).with_context(|| format!("writing {}", dest.display()))?;
            writeln!(
                out,
                "salvaged {path} {which} — {} bytes into {}",
                bytes.len(),
                dest.display()
            )?;
        }
        // To stdout raw, so it can be redirected or piped into a pager —
        // salvage is recovery, and recovery wants the bytes, not a report.
        None => out.write_all(&bytes)?,
    }
    Ok(())
}

pub(crate) fn show(db: &Db, seq: i64, config: &Config, out: &mut impl Write) -> anyhow::Result<()> {
    let task = db.tasks().get(seq)?;
    let now = Utc::now();

    writeln!(out, "#{} {}", task.seq, task.title)?;
    writeln!(out, "status    {}", task.status)?;
    writeln!(out, "project   {}", task.project)?;
    if task.priority != 0 {
        writeln!(out, "priority  {}", task.priority)?;
    }
    if let Some(holder) = &task.claimed_by {
        let lease = task
            .lease_expires_at
            .as_deref()
            .map(|e| format!(" ({})", fmt::lease_remaining(e, now)))
            .unwrap_or_default();
        writeln!(out, "held by   {holder}{lease}")?;
    }
    writeln!(out, "created   {}", fmt::age_phrase(&task.created_at, now))?;

    let (blockers, conflicts) = db.tasks().readiness(seq, config.clearance())?;
    if !blockers.is_empty() {
        let listed = blockers
            .iter()
            .map(|b| match b.pending_review {
                // Only reachable under `under_review = "holds"`: the work is
                // done, and what the dependent waits on is the verdict.
                Some(review) if b.status == Status::Done => {
                    format!("#{} (done, under review {review})", b.seq)
                }
                _ => format!("#{} ({})", b.seq, b.status),
            })
            .collect::<Vec<_>>()
            .join(", ");
        writeln!(out, "waits for {listed}")?;
    }
    for question in db.questions().for_task(seq)? {
        writeln!(out, "question  {}", question.question)?;
        match question.answer {
            Some(answer) => writeln!(out, "answer    {answer}")?,
            None => writeln!(out, "awaits    hird answer {seq} <ANSWER>")?,
        }
    }
    // The ground under the task: what the work it builds on says for itself.
    // One line per finished dependency — standing first, then as much of its
    // result as a line can hold.
    for ground in db.deps().ground(seq)? {
        let result = ground
            .result
            .as_deref()
            .map(|r| format!(" — {}", fmt::truncate(r, 60)))
            .unwrap_or_default();
        writeln!(out, "built on  {}{result}", ground.label())?;
    }
    let dependents = db.deps().dependents(seq)?;
    if !dependents.is_empty() {
        let listed = dependents
            .iter()
            .map(|b| format!("#{}", b.seq))
            .collect::<Vec<_>>()
            .join(", ");
        writeln!(out, "blocks    {listed}")?;
    }
    let patterns = db.scopes().for_task(seq)?;
    if !patterns.is_empty() {
        writeln!(out, "files     {}", patterns.join(", "))?;
    }
    let required = db.requirements().for_task(seq)?;
    if !required.is_empty() {
        writeln!(out, "requires  {}", required.join(", "))?;
    }
    if task.review {
        writeln!(out, "review    on finishing, by another harness")?;
    }
    for recusal in db.recusals().for_task(seq)? {
        writeln!(out, "recused   {}", recusal.describe())?;
    }
    // Two sides of the same table: what reviews concluded about this work,
    // and — when this task is itself a review — what it concluded.
    let judged = db.verdicts().for_task(seq)?;
    if let Some(latest) = judged.last() {
        let rounds = if judged.len() > 1 {
            format!(", verdict {} on this work", judged.len())
        } else {
            String::new()
        };
        writeln!(out, "verdict   {}{rounds}", latest.describe())?;
    }
    for delivered in db.verdicts().of_review(seq)? {
        writeln!(
            out,
            "verdict   {} on task {}, delivered by this review",
            delivered.verdict, delivered.task_seq
        )?;
    }
    for conflict in &conflicts {
        writeln!(out, "overlap   {}", conflict.describe())?;
    }
    // `files` is what somebody said would happen; `changed` is what the
    // working tree says did. On a finished task this is the evidence behind
    // the result line, and it was not written by the agent that wrote it.
    //
    // The headline goes first because it is the part a list of paths cannot
    // say: no paths means the task read and did not write, and it means that
    // only where hird was watching closely enough to know.
    let footprint = db.witnessed().footprint(seq).unwrap_or_default();
    if let Some(sentence) = footprint.describe(task.status.is_active()) {
        writeln!(out, "changed   {sentence}")?;
    }
    for observed in db.witnessed().touched(seq).unwrap_or_default() {
        writeln!(out, "          {}", observed.describe())?;
    }
    for found in db.witnessed().contention(seq).unwrap_or_default() {
        writeln!(out, "contended {}", found.describe())?;
    }
    // Earlier holdings, where the task has changed hands: who had it, how
    // that ended, what moved under them. `changed` above is the current
    // record; these are the rounds it replaced, still readable with
    // `hird diff <seq> --tenure <n>`.
    for held in db.witnessed().tenures(seq).unwrap_or_default() {
        writeln!(out, "held      {}", held.label())?;
    }

    if !task.body.trim().is_empty() {
        writeln!(out, "\n{}", task.body.trim_end())?;
    }
    if let Some(result) = &task.result {
        writeln!(out, "\nresult: {result}")?;
    }

    let events = db.tasks().events(&task.id, 20)?;
    if !events.is_empty() {
        writeln!(out, "\nhistory")?;
        for event in events {
            let detail = if event.detail.is_empty() {
                String::new()
            } else {
                format!("  {}", fmt::truncate(&event.detail, 72))
            };
            writeln!(
                out,
                "  {:>9}  {:<13} {}{}",
                fmt::age_phrase(&event.at, now),
                event.kind,
                event.actor,
                detail
            )?;
        }
    }

    let learned = db.memory().for_task(&task.id)?;
    if !learned.is_empty() {
        let discovered = config.witness(Path::new(&task.project));
        let ids: Vec<String> = learned.iter().map(|a| a.id.clone()).collect();
        let standings =
            footing::standings(db, config.footing(discovered.as_ref()), &task.project, &ids);
        writeln!(out, "\nassertions recorded on this task")?;
        for assertion in learned {
            writeln!(out, "  - {}", fmt::truncate(&assertion.content, 88))?;
            if let Some(why) = standings
                .get(&assertion.id)
                .filter(|s| s.needs_checking())
                .and_then(Standing::describe)
            {
                writeln!(out, "    {why}")?;
            }
        }
    }

    // Only what came from elsewhere: this task's own assertions are listed
    // above, and printing them twice would say nothing new.
    let elsewhere: Vec<_> = db
        .recall()
        .for_task(seq, config.recall_limit())?
        .into_iter()
        .filter(|r| r.reason != crate::repo::RecallReason::SameTask)
        .collect();
    if !elsewhere.is_empty() {
        writeln!(out, "\nrecalled from earlier work")?;
        for item in elsewhere {
            writeln!(out, "  - {}", fmt::truncate(&item.assertion.content, 88))?;
            writeln!(out, "    {}", item.reason.describe())?;
        }
    }
    Ok(())
}

/// `hird why`: the claim gates, run against one task and answered out loud.
///
/// Every check `task_claim` and `task_next` apply, in the order they apply
/// them, each reported rather than silently folded into an empty hand. The
/// verdict comes first — a human asking *why* wants the answer before the
/// evidence — and every line after it is one gate with something to say.
pub(crate) fn why(db: &Db, seq: i64, config: &Config, out: &mut impl Write) -> anyhow::Result<()> {
    // Readiness sweeps leases first, exactly as a claim would: a task whose
    // holder went quiet is open again by the time this answers.
    let (blockers, conflicts) = db.tasks().readiness(seq, config.clearance())?;
    let task = db.tasks().get(seq)?;
    let now = Utc::now();
    let question = db.questions().unanswered(seq)?;
    let recusals: Vec<_> = db
        .recusals()
        .for_task(seq)?
        .into_iter()
        // A recusal on work nobody has done bars nobody yet; `hird show`
        // lists those, but they are not part of why a claim would fail now.
        .filter(|r| r.worker.is_some())
        .collect();
    let required = db.requirements().for_task(seq)?;
    let refuses = config.on_conflict() == crate::repo::OnConflict::Refuse;

    writeln!(out, "#{} {}", task.seq, task.title)?;
    writeln!(out, "status    {}", task.status)?;

    // A lease or a terminal status answers the question by itself.
    if task.status.is_active() {
        let holder = task.claimed_by.as_deref().unwrap_or("?");
        let lease = task
            .lease_expires_at
            .as_deref()
            .map(|e| format!(", {}", fmt::lease_remaining(e, now)))
            .unwrap_or_default();
        writeln!(out, "claimable no — held by {holder}{lease}")?;
        return Ok(());
    }
    if task.status.is_terminal() {
        writeln!(
            out,
            "claimable no — {}; hird reopen {seq} returns it to the pool",
            task.status
        )?;
        return Ok(());
    }

    // What refuses the claim outright, in gate order.
    let mut stoppers: Vec<String> = Vec::new();
    let recess = db.recesses().current(&task.project)?;
    if recess.is_some() {
        stoppers.push("hird resume — the queue is in recess".to_string());
    }
    if question.is_some() {
        stoppers.push("an answer".to_string());
    }
    if !blockers.is_empty() {
        // The one distinction dispatch makes inside "blocked": work that is
        // all done but for a verdict is held, not waiting on hands.
        let verdicts: Vec<String> = blockers
            .iter()
            .filter(|b| b.status == Status::Done)
            .filter_map(|b| b.pending_review.map(|r| format!("#{r}")))
            .collect();
        let unfinished: Vec<String> = blockers
            .iter()
            .filter(|b| !(b.status == Status::Done && b.pending_review.is_some()))
            .map(|b| format!("#{}", b.seq))
            .collect();
        if !unfinished.is_empty() {
            stoppers.push(unfinished.join(", "));
        }
        if !verdicts.is_empty() {
            stoppers.push(format!("the verdict of review {}", verdicts.join(", ")));
        }
    }
    if refuses && !conflicts.is_empty() {
        stoppers.push("the overlap below to clear".to_string());
    }

    // What narrows who may claim without stopping everyone.
    let mut caveats: Vec<String> = Vec::new();
    if !recusals.is_empty() {
        let barred: Vec<&str> = recusals
            .iter()
            .filter_map(|r| r.worker.as_deref())
            .map(crate::identity::actor_harness)
            .collect();
        caveats.push(format!("not by {}", barred.join(" or ")));
    }
    if !required.is_empty() {
        caveats.push(format!(
            "only by a harness advertising {}",
            required.join(", ")
        ));
    }
    if !refuses && !conflicts.is_empty() && config.avoid_conflicts(None) {
        caveats.push(
            "task_next passes it over while the overlap lives; claiming it by number still works"
                .to_string(),
        );
    }

    if stoppers.is_empty() {
        let trailing = if caveats.is_empty() {
            String::new()
        } else {
            format!(" — {}", caveats.join("; "))
        };
        writeln!(out, "claimable yes{trailing}")?;
    } else {
        writeln!(out, "claimable no — waiting on {}", stoppers.join(" and "))?;
        for caveat in &caveats {
            writeln!(out, "and then   {caveat}")?;
        }
    }

    // The evidence behind the verdict, one gate per line.
    if let Some(recess) = &recess {
        writeln!(
            out,
            "recess    the human stood this queue down{}, {}",
            recess.quoted_reason(),
            fmt::age_phrase(&recess.at, now)
        )?;
    }
    if let Some(question) = question {
        writeln!(out, "awaits    {}", question.question)?;
        writeln!(
            out,
            "          asked by {} {} — hird answer {seq} <ANSWER>",
            question.asked_by,
            fmt::age_phrase(&question.asked_at, now)
        )?;
    }
    if !blockers.is_empty() {
        let listed = blockers
            .iter()
            .map(|b| match b.pending_review {
                Some(review) if b.status == Status::Done => {
                    format!("#{} (done, under review {review})", b.seq)
                }
                _ => format!("#{} ({})", b.seq, b.status),
            })
            .collect::<Vec<_>>()
            .join(", ");
        writeln!(out, "waits for {listed}")?;
    }
    for recusal in &recusals {
        writeln!(out, "recused   {}", recusal.describe())?;
    }
    if !required.is_empty() {
        writeln!(out, "requires  {}", required.join(", "))?;
    }
    for conflict in &conflicts {
        writeln!(out, "overlap   {}", conflict.describe())?;
    }
    if refuses && !conflicts.is_empty() {
        writeln!(
            out,
            "          path_conflicts = \"refuse\": a claim is rejected while the overlap lives"
        )?;
    }
    Ok(())
}

fn mem(
    db: &Db,
    project: &str,
    config: &Config,
    cmd: &MemCommand,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    let discovered = config.witness(Path::new(project));
    let witness = config.footing(discovered.as_ref());
    match cmd {
        MemCommand::Add {
            content,
            tags,
            task,
            paths,
        } => {
            let recorded = db.memory().record(NewAssertion {
                project,
                content,
                tags,
                actor: ACTOR_CLI,
                task_seq: *task,
            })?;
            let ground =
                footing::ground(db, *task, Some(paths.as_slice()).filter(|p| !p.is_empty()));
            let anchored = footing::anchor(db, witness, &recorded.assertion().id, &ground)?;
            writeln!(out, "{}", recorded.assertion().id)?;
            if recorded.was_affirmed() {
                writeln!(
                    out,
                    "  already on record — affirmed, not duplicated{}",
                    if anchored.is_empty() {
                        String::new()
                    } else {
                        " and re-anchored".to_string()
                    }
                )?;
            }
            if !anchored.is_empty() {
                let paths: Vec<&str> = anchored.iter().map(|a| a.path.as_str()).collect();
                writeln!(out, "  anchored to {}", paths.join(", "))?;
            }
            Ok(())
        }
        MemCommand::Standing {
            shaky,
            all_projects,
        } => {
            let scope = ProjectScope::resolve(project, config.all_projects(Some(*all_projects)));
            standing(db, config, witness, &scope, *shaky, out)
        }
        MemCommand::Export { path, firm } => {
            mem_export(db, project, witness, path.as_deref(), *firm, out)
        }
        MemCommand::Search {
            query,
            limit,
            all_projects,
            include_superseded,
        } => {
            let scope = ProjectScope::resolve(project, config.all_projects(Some(*all_projects)));
            let hits = db.memory().search(
                &MemoryQuery::new(query, scope.clone())
                    .limit((*limit).clamp(1, 500))
                    .include_superseded(*include_superseded),
            )?;
            if hits.is_empty() {
                writeln!(out, "no assertions")?;
                return Ok(());
            }
            let now = Utc::now();
            let ids: Vec<String> = hits.iter().map(|a| a.id.clone()).collect();
            let standings = footing::standings(db, witness, project, &ids);
            for assertion in hits {
                let standing = standings.get(&assertion.id);
                let mut meta = vec![
                    assertion.actor.clone(),
                    fmt::age_phrase(&assertion.created_at, now),
                ];
                if !assertion.tags.is_empty() {
                    meta.push(format!("#{}", assertion.tags.replace(',', " #")));
                }
                if assertion.superseded_by.is_some() {
                    meta.push("superseded".to_string());
                }
                if let Some(standing) = standing.filter(|s| **s != Standing::Unanchored) {
                    meta.push(standing.as_str().to_string());
                }
                if scope.is_all() {
                    meta.push(assertion.project.clone());
                }
                writeln!(out, "{}", assertion.content)?;
                writeln!(out, "    {}  {}", assertion.id, meta.join("  "))?;
                // Only the ones worth acting on explain themselves. A line
                // saying "unchanged" under every row is how a reader learns to
                // skip the line under the row that says otherwise.
                if let Some(why) = standing
                    .filter(|s| s.needs_checking())
                    .and_then(|s| s.describe())
                {
                    writeln!(out, "    {why}")?;
                }
            }
            Ok(())
        }
    }
}

/// `hird mem standing`: what the memory still stands on.
///
/// Deciding a standing means resolving paths against a working tree, and each
/// project has its own — so with `--all-projects` this discovers a witness per
/// project rather than measuring everybody's files against the checkout the
/// command happened to be run from.
fn standing(
    db: &Db,
    config: &Config,
    witness: Option<&witness::Witness>,
    scope: &ProjectScope,
    shaky_only: bool,
    out: &mut impl Write,
) -> anyhow::Result<()> {
    if witness.is_none() && !scope.is_all() {
        writeln!(
            out,
            "no footing here: assertions are only anchored to files in a git checkout \
             with `memory_footing` on"
        )?;
        return Ok(());
    }
    let anchored = db.footings().anchored(scope)?;
    if anchored.is_empty() {
        writeln!(out, "no anchored assertions")?;
        return Ok(());
    }

    let now = Utc::now();
    let mut by_project: BTreeMap<&str, Vec<String>> = BTreeMap::new();
    for assertion in &anchored {
        by_project
            .entry(assertion.project.as_str())
            .or_default()
            .push(assertion.id.clone());
    }
    let mut standings: BTreeMap<String, Standing> = BTreeMap::new();
    for (project, ids) in by_project {
        let discovered = config.witness(Path::new(project));
        standings.extend(footing::standings(
            db,
            config.footing(discovered.as_ref()),
            project,
            &ids,
        ));
    }
    let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
    let mut shown = 0usize;

    for assertion in &anchored {
        let standing = standings
            .get(&assertion.id)
            .cloned()
            .unwrap_or(Standing::Unanchored);
        *counts.entry(standing.as_str()).or_default() += 1;
        if shaky_only && !standing.needs_checking() {
            continue;
        }
        shown += 1;
        writeln!(
            out,
            "{:<9} {}",
            standing.as_str(),
            fmt::truncate(&assertion.content, 78)
        )?;
        let mut meta = vec![
            assertion.actor.clone(),
            fmt::age_phrase(&assertion.created_at, now),
        ];
        if scope.is_all() {
            meta.push(assertion.project.clone());
        }
        writeln!(out, "    {}  {}", assertion.id, meta.join("  "))?;
        writeln!(out, "    {}", standing.paths().join(", "))?;
        if let Some(why) = standing.describe().filter(|_| standing.needs_checking()) {
            writeln!(out, "    {why}")?;
        }
        if let Some(voices) = footing::corroboration(db, assertion) {
            writeln!(out, "    {voices}")?;
        }
    }

    if shown == 0 {
        writeln!(
            out,
            "nothing shaky: every anchored assertion still checks out"
        )?;
    }
    let summary: Vec<String> = counts
        .iter()
        .map(|(label, n)| format!("{n} {label}"))
        .collect();
    writeln!(out, "\n{} anchored: {}", anchored.len(), summary.join(", "))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    const PROJECT: &str = "/tmp/project";

    fn now() -> chrono::DateTime<Utc> {
        DateTime::from_timestamp(1_800_000_000, 0).unwrap()
    }
    use chrono::DateTime;

    fn summary(seq: i64, status: Status) -> TaskSummary {
        TaskSummary {
            seq,
            project: PROJECT.into(),
            title: "write the parser".into(),
            status,
            priority: 0,
            claimed_by: None,
            lease_expires_at: None,
            updated_at: crate::model::fmt_ts(now()),
            requirements: Vec::new(),
        }
    }

    #[test]
    fn the_command_tree_parses() {
        Cli::command().debug_assert();
    }

    #[test]
    fn ls_rows_line_up_and_omit_empty_columns() {
        let line = ls_line(
            &summary(7, Status::Open),
            2,
            false,
            now(),
            &[],
            None,
            Footprint::Unwatched,
        );
        assert_eq!(line, "#7   open         write the parser");
    }

    #[test]
    fn ls_rows_show_the_holder_and_lease_countdown() {
        let mut task = summary(7, Status::Claimed);
        task.claimed_by = Some("codex:9f2c".into());
        task.lease_expires_at = Some(crate::model::fmt_ts(now() + chrono::Duration::minutes(12)));

        let line = ls_line(&task, 1, false, now(), &[], None, Footprint::Unwatched);
        assert!(line.contains("[codex:9f2c] 12m left"), "{line}");
    }

    #[test]
    fn ls_rows_show_priority_and_project_only_when_relevant() {
        let mut task = summary(7, Status::Open);
        task.priority = 5;
        assert!(ls_line(&task, 1, false, now(), &[], None, Footprint::Unwatched).ends_with("  p5"));
        assert!(
            ls_line(&task, 1, true, now(), &[], None, Footprint::Unwatched)
                .ends_with(&format!("({PROJECT})"))
        );
    }

    #[test]
    fn add_body_flags_are_mutually_exclusive() {
        let err = Cli::try_parse_from(["hird", "add", "t", "--body", "x", "--body-file", "y"])
            .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn negative_priorities_parse() {
        let cli = Cli::try_parse_from(["hird", "add", "t", "--priority", "-3"]).unwrap();
        match cli.command {
            Some(Command::Add(args)) => assert_eq!(args.priority, -3),
            other => panic!("parsed as {other:?}"),
        }
    }

    #[test]
    fn list_is_an_alias_for_ls() {
        assert!(matches!(
            Cli::try_parse_from(["hird", "list"]).unwrap().command,
            Some(Command::Ls(_))
        ));
    }

    #[test]
    fn dependencies_can_be_given_as_a_list_or_repeated() {
        let comma = Cli::try_parse_from(["hird", "add", "t", "--needs", "3,4"]).unwrap();
        let repeated =
            Cli::try_parse_from(["hird", "add", "t", "--needs", "3", "--needs", "4"]).unwrap();
        for cli in [comma, repeated] {
            match cli.command {
                Some(Command::Add(args)) => assert_eq!(args.needs, vec![3, 4]),
                other => panic!("parsed as {other:?}"),
            }
        }
    }

    #[test]
    fn paths_are_repeatable_and_kept_verbatim_for_normalization() {
        let cli = Cli::try_parse_from(["hird", "add", "t", "--path", "src/**", "--path", "tests/"])
            .unwrap();
        match cli.command {
            Some(Command::Add(args)) => assert_eq!(args.paths, vec!["src/**", "tests/"]),
            other => panic!("parsed as {other:?}"),
        }
    }

    #[test]
    fn a_plan_is_applied_from_a_file_and_dry_run_is_opt_in() {
        let cli = Cli::try_parse_from(["hird", "plan", "apply", "plan.toml"]).unwrap();
        match cli.command {
            Some(Command::Plan(PlanCommand::Apply { file, dry_run, .. })) => {
                assert_eq!(file, PathBuf::from("plan.toml"));
                assert!(!dry_run);
            }
            other => panic!("parsed as {other:?}"),
        }
        let dry = Cli::try_parse_from(["hird", "plan", "apply", "-", "--dry-run"]).unwrap();
        match dry.command {
            Some(Command::Plan(PlanCommand::Apply { file, dry_run, .. })) => {
                assert_eq!(file, PathBuf::from("-"));
                assert!(dry_run);
            }
            other => panic!("parsed as {other:?}"),
        }
    }

    #[test]
    fn counted_nouns_agree_with_their_number() {
        assert_eq!(count(1, "task"), "1 task");
        assert_eq!(count(0, "task"), "0 tasks");
        assert_eq!(count(3, "wave"), "3 waves");
        assert_eq!(count(1, "dependency"), "1 dependency");
        assert_eq!(count(2, "dependency"), "2 dependencies");
    }

    #[test]
    fn clearing_a_scope_conflicts_with_setting_one() {
        let err =
            Cli::try_parse_from(["hird", "scope", "1", "--clear", "--path", "src/**"]).unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn ls_rows_mark_the_tasks_that_cannot_start_yet() {
        let line = ls_line(
            &summary(7, Status::Open),
            1,
            false,
            now(),
            &[3, 4],
            None,
            Footprint::Unwatched,
        );
        assert!(line.contains("waits #3,#4"), "{line}");
    }

    #[test]
    fn overlaps_are_reported_both_ways_or_not_at_all() {
        let mut scopes = BTreeMap::new();
        scopes.insert(1, vec!["src/**".to_string()]);
        scopes.insert(2, vec!["src/db.rs".to_string()]);
        scopes.insert(3, vec!["docs/**".to_string()]);

        assert_eq!(overlapping(&scopes, 1, 2), vec!["src/**".to_string()]);
        assert_eq!(overlapping(&scopes, 2, 1), vec!["src/db.rs".to_string()]);
        assert!(overlapping(&scopes, 1, 3).is_empty());
        assert!(overlapping(&scopes, 1, 99).is_empty());
    }

    #[test]
    fn every_harness_is_registrable_by_name() {
        for (word, expected) in [
            ("claude-code", register::Harness::ClaudeCode),
            ("codex", register::Harness::Codex),
            ("copilot", register::Harness::Copilot),
            ("copilot-cli", register::Harness::CopilotCli),
            ("gemini", register::Harness::Gemini),
            ("opencode", register::Harness::OpenCode),
        ] {
            let cli = Cli::try_parse_from(["hird", "register", word]).unwrap();
            match cli.command {
                Some(Command::Register(args)) => {
                    assert_eq!(args.harness, expected);
                    assert_eq!(args.name, "hird");
                    assert!(!args.print && !args.force);
                }
                other => panic!("parsed as {other:?}"),
            }
        }
        assert!(Cli::try_parse_from(["hird", "register", "emacs"]).is_err());
    }

    #[test]
    fn printing_a_registration_cannot_also_force_one() {
        let err =
            Cli::try_parse_from(["hird", "register", "codex", "--print", "--force"]).unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn mem_search_defaults_to_an_empty_query() {
        let cli = Cli::try_parse_from(["hird", "mem", "search"]).unwrap();
        match cli.command {
            Some(Command::Mem(MemCommand::Search { query, limit, .. })) => {
                assert_eq!(query, "");
                assert_eq!(limit, 20);
            }
            other => panic!("parsed as {other:?}"),
        }
    }

    #[test]
    fn installer_options_parse_without_a_subcommand_and_may_be_combined() {
        let mcp = Cli::try_parse_from(["hird", "--install"]).unwrap();
        assert!(mcp.install);
        assert!(mcp.command.is_none());

        let both = Cli::try_parse_from(["hird", "--install", "--install-skill"]).unwrap();
        assert!(both.install);
        assert!(both.install_skill);
        assert!(both.command.is_none());
    }

    #[test]
    fn the_install_typo_is_not_an_option() {
        let err = Cli::try_parse_from(["hird", "--insytall"]).unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::UnknownArgument);
    }

    #[test]
    fn installer_options_and_normal_commands_are_detectably_distinct() {
        let cli = Cli::try_parse_from(["hird", "--install-skill", "ls"]).unwrap();
        assert!(cli.install_skill);
        assert!(matches!(cli.command, Some(Command::Ls(_))));
    }
}