hird 0.3.0

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
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
//! The MCP server: `hird mcp`.
//!
//! One process per harness session, speaking JSON-RPC over stdio. Every tool
//! result is compact JSON; every error is a sentence the model can relay to the
//! human verbatim.
//!
//! Both lifecycles are served. A client may handshake with `initialize`, or —
//! from MCP 2026-07-28, which has no handshake — open with `server/discover` or
//! with the request it wanted to make, carrying the protocol version, its own
//! name and its capabilities in `_meta` on each one. Nothing below depends on
//! which: the session is a process, the identity and the project scope are read
//! from the environment when it starts, and there is no protocol-level session
//! state to keep either way.

use std::collections::BTreeMap;
use std::path::Path;
use std::sync::{Arc, Mutex};

use rmcp::handler::server::tool::ToolCallContext;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
    CacheScope, CallToolRequestParams, CallToolResponse, DiscoverResult, ErrorCode, Implementation,
    ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig,
};
use rmcp::service::RequestContext;
use rmcp::{tool, tool_handler, tool_router, ErrorData, RoleServer, ServerHandler, ServiceExt};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::config::Config;
use crate::db::Db;
use crate::error::Error;

use crate::footing;
use crate::herald::{Announcement, Cause, Herald};
use crate::identity::{self, AgentId};
use crate::model::{
    Assertion, Blocker, Conflict, Contention, Footprint, Ground, Observed, Question, Recusal,
    Shifted, Standing, Status, Task, TaskEvent, TaskLinks, TaskSummary, Verdict, VerdictRecord,
};
use crate::repo::{
    Claim, Claimable, Delivered, Dispatch, Finished, LinkChange, MemoryQuery, NewAssertion,
    ProjectScope, Recalled, Subtask,
};
use crate::witness::{self, Witness};

/// Number of trailing events `task_get` returns.
const EVENT_WINDOW: usize = 20;

/// What a 2026-07-28 client must put in `_meta` to open a connection without
/// an `initialize` handshake, said the way the client's author would fix it.
const SELF_CONTAINED: &str =
    "a connection now opens either with an `initialize` request or with a \
     self-contained one, and a self-contained request carries \
     io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientInfo and \
     io.modelcontextprotocol/clientCapabilities in its `params._meta`";

/// Serve the MCP protocol on stdio until the client disconnects.
pub async fn serve(db_path: &Path, config: Config) -> anyhow::Result<()> {
    serve_session(db_path, config, &Attributes::default()).await
}

/// Serve one connection whose session `attributes` describe.
pub async fn serve_session(
    db_path: &Path,
    config: Config,
    attributes: &Attributes,
) -> anyhow::Result<()> {
    let session = Session::resolve(attributes, &config)?;
    let shared = Arc::new(Shared::new(Db::open(db_path)?, config));
    let server = HirdMcp::connect(shared, session);
    let running = match server.serve(rmcp::transport::stdio()).await {
        Ok(running) => running,
        Err(rmcp::service::ServerInitializeError::ExpectedInitializeRequest(opener)) => {
            refuse_opener(opener.as_ref());
            anyhow::bail!("this connection was never opened: {SELF_CONTAINED}");
        }
        // The client hung up before opening a session: after `server/discover`
        // alone, which is a whole conversation in 2026-07-28, or after the SDK
        // answered a malformed opener with the field it lacks. Neither is a
        // failure of this process.
        Err(rmcp::service::ServerInitializeError::ConnectionClosed(_)) => return Ok(()),
        Err(other) => return Err(other.into()),
    };
    running.waiting().await?;
    Ok(())
}

/// Answer an opening message that could not open anything.
///
/// The SDK hands back the offending message and drops the transport, which
/// would leave the client reading a closed pipe and reporting that hird
/// crashed. It did not crash; the request was malformed, and a request with an
/// id is owed an answer saying so. Written straight to stdout because on this
/// transport that is what the connection is. Best-effort: a client that has
/// already hung up is exactly the case where there is nothing left to say.
fn refuse_opener(opener: Option<&rmcp::model::ClientJsonRpcMessage>) {
    use std::io::Write;

    let Some(rmcp::model::JsonRpcMessage::Request(request)) = opener else {
        return;
    };
    let response = serde_json::json!({
        "jsonrpc": "2.0",
        "id": request.id,
        "error": {
            "code": ErrorCode::INVALID_REQUEST.0,
            "message": format!("this request cannot open a connection: {SELF_CONTAINED}"),
        },
    });
    let Ok(line) = serde_json::to_string(&response) else {
        return;
    };
    let mut stdout = std::io::stdout().lock();
    let _ = writeln!(stdout, "{line}");
    let _ = stdout.flush();
}

/// What one process holds however many connections it serves.
///
/// The database handle, the configuration, and the two hooks: everything whose
/// answer is the same whoever is asking. One `rusqlite::Connection` behind one
/// mutex serializes every session's writes, which is what the claim CAS wanted
/// anyway — a second connection would buy concurrency the queue then has to
/// take back.
pub struct Shared {
    // `rusqlite::Connection` is `Send` but not `Sync`; the mutex is only ever
    // held inside synchronous closures, never across an await.
    db: Mutex<Db>,
    config: Config,
    /// The dispatch hook, if one is configured, ready to announce tasks a
    /// session's calls make claimable.
    herald: Option<Herald>,
    /// The dispatch hook's twin for the other audience: the question hook, if
    /// one is configured, ready to tell a human a task now waits on them.
    question_herald: Option<crate::herald::QuestionHerald>,
}

impl Shared {
    /// Open the database and resolve everything that does not depend on who
    /// is connecting.
    pub fn new(db: Db, config: Config) -> Shared {
        let herald = config.herald(db.path());
        let question_herald = config.question_herald(db.path());
        Shared {
            db: Mutex::new(db),
            config,
            herald,
            question_herald,
        }
    }

    /// Read the shared database, for a process that serves something beside
    /// the sessions: a viewer. Held only inside `f`, never across an await.
    pub fn with_db<T>(&self, f: impl FnOnce(&Db) -> T) -> T {
        let db = self.db.lock().unwrap_or_else(|e| e.into_inner());
        f(&db)
    }

    /// Sweep expired leases, announcing what comes back when a dispatch hook
    /// is configured — what a viewer polling the board does, so a board left
    /// open never shows a dead lease as live, nor swallows a summons.
    pub fn sweep(&self) {
        self.with_db(|db| {
            if self.herald.is_some() {
                crate::herald::sweep_announcing(db, &self.config, self.herald.as_ref());
            } else {
                let _ = db.tasks().sweep_leases();
            }
        });
    }
}

/// What one connection is: who is calling, from where, and with what.
///
/// Until now these lived on the server, because one process served exactly one
/// session and the two were the same thing. They are separated so a process
/// can serve more than one — the identity a connection acts under, the project
/// its calls scope to, the capabilities it may claim against, and the tree, if
/// any, its evidence is read from.
///
/// Every field is fixed for the life of the connection. An identity that
/// changed mid-session would leave a caller unable to find its own leases; a
/// project or capability set that changed would make two calls from one agent
/// obey different rules.
pub struct Session {
    agent: AgentId,
    project: String,
    /// Human-controlled labels this connection may claim against.
    capabilities: Vec<String>,
    /// Whether this connection's project is somewhere the working tree can be
    /// watched. `None` is an ordinary state, not a degraded one — and it is
    /// the ordinary state for a connection whose tree is on another machine.
    witness: Option<Witness>,
    /// The role an operator granted this connection, when one did. Locally
    /// there is none; `hird-server` sets it from the roster.
    role: Option<String>,
    /// The policy in front of this connection's claims and finishes, when the
    /// process serving it put one there. Locally there is none.
    gate: Option<Arc<dyn crate::gate::Gate>>,
    /// The actor whose model and role were last declared to the audit, so a
    /// session declares once rather than on every call.
    declared: Mutex<Option<String>>,
}

impl Session {
    /// Resolve a connection's session against `config`.
    pub fn new(
        agent: AgentId,
        project: String,
        capabilities: Vec<String>,
        config: &Config,
    ) -> crate::Result<Session> {
        let witness = config.witness(Path::new(&project));
        Ok(Session {
            agent,
            project,
            capabilities: crate::capability::normalize_all(&capabilities)?,
            witness,
            role: None,
            gate: None,
            declared: Mutex::new(None),
        })
    }

    /// Grant this connection a role. Only an operator's roster may do this; no
    /// client-supplied value ever reaches it.
    pub fn with_role(mut self, role: impl Into<String>) -> Session {
        self.role = Some(role.into());
        self
    }

    /// Put a policy in front of this connection's claims and finishes.
    pub fn with_gate(mut self, gate: Arc<dyn crate::gate::Gate>) -> Session {
        self.gate = Some(gate);
        self
    }

    /// The policy in front of this connection's claims and finishes, if any.
    pub fn gate(&self) -> Option<&dyn crate::gate::Gate> {
        self.gate.as_deref()
    }

    /// The role this connection was granted, if any.
    pub fn role(&self) -> Option<&str> {
        self.role.as_deref()
    }

    /// What this connection declares to the audit: its model and its role.
    pub fn stamp(&self) -> crate::repo::Stamp {
        crate::repo::Stamp {
            model: self.agent.model().map(str::to_string),
            role: self.role.clone(),
        }
    }

    /// The session a process's own environment describes — one harness, one
    /// checkout, one set of labels. The stdio case, and the only case before
    /// a connection could say anything about itself.
    pub fn from_env(config: &Config) -> crate::Result<Session> {
        Session::resolve(&Attributes::default(), config)
    }

    /// The session `attributes` describe, with the environment answering
    /// whatever they leave unsaid.
    pub fn resolve(attributes: &Attributes, config: &Config) -> crate::Result<Session> {
        let agent = match &attributes.harness {
            Some(harness) => AgentId::fresh(harness.clone()),
            None => AgentId::from_env(),
        };
        let agent = match &attributes.identity {
            Some(who) => agent.acting_for(who.clone()),
            None => agent,
        };
        let agent = agent.running(std::env::var(identity::MODEL_ENV).unwrap_or_default());
        let project = match &attributes.project {
            Some(project) => identity::resolve_project(Path::new(project)),
            None => {
                let cwd = std::env::current_dir().unwrap_or_else(|_| Path::new(".").to_path_buf());
                identity::resolve_project(&cwd)
            }
        };
        let capabilities = if attributes.capabilities.is_empty() {
            crate::capability::from_env()?
        } else {
            attributes.capabilities.clone()
        };
        Session::new(agent, project, capabilities, config)
    }

    /// Who this session acts for, if anybody said.
    pub fn principal(&self) -> Option<&str> {
        self.agent.principal()
    }
}

/// What a connection is told it is, ahead of the environment.
///
/// Every field is optional and the environment answers what is left unsaid, so
/// a harness that sets `HIRD_HARNESS` and nothing else behaves exactly as it
/// did. The point of saying it explicitly is that it can then be said by
/// somebody other than the harness — an SSH `authorized_keys` forced command
/// pins the identity of the person on the far end of the key, which is the one
/// arrangement where a remote caller cannot name itself.
#[derive(Debug, Default, Clone)]
pub struct Attributes {
    /// The person this connection acts for.
    pub identity: Option<String>,
    /// The harness name, when it is not coming from the environment.
    pub harness: Option<String>,
    /// The project directory this connection's calls scope to.
    pub project: Option<String>,
    /// Capability labels this connection may claim against.
    pub capabilities: Vec<String>,
}

/// The MCP server state for one connection: what everybody shares, and what
/// only this caller is.
pub struct HirdMcp {
    shared: Arc<Shared>,
    session: Session,
}

impl HirdMcp {
    pub fn new(db: Db, agent: AgentId, project: String, config: Config) -> HirdMcp {
        HirdMcp::with_capabilities(db, agent, project, config, Vec::new())
            .expect("an empty capability set is valid")
    }

    pub fn with_capabilities(
        db: Db,
        agent: AgentId,
        project: String,
        config: Config,
        capabilities: Vec<String>,
    ) -> crate::Result<HirdMcp> {
        let session = Session::new(agent, project, capabilities, &config)?;
        Ok(HirdMcp::connect(Arc::new(Shared::new(db, config)), session))
    }

    /// One connection onto an already-open process.
    pub fn connect(shared: Arc<Shared>, session: Session) -> HirdMcp {
        HirdMcp { shared, session }
    }

    /// The identity recorded on this session's claims and assertions.
    pub fn actor(&self) -> String {
        self.session.agent.as_actor()
    }

    /// Who this connection is, and what it may do.
    pub fn session(&self) -> &Session {
        &self.session
    }

    /// Offer a client's name for itself to this session's identity, as every
    /// tool call does. For a server wrapping this one with tools of its own.
    pub fn name_from_client(&self, client_name: &str) -> bool {
        self.session.agent.name_from_client(client_name)
    }

    /// The project scope this session defaults to.
    pub fn project(&self) -> &str {
        &self.session.project
    }

    /// Run a closure against the database.
    ///
    /// Deliberately a synchronous function: the guard is created and dropped
    /// entirely inside it, so it never lands in an async state machine.
    pub fn with_db<T>(&self, f: impl FnOnce(&Db) -> T) -> T {
        let db = self.shared.db.lock().unwrap_or_else(|e| e.into_inner());
        self.declare(&db);
        f(&db)
    }

    /// Tell the audit what this session runs as, once per actor string. The
    /// actor can change once — when a client names the harness late — so the
    /// check is against the string, not a flag. Best effort: the audit missing
    /// a model must never fail the call that would have recorded it.
    fn declare(&self, db: &Db) {
        let stamp = self.session.stamp();
        if stamp.is_empty() {
            return;
        }
        let actor = self.actor();
        let mut declared = self
            .session
            .declared
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        if declared.as_deref() == Some(actor.as_str()) {
            return;
        }
        if db.audit().declare(&actor, &stamp).is_ok() {
            *declared = Some(actor);
        }
    }

    fn scope(&self, all_projects: Option<bool>) -> ProjectScope {
        ProjectScope::resolve(
            &self.session.project,
            self.shared.config.all_projects(all_projects),
        )
    }

    /// Run the dispatch hook for each announcement, if a hook is configured.
    ///
    /// Called after `with_db` returns, never inside it: the hook's own `hird`
    /// invocations read the same database, and must find both the lock free
    /// and the write they are being told about already committed.
    fn announce(&self, list: &[Announcement]) {
        crate::herald::announce(self.shared.herald.as_ref(), list);
    }

    /// Task `seq` as an announcement with `cause`, if it is claimable now.
    ///
    /// Read against the committed board, so a task another agent has taken in
    /// the meantime — or one that still waits for something — stays quiet.
    fn dispatchable(&self, db: &Db, cause: Cause, seq: i64) -> Option<Announcement> {
        self.shared.herald.as_ref()?;
        let claimable = db
            .deps()
            .claimable(seq, self.shared.config.clearance())
            .ok()
            .flatten()?;
        if self.held(db, seq) {
            return None;
        }
        Some(announcement(cause, claimable))
    }

    /// Whether this session's gate holds task `seq` against every claimant,
    /// so announcing it would summon an agent only to be refused.
    fn held(&self, db: &Db, seq: i64) -> bool {
        let Some(gate) = self.session.gate() else {
            return false;
        };
        !matches!(db.tasks().held_by(seq, gate), Ok(None))
    }

    /// Announce the open dependents of `seq` that now wait for nothing, as
    /// unblocked: for a move outside the core tools that clears ground — a
    /// factory's merge — after its transaction has committed.
    pub fn announce_unblocked_by(&self, seq: i64) {
        if self.shared.herald.is_none() {
            return;
        }
        let clearance = self.shared.config.clearance();
        let announcements = self.with_db(|db| {
            db.deps()
                .released_by(seq, clearance)
                .unwrap_or_default()
                .into_iter()
                .filter(|c| !self.held(db, c.seq))
                .map(|c| announcement(Cause::Unblocked, c))
                .collect::<Vec<_>>()
        });
        self.announce(&announcements);
    }

    /// Announcements for tasks a sweep just returned to the pool.
    ///
    /// The claimable check screens each one: a task that came back with a
    /// dependency meanwhile unmet, or that another agent grabbed already, is
    /// not waiting for hands.
    fn expired_announcements(&self, db: &Db, expired: &[i64]) -> Vec<Announcement> {
        expired
            .iter()
            .filter_map(|&seq| self.dispatchable(db, Cause::LeaseExpired, seq))
            .collect()
    }

    /// Sweep expired leases and announce what the sweep put back in the pool.
    ///
    /// Every queue-touching tool runs this before its real work. The repo
    /// method it is about to call would sweep anyway; sweeping here first
    /// keeps the outcome, so an expiry is announced by the call that notices
    /// it — including a call that then goes on to fail. The cost is a small
    /// window on `task_claim`: a task whose own lease just expired is
    /// announced in the instant before this call re-claims it, and the agent
    /// the hook summons finds `task_next` empty-handed. That is the race the
    /// skill's fallback exists for, and cheaper than an expiry nobody hears.
    fn sweep_announcing(&self) {
        if self.shared.herald.is_none() {
            return;
        }
        let announcements = self.with_db(|db| {
            let expired = db
                .tasks()
                .sweep_leases()
                .map(|s| s.expired)
                .unwrap_or_default();
            self.expired_announcements(db, &expired)
        });
        self.announce(&announcements);
    }

    /// Everything `finished` just made claimable, ready for the herald.
    ///
    /// Three kinds of becoming: dependents whose last unmet blocker this
    /// finish cleared — through `done` itself, or through an `upheld` verdict
    /// where `under_review = "holds"` had dependents waiting on it; work a
    /// `sent_back` verdict reopened; and the review the finish filed, which
    /// is itself an open task waiting for a harness that did not do the work.
    fn dispatched(&self, db: &Db, finished: &Finished) -> Vec<Announcement> {
        if self.shared.herald.is_none() {
            return Vec::new();
        }
        let clearance = self.shared.config.clearance();
        let mut released = db
            .deps()
            .released_by(finished.task.seq, clearance)
            .unwrap_or_default();
        for delivered in &finished.verdicts {
            if delivered.verdict == Verdict::Upheld {
                released.extend(
                    db.deps()
                        .released_by(delivered.seq, clearance)
                        .unwrap_or_default(),
                );
            }
        }
        released.sort_by_key(|c| c.seq);
        released.dedup_by_key(|c| c.seq);
        released.retain(|c| !self.held(db, c.seq));

        let mut out: Vec<Announcement> = released
            .into_iter()
            .map(|c| announcement(Cause::Unblocked, c))
            .collect();
        for delivered in &finished.verdicts {
            if delivered.reopened {
                out.extend(self.dispatchable(db, Cause::SentBack, delivered.seq));
            }
        }
        if let Some(review) = finished.review {
            out.extend(self.dispatchable(db, Cause::ReviewFiled, review));
        }
        out
    }

    /// Look at the working tree on this task's behalf and report what it says.
    ///
    /// The order is the point. The sweep brings every live task's footprint up
    /// to date without confirming anything; the report is read off that; and
    /// only then is this task's holder recorded as having been shown those
    /// versions. Confirming first would mark the agent's copy current in the
    /// same breath as telling it the file had moved, which is to say it would
    /// never tell it anything.
    ///
    /// Best-effort in the strongest sense: a sweep that fails costs the agent a
    /// report it did not ask for, while propagating the failure would cost it
    /// the call it did make. Nothing here can turn a completed task into an
    /// error, and there is no configuration in which it can.
    fn witnessed(&self, db: &Db, seq: i64) -> Evidence {
        let Some(witness) = &self.session.witness else {
            return Evidence::default();
        };
        let swept = witness::sweep(db, witness, &self.session.project, &self.actor()).ok();
        let mut evidence = self.evidence(db, seq);
        if let Some(swept) = swept {
            let _ = db.witnessed().confirm(seq, swept.changes_for(seq));
            if swept.tree.truncated {
                evidence.partial = Some(
                    "the working tree has more uncommitted files than hird will fingerprint \
                     in one go, so `changed` is a floor and not the whole story"
                        .to_string(),
                );
            }
        }
        evidence
    }

    /// Who this session acts for, when a human has said.
    ///
    /// Silent on a queue with one person on it, where an unattributed actor is
    /// the whole truth and a sentence about identity is noise in a context
    /// window. Said plainly where it matters, because an agent whose claims
    /// carry a name should be able to report that name to the human.
    fn identity_instructions(&self) -> String {
        match self.session.agent.principal() {
            Some(who) => format!(
                "\nThis session acts for {who}, and every claim, review and assertion it \
                 makes is recorded under that name alongside the harness. More than one \
                 person files into this queue: work you did not do may be waiting, and \
                 work you do will be read back to somebody else.\n"
            ),
            None => String::new(),
        }
    }

    /// The witness memory may read the tree through, if the configuration
    /// lets it. Narrower than `self.session.witness` by one flag.
    fn footing(&self) -> Option<&Witness> {
        self.shared.config.footing(self.session.witness.as_ref())
    }

    /// The memory relevant to a task, each fact carrying whether the code it
    /// was learned from still says what it said.
    ///
    /// Recall is a courtesy on top of the real answer, so it never turns a
    /// successful claim into an error: a failure here costs the agent some
    /// context, while propagating it would cost it the task it just took.
    fn recall(&self, db: &Db, seq: i64, limit: usize) -> Vec<Recalled> {
        let recalled = db.recall().for_task(seq, limit).unwrap_or_default();
        footing::decorate(db, self.footing(), recalled)
    }

    /// Start watching the tree on behalf of a task this session just claimed.
    fn begin_witnessing(&self, db: &Db, seq: i64) {
        let Some(witness) = &self.session.witness else {
            return;
        };
        let _ = witness::begin(db, witness, &self.session.project, seq, &self.actor());
    }

    /// What happened to this task before it was this claimant's, if it has
    /// ever changed hands under the witness.
    ///
    /// Read after [`HirdMcp::begin_witnessing`], which is what archives the
    /// previous holding — so on the claim where a task changes hands, the
    /// newest tenure is exactly the holding that just ended, and its holder's
    /// uncommitted leavings are sitting in the tree the new baseline was read
    /// off. Nobody but the queue is positioned to say so: the previous
    /// holder's session is gone, the new holder was not there, and the human
    /// sees two claims on a board that look like one continuous task.
    fn inheritance(&self, db: &Db, seq: i64) -> Option<String> {
        self.session.witness.as_ref()?;
        let held = db.witnessed().tenures(seq).ok()?;
        let last = held.last()?;
        let mut sentence = last.describe(seq);
        if held.len() > 1 {
            sentence = format!(
                "{sentence}. This task has changed hands {} times — `hird show {seq}` \
                 lists every holding",
                held.len()
            );
        }
        Some(sentence)
    }

    /// What the witness has to say about a task, as the tools report it.
    fn evidence(&self, db: &Db, seq: i64) -> Evidence {
        if self.session.witness.is_none() {
            return Evidence::default();
        }
        let live = db
            .tasks()
            .get(seq)
            .map(|task| task.status.is_active())
            .unwrap_or(false);
        let watched = db.witnessed().footprint(seq).unwrap_or_default();
        Evidence {
            footprint: watched.describe(live),
            watched,
            changed: db
                .witnessed()
                .touched(seq)
                .map(|seen| seen.iter().map(Observed::describe).collect())
                .unwrap_or_default(),
            contended: db
                .witnessed()
                .contention(seq)
                .map(|seen| seen.iter().map(Contention::describe).collect())
                .unwrap_or_default(),
            undeclared: db.witnessed().undeclared(seq).unwrap_or_default(),
            partial: None,
            alone: db
                .witnessed()
                .baselines(&self.session.project)
                .map(|live| live.len() <= 1)
                .unwrap_or(true),
        }
    }

    /// How often an agent should call `task_update` to keep its lease.
    fn heartbeat_minutes(&self) -> u64 {
        (self.shared.config.lease_ttl_minutes / 2).max(1)
    }

    /// What a harness sees in `initialize`.
    ///
    /// This is the only chance to tell the model the queue's rules, so it
    /// states them plainly: how to be handed work, claim before working,
    /// heartbeat before the lease runs out, say which files you are in, and
    /// write down what you learn.
    fn instructions(&self) -> String {
        format!(
            "hird is a shared work queue and memory, used at the same time by other agents \
             in other harnesses and by a human watching a TUI. Assume you are not alone.\n\
             \n\
             Tasks are referred to by their number (`seq`), the way the human says them: \
             \"pick up task 42\" means seq 42. Always quote that number back.\n\
             \n\
             Getting work:\n\
             - Told a number (\"pick up task 42\") → `task_claim`.\n\
             - Told to work the queue, with no number → `task_next`. It picks the most \
             important task that is actually workable and claims it for you. Call it again \
             when you finish; keep going until it comes back with nothing.\n\
             \n\
             Working a task:\n\
             1. `task_get` to read the full instructions.\n\
             2. Claim BEFORE doing any work. Claims are atomic — if another agent holds the \
             task the call fails and tells you who has it; relay that to the human instead of \
             working the task anyway.\n\
             3. `task_scope` with the files you are about to change, as soon as you know \
             them. This is how the queue keeps two agents out of the same file: it answers \
             with any overlap with work already under way. If it reports one, say so and \
             coordinate rather than editing over someone.\n\
             4. `task_update` with a short note as you go. A claim is a lease of {ttl} minutes \
             and every update renews it, so call it at least every {heartbeat} minutes or the \
             task returns to the pool and another agent may take it.\n\
             5. `task_complete` with a result summary, or `task_fail` with a reason. \
             Only the lease holder may do either.\n\
             \n\
             When a task turns out to be bigger than one job, `task_split` files the pieces \
             as real tasks, makes the original wait for them, and puts it back in the pool — \
             so the other agents can work the pieces in parallel while it waits. When you \
             simply cannot do a task, `task_release` hands it back without marking it failed. \
             When no agent can continue until a human decides or supplies something, pass the \
             exact `question`: the task stays out of dispatch until `hird answer` records the \
             response, and the next claim receives that question and answer.\n\
             \n\
             Tasks can depend on other tasks. A task whose dependencies are unfinished \
             cannot be claimed, and the refusal names what it is waiting for. When you do \
             claim, `built_on` carries each finished dependency's own result — the work \
             this task was ordered after, summarised by whoever did it. Read it before \
             the body: it is the context the dependency existed to produce. A `built_on` \
             entry marked provisional is done but still under review; if its verdict \
             sends that work back while you hold this task, your next `task_update` \
             answers with `ground_shifted` — stop and re-read the reopened task before \
             building further on what it made.\n\
             \n\
             A task may require capabilities such as `browser` or `network`. This session \
             advertises [{capabilities}]. Named claims are refused when those do not fit, \
             and `task_next` routes around incompatible work. That is not a transient race: \
             relay it to the human, who must use a suitably configured harness.\n\
             \n\
             Some tasks are reviews, and a review is barred to the harness whose work it \
             reviews — including this one. If a claim comes back saying the task is recused, \
             that is not a race you can retry: relay it to the human, who needs to point a \
             different tool at it. When a task you finish was marked for review, the answer \
             names the review it filed; say that number out loud too. You are not being \
             distrusted, you are being read by somebody who was not in the room, which is \
             the whole reason the human is running more than one of us.\n\
             \n\
             A review ends in a verdict, not just prose: `task_complete` on a review \
             requires `verdict` — \"upheld\" if the work stands, \"sent_back\" if it does \
             not. Sending work back acts immediately: the queue reopens it with your \
             findings appended to its brief, any agent (its author included) may pick it \
             up, and completing it again files a fresh review — so write the result as \
             instructions for whoever redoes it. Upholding is a signature: the board marks \
             the work upheld on your harness's word, on the record.\n\
             \n\
             Memory: `mem_store` durable facts you learn — where something lives, why a \
             decision was made, what a command is — one assertion per call, in plain prose \
             that will still make sense to a different agent next week. Pass `task_seq` when \
             you learned it working a task. `mem_search` before exploring from scratch; \
             another agent may already have found the answer.\n\
             \n\
             Recall: a claimed task comes back with `recalled` — facts earlier agents \
             recorded while working the same files, each with a `why` saying where it came \
             from. Read those before you start; they are the reason to declare your paths \
             early, because file scope is how the queue knows what to hand you. They are \
             assertions, not gospel: if one turns out to be wrong, `mem_store` the truth.\n\
             {footing}\
             {witness}\n\
             {identity}\
             Everything is scoped to the current project ({project}) unless you pass \
             `all_projects: true`.",
            ttl = self.shared.config.lease_ttl_minutes,
            heartbeat = self.heartbeat_minutes(),
            capabilities = self.session.capabilities.join(", "),
            identity = self.identity_instructions(),
            project = self.session.project,
            footing = self.footing_instructions(),
            witness = self.witness_instructions(),
        )
    }

    /// The paragraph about memory's footing, or nothing where there is none.
    ///
    /// Left out for the same reason as the witness paragraph: a model told to
    /// read a `standing` field that nothing will ever populate has been handed
    /// a rule it cannot use and a reason to doubt the ones it can.
    fn footing_instructions(&self) -> &'static str {
        if self.footing().is_none() {
            return "";
        }
        "\nHow much to trust a fact: assertions carry a `standing`, because hird records \
         which files each one was read off and what those files said at the time. `firm` \
         means the code has not moved since; `shaky` means it has, so the fact is \
         unverified rather than wrong — re-read the file before you act on it; `orphaned` \
         means the file is gone. Nothing marks a fact false; that is your call after \
         looking. When you check a shaky fact and it still holds, `mem_store` it again \
         word for word: that does not duplicate it, it re-anchors it to today's code and \
         records you as another voice for it, and the next agent gets it marked firm. When \
         it does not hold, `mem_store` the truth instead. Pass `paths` (or `task_seq`) so \
         what you record gets a footing of its own.\n"
    }

    /// The paragraph about the witness, or nothing at all where there is none.
    ///
    /// Left out entirely rather than hedged: a model told about `contended` in
    /// a project where nothing will ever populate it has been given a rule it
    /// cannot use and a reason to doubt the ones it can.
    fn witness_instructions(&self) -> &'static str {
        if self.session.witness.is_none() {
            return "";
        }
        "\nThe working tree: hird watches it. A claim fingerprints the repository, and \
         every task_update, task_scope and finishing call compares it again, so results \
         come back with `changed` — the files that moved while you held the task, off the \
         disk rather than out of anyone's summary. Two things there are worth acting on. \
         `undeclared` lists files you have changed that you never declared: call \
         task_scope with them, because the other agents' collision checks are reading \
         your declaration and not your edits. `contended` means a file you declared has \
         moved under another agent that declared it too — whoever read it first is \
         holding a copy that no longer matches, so re-read it before your next write and \
         tell the human. hird watched the file change; it cannot see who typed, so treat \
         `changed` as what happened in your window, not as a list of your own edits. \
         `footprint` is the same evidence in one sentence — `read-only` when nothing has \
         moved, `modified 3 files` when something has — and it is what to tell the human \
         when they ask whether the work changed anything. A claim that answers with \
         `previously` is handing you a task that has been held before — a lease that \
         expired, work released or sent back — and whatever that holder left uncommitted \
         is in your working tree now, looking exactly like code that was always there. \
         The sentence says who held it, how it ended and which files moved; re-read \
         those files before building on or over them.\n"
    }
}

// ------------------------------------------------------------------ arguments

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskListArgs {
    /// Only tasks in this status: open, claimed, in_progress, done, failed or cancelled.
    #[serde(default)]
    pub status: Option<String>,
    /// Include tasks from every project rather than just the current one.
    #[serde(default)]
    pub all_projects: Option<bool>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SeqArgs {
    /// The task number, as the human refers to it.
    pub seq: i64,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskClaimArgs {
    /// The task number.
    pub seq: i64,
    /// Files you expect to change, as paths or globs relative to the project
    /// root, e.g. ["src/config.rs", "tests/**"]. Declaring them is how the
    /// queue can warn you that another agent is already in there.
    #[serde(default)]
    pub paths: Option<Vec<String>>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskNextArgs {
    /// Consider tasks from every project rather than just the current one.
    #[serde(default)]
    pub all_projects: Option<bool>,
    /// Pass over tasks whose files overlap work another agent holds.
    /// On by default.
    #[serde(default)]
    pub avoid_conflicts: Option<bool>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskScopeArgs {
    /// The task number. You must hold its lease.
    pub seq: i64,
    /// Paths or globs relative to the project root, e.g. ["src/**/*.rs"].
    pub paths: Vec<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskSplitArgs {
    /// The task to break up. You must hold its lease.
    pub seq: i64,
    /// The pieces, in the order they should be worked.
    pub subtasks: Vec<SubtaskArgs>,
    /// Make each piece wait for the one before it. Leave this off when the
    /// pieces can be worked at the same time by different agents.
    #[serde(default)]
    pub sequential: Option<bool>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SubtaskArgs {
    /// Short title, as a human would say it.
    pub title: String,
    /// Full instructions for whichever agent picks this up. Write it for
    /// someone who has not seen your session.
    #[serde(default)]
    pub body: Option<String>,
    /// Higher sorts first. Defaults to the parent task's priority.
    #[serde(default)]
    pub priority: Option<i64>,
    /// Files this piece is expected to touch.
    #[serde(default)]
    pub paths: Option<Vec<String>>,
    /// Capabilities a claimant must advertise for this piece.
    #[serde(default)]
    pub requires: Option<Vec<String>>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskReleaseArgs {
    /// The task number. You must hold its lease.
    pub seq: i64,
    /// Why you are handing it back, for the next agent and the human.
    pub reason: String,
    /// The answer this task needs before any agent can continue. When present,
    /// the task stays out of dispatch until a human runs `hird answer`.
    #[serde(default)]
    pub question: Option<String>,
}

#[derive(Debug, Default, Deserialize, JsonSchema)]
pub struct TaskUpdateArgs {
    /// The task number.
    pub seq: i64,
    /// What you have done or found. Recorded in the task's history.
    pub note: String,
    /// Pass "in_progress" the first time you actually start work.
    #[serde(default)]
    pub status: Option<String>,
    /// The git branch the work is on. An empty string clears it.
    #[serde(default)]
    pub branch: Option<String>,
    /// The worktree the work is done in. An empty string clears it.
    #[serde(default)]
    pub worktree: Option<String>,
    /// The pull request that carries the work, as an http(s) URL. An empty
    /// string clears it.
    #[serde(default)]
    pub pr_url: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskCompleteArgs {
    /// The task number.
    pub seq: i64,
    /// A summary of what was done, for the human reading the board. On a
    /// review, this is your findings — written for whoever redoes the work if
    /// you send it back.
    pub result: String,
    /// Required when the task is a review, refused when it is not.
    /// "upheld" — the work stands. "sent_back" — the work is reopened with
    /// your findings appended to its brief, and a fresh review will be filed
    /// when it is completed again.
    #[serde(default)]
    pub verdict: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TaskFailArgs {
    /// The task number.
    pub seq: i64,
    /// Why the task could not be completed.
    pub reason: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct MemStoreArgs {
    /// One factual assertion, in plain prose.
    pub content: String,
    /// Optional comma-separated tags, e.g. "build,ci".
    #[serde(default)]
    pub tags: Option<String>,
    /// The task you learned this while working, if any.
    #[serde(default)]
    pub task_seq: Option<i64>,
    /// The files this fact is about, as literal paths relative to the project
    /// root, e.g. ["src/config.rs"]. hird records what they say right now, so
    /// a later reader can be told if the code has moved under this fact.
    /// Leave it off when you passed `task_seq` — the files that task is in are
    /// used instead.
    #[serde(default)]
    pub paths: Option<Vec<String>>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct MemSearchArgs {
    /// Search text. Full-text syntax is supported; plain words are fine.
    pub query: String,
    /// Maximum results to return. Defaults to 20.
    #[serde(default)]
    pub limit: Option<usize>,
    /// Search every project rather than just the current one.
    #[serde(default)]
    pub all_projects: Option<bool>,
    /// Include assertions that have since been replaced.
    #[serde(default)]
    pub include_superseded: Option<bool>,
}

// -------------------------------------------------------------------- results

#[derive(Debug, Serialize)]
struct TaskListResult<'a> {
    project: &'a str,
    all_projects: bool,
    count: usize,
    tasks: Vec<TaskRow>,
    /// Tasks whose leases expired during this call and are open again.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    released: Vec<i64>,
}

#[derive(Debug, Serialize)]
struct TaskRow {
    seq: i64,
    title: String,
    status: Status,
    #[serde(skip_serializing_if = "Option::is_none")]
    holder: Option<String>,
    priority: i64,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    requires: Vec<String>,
    /// Required capabilities this MCP session did not advertise. A non-empty
    /// value means the task may be ready globally but cannot be claimed here.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    missing_capabilities: Vec<String>,
    updated_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    project: Option<String>,
    /// Unfinished tasks this one waits for. An `open` task with any of these
    /// cannot be claimed yet.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    blocked_by: Vec<i64>,
    /// The question keeping this otherwise-open task out of dispatch.
    #[serde(skip_serializing_if = "Option::is_none")]
    awaiting_answer: Option<String>,
    /// Set when this task is a review of work *you* did, so you cannot claim
    /// it however open it looks. Same reason `blocked_by` is here: a list that
    /// shows unclaimable work as available is lying to whoever reads it.
    #[serde(skip_serializing_if = "Option::is_none")]
    recused_from_you: Option<String>,
    /// True on `done` work a review has upheld: finished, and seen to be
    /// finished by a harness that did not do it. Done without this just means
    /// nobody has judged it — or a round of review is still under way.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    upheld: bool,
}

impl TaskRow {
    fn from_summary(
        summary: TaskSummary,
        show_project: bool,
        blocked_by: Vec<i64>,
        awaiting_answer: Option<Question>,
        recused: Option<Recusal>,
        verdict: Option<Verdict>,
        capabilities: &[String],
    ) -> TaskRow {
        let missing_capabilities = crate::capability::missing(&summary.requirements, capabilities);
        TaskRow {
            seq: summary.seq,
            title: summary.title,
            upheld: summary.status == Status::Done && verdict == Some(Verdict::Upheld),
            status: summary.status,
            holder: summary.claimed_by,
            priority: summary.priority,
            requires: summary.requirements,
            missing_capabilities,
            updated_at: summary.updated_at,
            project: show_project.then_some(summary.project),
            blocked_by,
            awaiting_answer: awaiting_answer.map(|q| q.question),
            recused_from_you: recused.map(|r| r.describe()),
        }
    }
}

#[derive(Debug, Serialize)]
struct TaskDetail {
    seq: i64,
    project: String,
    title: String,
    body: String,
    status: Status,
    priority: i64,
    /// Capabilities a claimant must advertise.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    requires: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    holder: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    lease_expires_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    result: Option<String>,
    /// Where the work lives: branch, worktree, pull request.
    #[serde(skip_serializing_if = "Option::is_none")]
    links: Option<TaskLinks>,
    /// Questions earlier holders asked, including the answer that resumed
    /// each completed round and the current unanswered one, when present.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    questions: Vec<QuestionRow>,
    created_at: String,
    updated_at: String,
    /// Tasks that must finish before this one can be claimed.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    waiting_for: Vec<BlockerRow>,
    /// The finished dependencies this task builds on — each one's own summary
    /// of what it did, and whether that answer is upheld, done, or still
    /// provisional under an unfinished review.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    built_on: Vec<GroundRow>,
    /// Tasks that are waiting for this one.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    blocks: Vec<i64>,
    /// The files this task has said it will touch.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    paths: Vec<String>,
    /// Overlaps between those files and work other agents hold right now.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    overlaps: Vec<String>,
    /// Who cannot claim this task, and why. Present on reviews.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    recused_from: Vec<String>,
    /// True when finishing this task will file a review of what it changed.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    review_on_finish: bool,
    /// The newest verdict delivered on this task's work, when a review has
    /// judged it: who upheld it or sent it back, and after how many rounds.
    #[serde(skip_serializing_if = "Option::is_none")]
    verdict: Option<String>,
    /// When this task is a review that has been completed: what it concluded,
    /// per task it judged.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    verdicts_delivered: Vec<String>,
    /// What earlier work in the same territory learned. Read before exploring.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    recalled: Vec<RecallRow>,
    /// What the working tree was seen to do while this task was held, as
    /// against `paths`, which is what somebody said it would do.
    #[serde(flatten)]
    witness: Evidence,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    events: Vec<EventRow>,
}

/// A dependency, with enough context to act on without another lookup.
#[derive(Debug, Serialize)]
struct BlockerRow {
    seq: i64,
    title: String,
    status: Status,
    /// The unfinished review holding this `done` blocker short of clearing —
    /// present only under `under_review = "holds"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pending_review: Option<i64>,
}

impl From<Blocker> for BlockerRow {
    fn from(b: Blocker) -> BlockerRow {
        BlockerRow {
            seq: b.seq,
            title: b.title,
            status: b.status,
            pending_review: b.pending_review,
        }
    }
}

/// One finished dependency, handed over with the claim: the summary its own
/// finisher wrote, and how far that word can currently be trusted.
#[derive(Debug, Serialize)]
struct GroundRow {
    seq: i64,
    title: String,
    /// What finishing it said it did — the context this task was ordered
    /// after it to have.
    #[serde(skip_serializing_if = "Option::is_none")]
    result: Option<String>,
    /// `done`, `upheld`, or `under review N, provisional`. Provisional means a
    /// sent-back verdict could reopen that work while this task runs; a
    /// check-in will say so if it happens.
    standing: String,
}

impl From<Ground> for GroundRow {
    fn from(g: Ground) -> GroundRow {
        GroundRow {
            seq: g.seq,
            title: g.title,
            result: g.result,
            standing: g.standing.describe(),
        }
    }
}

fn ground_rows(ground: Vec<Ground>) -> Vec<GroundRow> {
    ground.into_iter().map(GroundRow::from).collect()
}

/// Everything about a task other than its own row.
struct TaskContext {
    waiting_for: Vec<Blocker>,
    ground: Vec<Ground>,
    blocks: Vec<i64>,
    paths: Vec<String>,
    conflicts: Vec<Conflict>,
    recusals: Vec<Recusal>,
    /// Verdicts delivered on this task's work, oldest first.
    verdicts: Vec<VerdictRecord>,
    /// Verdicts this task delivered, when it is a completed review.
    delivered: Vec<VerdictRecord>,
    recalled: Vec<Recalled>,
    witness: Evidence,
    events: Vec<TaskEvent>,
    questions: Vec<Question>,
    requirements: Vec<String>,
    links: Option<TaskLinks>,
}

impl TaskDetail {
    fn new(task: Task, context: TaskContext) -> TaskDetail {
        TaskDetail {
            seq: task.seq,
            project: task.project,
            title: task.title,
            body: task.body,
            status: task.status,
            priority: task.priority,
            requires: context.requirements,
            holder: task.claimed_by,
            lease_expires_at: task.lease_expires_at,
            result: task.result,
            links: context.links,
            questions: context
                .questions
                .into_iter()
                .map(QuestionRow::from)
                .collect(),
            created_at: task.created_at,
            updated_at: task.updated_at,
            waiting_for: context
                .waiting_for
                .into_iter()
                .map(BlockerRow::from)
                .collect(),
            built_on: ground_rows(context.ground),
            blocks: context.blocks,
            paths: context.paths,
            overlaps: describe_all(&context.conflicts),
            recused_from: context.recusals.iter().map(Recusal::describe).collect(),
            review_on_finish: task.review,
            verdict: verdict_sentence(&context.verdicts),
            verdicts_delivered: context
                .delivered
                .iter()
                .map(|v| format!("task {}: {}", v.task_seq, v.verdict))
                .collect(),
            recalled: recall_rows(context.recalled),
            witness: context.witness,
            events: context.events.into_iter().map(EventRow::from).collect(),
        }
    }
}

#[derive(Debug, Serialize)]
struct QuestionRow {
    n: i64,
    question: String,
    asked_by: String,
    asked_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    answer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    answered_by: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    answered_at: Option<String>,
}

impl From<Question> for QuestionRow {
    fn from(q: Question) -> QuestionRow {
        QuestionRow {
            n: q.n,
            question: q.question,
            asked_by: q.asked_by,
            asked_at: q.asked_at,
            answer: q.answer,
            answered_by: q.answered_by,
            answered_at: q.answered_at,
        }
    }
}

/// Conflicts as the sentences a model can relay without rewording them.
fn describe_all(conflicts: &[Conflict]) -> Vec<String> {
    conflicts.iter().map(Conflict::describe).collect()
}

/// The newest verdict on a task's work as one sentence, with the round count
/// when there has been more than one — "sent back once already" is exactly the
/// context the next reader of this task needs.
fn verdict_sentence(verdicts: &[VerdictRecord]) -> Option<String> {
    let latest = verdicts.last()?;
    Some(if verdicts.len() > 1 {
        format!(
            "{}, verdict {} on this work",
            latest.describe(),
            verdicts.len()
        )
    } else {
        latest.describe()
    })
}

#[derive(Debug, Serialize)]
struct EventRow {
    at: String,
    actor: String,
    kind: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    detail: String,
}

impl From<TaskEvent> for EventRow {
    fn from(e: TaskEvent) -> EventRow {
        EventRow {
            at: e.at,
            actor: e.actor,
            kind: e.kind.as_str().to_string(),
            detail: e.detail,
        }
    }
}

/// One assertion the queue volunteered, and why.
///
/// `why` is a sentence rather than a code: the agent that reads this is a
/// language model, and "learned on task 4 (Port the config loader), working
/// src/config.rs" tells it how much to trust the fact and who to ask.
#[derive(Debug, Serialize)]
struct RecallRow {
    content: String,
    why: String,
    actor: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    task_seq: Option<i64>,
    created_at: String,
    /// Pass to `mem_search` results or quote to the human; assertions are
    /// never edited, so an id stays valid.
    id: String,
    /// `firm`, `shaky` or `orphaned`: whether the code this was learned from is
    /// still the code on disk. Absent means hird has no footing for it.
    #[serde(skip_serializing_if = "Option::is_none")]
    standing: Option<&'static str>,
    /// Present only when there is something to do about it — the files have
    /// moved, or the agent that wrote this is not the only one who has said it.
    #[serde(skip_serializing_if = "Option::is_none")]
    caution: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    corroboration: Option<String>,
}

impl RecallRow {
    fn new(r: Recalled) -> RecallRow {
        let standing = r.standing.filter(|s| *s != Standing::Unanchored);
        RecallRow {
            why: r.reason.describe(),
            content: r.assertion.content,
            actor: r.assertion.actor,
            task_seq: r.task_seq,
            created_at: r.assertion.created_at,
            id: r.assertion.id,
            standing: standing.as_ref().map(|s| s.as_str()),
            // Only the standings worth acting on carry their sentence here. A
            // claim's recall is the smallest budget in hird and it lands in an
            // agent's context unasked; "this file is unchanged" spent on all
            // five rows would crowd out the one row that says otherwise.
            caution: standing
                .filter(Standing::needs_checking)
                .and_then(|s| s.describe()),
            corroboration: r.corroboration,
        }
    }
}

fn recall_rows(recalled: Vec<Recalled>) -> Vec<RecallRow> {
    recalled.into_iter().map(RecallRow::new).collect()
}

#[derive(Debug, Serialize)]
struct ClaimResult {
    claimed: i64,
    holder: String,
    lease_expires_at: String,
    title: String,
    body: String,
    priority: i64,
    project: String,
    /// Capabilities this session proved it had when the claim landed.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    requires: Vec<String>,
    /// The files this task is on record as touching.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    paths: Vec<String>,
    /// Overlaps with work other agents hold. Non-empty means someone else is
    /// already in these files.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    overlaps: Vec<String>,
    /// What earlier agents recorded about this task or these files. Nobody
    /// asked for it; the queue knew it was relevant and sent it along.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    recalled: Vec<RecallRow>,
    /// The finished tasks this one builds on: each one's own summary of what
    /// it did, and how far that word can be trusted. The dependency order
    /// existed because this task needs to know what that work turned out to
    /// be — so here it is, unasked.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    built_on: Vec<GroundRow>,
    /// Decisions earlier holders stopped to ask for. Every row here is
    /// answered — an unresolved one would have prevented this claim.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    questions: Vec<QuestionRow>,
    /// Every earlier attempt at this work that was rejected: whose, by what
    /// judge, and what the judge said, oldest first.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    attempts: Vec<crate::model::Attempt>,
    /// What happened to this task before this claim, when it has changed
    /// hands: who held it, how that holding ended, and what moved under them
    /// — because whatever they left uncommitted is in the tree this claim
    /// starts from, indistinguishable from code that was always there.
    #[serde(skip_serializing_if = "Option::is_none")]
    previously: Option<String>,
    /// Restated so the model does not have to remember the initialize text.
    reminder: String,
}

impl ClaimResult {
    fn new(
        claim: Claim,
        holder: String,
        heartbeat: u64,
        recalled: Vec<Recalled>,
        previously: Option<String>,
    ) -> ClaimResult {
        let overlaps = describe_all(&claim.conflicts);
        let questions: Vec<QuestionRow> = claim
            .questions
            .iter()
            .cloned()
            .map(QuestionRow::from)
            .collect();
        let provisional: Vec<i64> = claim
            .ground
            .iter()
            .filter(|g| g.standing.is_provisional())
            .map(|g| g.seq)
            .collect();
        let heartbeat_rule = format!(
            "call task_update at least every {heartbeat} minutes to keep this lease, \
             then task_complete or task_fail when you are done"
        );
        let mut reminder = if overlaps.is_empty() {
            heartbeat_rule
        } else {
            format!(
                "another agent is already in some of these files — say so before you edit \
                 them. Otherwise: {heartbeat_rule}"
            )
        };
        if !provisional.is_empty() {
            let listed = provisional
                .iter()
                .map(|seq| format!("task {seq}"))
                .collect::<Vec<_>>()
                .join(", ");
            reminder = format!(
                "{listed} in `built_on` {} finished but still under review — a sent-back \
                 verdict would reopen {}, and your next check-in will say so if it happens. \
                 {reminder}",
                plural(provisional.len(), "is", "are"),
                plural(provisional.len(), "it", "them"),
            );
        }
        if !recalled.is_empty() {
            reminder = format!(
                "read `recalled` first — earlier agents left those notes about this work, \
                 and each says where it came from. Then: {reminder}"
            );
        }
        if previously.is_some() {
            reminder = format!(
                "this task has been held before — `previously` says by whom and what moved \
                 under them; re-read those files rather than assuming the tree is untouched. \
                 {reminder}"
            );
        }
        if let Some(last) = claim.attempts.last() {
            reminder = format!(
                "this work has been rejected {} time{} — read `attempts`, newest last, and \
                 fix what the latest one ({} by {}) says before anything else. {reminder}",
                claim.attempts.len(),
                if claim.attempts.len() == 1 { "" } else { "s" },
                last.outcome,
                last.source,
            );
        }
        if !questions.is_empty() {
            reminder = format!(
                "read `questions` before continuing — an earlier holder stopped for those \
                 decisions, and the answers are part of this task's brief. Then: {reminder}"
            );
        }
        ClaimResult {
            claimed: claim.task.seq,
            holder,
            lease_expires_at: claim.task.lease_expires_at.unwrap_or_default(),
            title: claim.task.title,
            body: claim.task.body,
            priority: claim.task.priority,
            project: claim.task.project,
            requires: claim.requirements,
            paths: claim.paths,
            overlaps,
            recalled: recall_rows(recalled),
            built_on: ground_rows(claim.ground),
            questions,
            attempts: claim.attempts,
            previously,
            reminder,
        }
    }
}

/// What `task_next` answers with: a claim, or the reason there wasn't one.
#[derive(Debug, Serialize)]
struct NextResult {
    #[serde(skip_serializing_if = "Option::is_none")]
    claimed: Option<ClaimResult>,
    /// One sentence explaining an empty-handed answer.
    #[serde(skip_serializing_if = "Option::is_none")]
    idle: Option<String>,
    /// The queue is in recess: the human stood it down, and nothing is handed
    /// out until they lift it. Not idle — standing by is the correct move.
    #[serde(skip_serializing_if = "Option::is_none")]
    recess: Option<String>,
    /// Open tasks that are waiting on unfinished dependencies.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    blocked: Vec<i64>,
    /// Tasks whose every dependency is finished but for a verdict — the queue
    /// is configured to hold their dependents until the named review
    /// concludes. Different from `blocked`: the fix is a review being read,
    /// not work being done.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    held: Vec<HeldRow>,
    /// Open tasks parked until a human answers the named question.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    awaiting_answer: Vec<AwaitingAnswerRow>,
    /// Ready tasks passed over because another agent is in their files.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    deferred: Vec<DeferredRow>,
    /// Ready tasks this harness is barred from, and why. Usually a review of
    /// work this harness did: say so to the human, because the task is waiting
    /// for a different tool and not for time to pass.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    recused: Vec<RecusedRow>,
    /// Ready tasks the policy serving this connection would not let it take.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    gated: Vec<RecusedRow>,
    /// Ready tasks this session is not equipped to perform.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    incompatible: Vec<IncompatibleRow>,
}

#[derive(Debug, Serialize)]
struct DeferredRow {
    seq: i64,
    overlaps: Vec<String>,
}

#[derive(Debug, Serialize)]
struct HeldRow {
    seq: i64,
    /// The unfinished review whose verdict this task waits on.
    review: i64,
}

#[derive(Debug, Serialize)]
struct AwaitingAnswerRow {
    seq: i64,
    question: String,
}

#[derive(Debug, Serialize)]
struct RecusedRow {
    seq: i64,
    why: String,
}

#[derive(Debug, Serialize)]
struct IncompatibleRow {
    seq: i64,
    missing: Vec<String>,
}

impl NextResult {
    fn new(
        dispatch: Dispatch,
        holder: String,
        heartbeat: u64,
        recalled: Vec<Recalled>,
        previously: Option<String>,
    ) -> NextResult {
        let idle = dispatch.claim.is_none().then(|| idle_reason(&dispatch));
        NextResult {
            claimed: dispatch
                .claim
                .map(|claim| ClaimResult::new(claim, holder, heartbeat, recalled, previously)),
            idle,
            recess: dispatch.recess.map(|r| r.describe()),
            blocked: dispatch.blocked,
            held: dispatch
                .held
                .into_iter()
                .map(|(seq, review)| HeldRow { seq, review })
                .collect(),
            awaiting_answer: dispatch
                .awaiting_answer
                .into_iter()
                .map(|(seq, question)| AwaitingAnswerRow {
                    seq,
                    question: question.question,
                })
                .collect(),
            deferred: dispatch
                .deferred
                .into_iter()
                .map(|(seq, conflicts)| DeferredRow {
                    seq,
                    overlaps: describe_all(&conflicts),
                })
                .collect(),
            recused: dispatch
                .recused
                .into_iter()
                .map(|(seq, recusal)| RecusedRow {
                    seq,
                    why: recusal.describe(),
                })
                .collect(),
            gated: dispatch
                .gated
                .into_iter()
                .map(|(seq, why)| RecusedRow { seq, why })
                .collect(),
            incompatible: dispatch
                .incompatible
                .into_iter()
                .map(|(seq, missing)| IncompatibleRow { seq, missing })
                .collect(),
        }
    }
}

/// Why the queue had nothing to hand out, in the terms the agent can act on.
fn idle_reason(dispatch: &Dispatch) -> String {
    // A recess outranks every other sentence, because it is the one answer
    // under which nothing else was even considered: the human stood the queue
    // down, and standing by — not retrying, not escalating — is the move.
    if let Some(recess) = &dispatch.recess {
        return format!(
            "in recess, not idle: {}. Stand by rather than retrying; the human \
             decides when claims resume",
            recess.describe()
        );
    }
    // Like a recusal, a role is not something waiting will change.
    if dispatch.claim.is_none()
        && dispatch.recused.is_empty()
        && dispatch.held.is_empty()
        && dispatch.awaiting_answer.is_empty()
        && dispatch.blocked.is_empty()
        && dispatch.deferred.is_empty()
        && dispatch.incompatible.is_empty()
    {
        if let Some((seq, why)) = dispatch.gated.first() {
            return format!(
                "{} task{} ready, but this connection may not take {}: task {seq}: {why}",
                dispatch.gated.len(),
                plural(dispatch.gated.len(), " is", "s are"),
                if dispatch.gated.len() == 1 {
                    "it"
                } else {
                    "them"
                }
            );
        }
    }
    let recused = dispatch.recused.len();
    let held = dispatch.held.len();
    let awaiting = dispatch.awaiting_answer.len();
    let blocked = dispatch.blocked.len();
    let deferred = dispatch.deferred.len();
    let incompatible = dispatch.incompatible.len();

    // Named first when it is the only thing left, because it is the only one
    // of the four that waiting will not fix: a review of this harness's own
    // work stays unclaimable until somebody opens a different tool.
    if recused > 0
        && held == 0
        && awaiting == 0
        && blocked == 0
        && deferred == 0
        && incompatible == 0
    {
        return format!(
            "{recused} task{} ready, but every one of them is a review of work this harness \
             did — they need an agent in another harness. Tell the human; waiting will not \
             change it",
            plural(recused, " is", "s are")
        );
    }
    // Held gets its own sentence when it is the whole story: "the work is done
    // and its review has not concluded" points at a review to work or chase,
    // where "waiting on dependencies" points at work that has not happened.
    if held > 0
        && recused == 0
        && awaiting == 0
        && blocked == 0
        && deferred == 0
        && incompatible == 0
    {
        let mut reviews: Vec<i64> = dispatch.held.iter().map(|(_, review)| *review).collect();
        reviews.sort_unstable();
        reviews.dedup();
        let listed = reviews
            .iter()
            .map(|s| format!("{s}"))
            .collect::<Vec<_>>()
            .join(", ");
        return format!(
            "{held} task{} finished but for a verdict: this queue holds dependents until \
             review {listed} concludes. The way forward is that review, not waiting",
            plural(held, " is", "s are")
        );
    }
    if awaiting > 0
        && recused == 0
        && held == 0
        && blocked == 0
        && deferred == 0
        && incompatible == 0
    {
        return format!(
            "{awaiting} open task{} awaiting a human answer; `awaiting_answer` names the \
             question{}. No agent can make progress on {} until the answer is recorded",
            plural(awaiting, " is", "s are"),
            plural(awaiting, "", "s"),
            plural(awaiting, "it", "them"),
        );
    }
    let mut tail = String::new();
    if held > 0 {
        tail.push_str(&format!(
            ", and {held} held until a review delivers its verdict"
        ));
    }
    if recused > 0 {
        tail.push_str(&format!(
            ", and {recused} that this harness is recused from (they need another harness)"
        ));
    }
    if awaiting > 0 {
        tail.push_str(&format!(
            ", and {awaiting} awaiting a human answer before any agent can continue"
        ));
    }
    if incompatible > 0 {
        tail.push_str(&format!(
            ", and {incompatible} requiring capabilities this session does not advertise"
        ));
    }
    let standing_down = dispatch.in_recess.len();
    if standing_down > 0 {
        tail.push_str(&format!(
            ", and {standing_down} in a project whose queue the human stood down"
        ));
    }
    match (blocked, deferred) {
        // Both zero with a tail means everything left is held or recused; the
        // tail carries the counts.
        (0, 0) if !tail.is_empty() => {
            format!("nothing is workable: {}", tail.trim_start_matches(", and "))
        }
        (0, 0) => "nothing is open in this project; the queue is empty".to_string(),
        (0, n) => format!(
            "{n} task{} ready, but every one of them touches files another agent is \
             working right now; try again once they finish{tail}",
            plural(n, " is", "s are")
        ),
        (n, 0) => format!(
            "{n} task{} open, but all of them are waiting on unfinished dependencies{tail}",
            plural(n, " is", "s are")
        ),
        (blocked, deferred) => format!(
            "nothing is workable: {blocked} task{} waiting on dependencies and \
             {deferred} overlapping files another agent is in{tail}",
            plural(blocked, " is", "s are")
        ),
    }
}

fn plural(n: usize, one: &'static str, many: &'static str) -> &'static str {
    if n == 1 {
        one
    } else {
        many
    }
}

/// What the witness saw, in the shape every tool that reports it uses.
///
/// Flattened into the results rather than nested, so an agent reading a
/// `task_update` reply sees `contended` at the top level next to its own note
/// instead of having to know there is a witness at all. Every field disappears
/// when it is empty, which is the ordinary case and the quiet one.
#[derive(Debug, Default, Serialize)]
struct Evidence {
    /// Whether this task has changed anything at all: `read-only` when the
    /// tree has not moved since it was claimed, `modified 3 files` when it
    /// has. Absent where hird was not watching, which is not the same as
    /// nothing having happened — say which of the two you are reporting.
    #[serde(skip_serializing_if = "Option::is_none")]
    footprint: Option<String>,
    /// Files that moved while you held this task, as `path (modified)`. Not a
    /// claim about who moved them — one checkout, several agents.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    changed: Vec<String>,
    /// Files you and another live agent both declared, which have since moved.
    /// Somebody's copy is out of date; the sentence says whose and what to do.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    contended: Vec<String>,
    /// Files that moved under you that none of your declared patterns covers.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    undeclared: Vec<String>,
    /// Set when the working tree was too dirty to fingerprint in full, so
    /// `changed` is a floor rather than the whole story. Reported rather than
    /// swallowed: a list that silently stops short reads exactly like a list
    /// that found everything.
    #[serde(skip_serializing_if = "Option::is_none")]
    partial: Option<String>,
    /// Whether another agent held a task in this project at the same time.
    /// Not reported — it only decides how confidently the advice can speak.
    #[serde(skip)]
    alone: bool,
    /// The same answer `footprint` is written from, kept in its typed form so
    /// a result assembled after the task has stopped being worked can re-say
    /// it without the hedge a task still in flight needs.
    #[serde(skip)]
    watched: Footprint,
}

impl Evidence {
    /// The same evidence, re-said for a task that has just stopped being
    /// worked.
    ///
    /// The last look has to be taken while the task is still live, or its
    /// footprint would miss whatever it did on the way out — so by the time
    /// the reply is written the hedge in "read-only so far" is one call out
    /// of date. There is no more work coming: it is the whole story now.
    fn settled(mut self) -> Evidence {
        self.footprint = self.watched.describe(false);
        self
    }

    /// The one thing to do about it, or nothing.
    ///
    /// Ordered by cost of ignoring it: losing another agent's work beats
    /// leaving the board's picture of your file scope wrong.
    fn advice(&self) -> Option<String> {
        if !self.contended.is_empty() {
            return Some(
                "a file you declared has changed under another agent that declared it too — \
                 re-read it before your next write, and tell the human"
                    .to_string(),
            );
        }
        if !self.undeclared.is_empty() {
            let listed = self.undeclared.join(", ");
            // Alone in the project, a file that moved moved because of you.
            // With another agent live, hird watched the file and not the
            // keyboard, and the advice has to leave room for that.
            return Some(if self.alone {
                format!(
                    "you have changed {} nobody was told about: {listed}. Call task_scope \
                     with {} so the other agents' collision checks can see it",
                    plural(self.undeclared.len(), "a file", "files"),
                    plural(self.undeclared.len(), "it", "them"),
                )
            } else {
                format!(
                    "{listed} moved while you held this task and nobody has declared {}. If \
                     the edit was yours, call task_scope so the other agents can see it; if \
                     it was not, another agent is working outside what it declared",
                    plural(self.undeclared.len(), "it", "them"),
                )
            });
        }
        None
    }
}

#[derive(Debug, Serialize)]
struct ScopeResult {
    seq: i64,
    paths: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    overlaps: Vec<String>,
    #[serde(flatten)]
    witness: Evidence,
    /// What to do about it, in one sentence.
    advice: String,
}

#[derive(Debug, Serialize)]
struct SplitResult {
    seq: i64,
    status: Status,
    /// The pieces, in the order they were filed.
    subtasks: Vec<SubtaskRow>,
    note: String,
}

#[derive(Debug, Serialize)]
struct SubtaskRow {
    seq: i64,
    title: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    waiting_for: Vec<i64>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    requires: Vec<String>,
}

#[derive(Debug, Serialize)]
struct UpdateResult {
    seq: i64,
    status: Status,
    lease_expires_at: String,
    note_recorded: String,
    /// The task's links after this update, when it set any.
    #[serde(skip_serializing_if = "Option::is_none")]
    links: Option<TaskLinks>,
    /// Dependencies of this task that have stopped being `done` since the
    /// claim let it through — sent back by a review, reopened, cancelled or
    /// failed. One sentence each; the first also lands in `advice`.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    ground_shifted: Vec<String>,
    #[serde(flatten)]
    witness: Evidence,
    #[serde(skip_serializing_if = "Option::is_none")]
    advice: Option<String>,
}

#[derive(Debug, Serialize)]
struct FinishResult {
    seq: i64,
    status: Status,
    result: String,
    /// What the working tree says this task did, which is not the same source
    /// as `result` — that is the agent's own account of itself.
    #[serde(flatten)]
    witness: Evidence,
    /// The review task this completion filed, if the work was marked for one.
    /// It is scoped to the files that moved and recused from your harness, so
    /// another agent will pick it up. Tell the human its number.
    #[serde(skip_serializing_if = "Option::is_none")]
    review_filed: Option<i64>,
    /// When the finished task was a review: what your verdict did, per task
    /// judged. Relay these sentences to the human as they stand.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    verdicts: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    advice: Option<String>,
}

#[derive(Debug, Serialize)]
struct ReleaseResult {
    #[serde(flatten)]
    finish: FinishResult,
    /// Present when this was not an ordinary handoff: no agent can claim the
    /// task until the human records an answer.
    #[serde(skip_serializing_if = "Option::is_none")]
    awaiting_answer: Option<String>,
}

impl FinishResult {
    fn new(
        seq: i64,
        status: Status,
        result: String,
        witness: Evidence,
        review_filed: Option<i64>,
        delivered: &[Delivered],
    ) -> FinishResult {
        let witness = witness.settled();
        // A filed review outranks the witness's advice: it is the thing the
        // agent has to say out loud, and it is about to stop being this
        // agent's business entirely. A delivered verdict outranks the witness
        // for the same reason: the queue already acted on it.
        let advice = match (review_filed, delivered) {
            (Some(review), _) => Some(format!(
                "this work was marked for review, so task {review} is now open for an agent in \
                 another harness — you cannot take it yourself. Tell the human."
            )),
            (None, [.., _]) if delivered.iter().any(|d| d.reopened) => Some(
                "the work you sent back is open again carrying your findings; any agent — \
                 its author included — may pick it up, and completing it will file a fresh \
                 review. Tell the human the verdict."
                    .to_string(),
            ),
            (None, [.., _]) => Some(
                "your verdict is on the record. Tell the human what you concluded.".to_string(),
            ),
            (None, []) => witness.advice(),
        };
        FinishResult {
            seq,
            status,
            result,
            advice,
            witness,
            review_filed,
            verdicts: delivered.iter().map(Delivered::describe).collect(),
        }
    }
}

#[derive(Debug, Serialize)]
struct MemStoreResult {
    id: String,
    project: String,
    content: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    tags: Vec<String>,
    actor: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    task_seq: Option<i64>,
    created_at: String,
    /// True when this exact sentence was already on file. Nothing was
    /// duplicated: the original assertion keeps its id and its author, you have
    /// been recorded as another voice for it, and its footing has been re-taken
    /// against the code as it stands now.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    affirmed: bool,
    /// The files this fact is now on record as having been read off.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    anchored_to: Vec<String>,
    /// Who has stated it, if more than one agent has.
    #[serde(skip_serializing_if = "Option::is_none")]
    corroboration: Option<String>,
}

#[derive(Debug, Serialize)]
struct MemSearchResult<'a> {
    query: &'a str,
    project: &'a str,
    all_projects: bool,
    count: usize,
    assertions: Vec<AssertionRow>,
}

#[derive(Debug, Serialize)]
struct AssertionRow {
    id: String,
    content: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    tags: Vec<String>,
    actor: String,
    created_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    project: Option<String>,
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    superseded: bool,
    /// `firm`, `shaky` or `orphaned` — how the files this was learned against
    /// compare with the ones on disk right now. Absent means hird has no
    /// footing for it and is not guessing.
    #[serde(skip_serializing_if = "Option::is_none")]
    standing: Option<&'static str>,
    /// The same, as a sentence you can relay.
    #[serde(skip_serializing_if = "Option::is_none")]
    footing: Option<String>,
}

impl AssertionRow {
    fn new(a: Assertion, show_project: bool, standing: Option<&Standing>) -> AssertionRow {
        let tags = a.tag_list().into_iter().map(str::to_string).collect();
        let standing = standing.filter(|s| **s != Standing::Unanchored);
        AssertionRow {
            id: a.id,
            tags,
            content: a.content,
            actor: a.actor,
            created_at: a.created_at,
            project: show_project.then_some(a.project),
            superseded: a.superseded_by.is_some(),
            standing: standing.map(Standing::as_str),
            footing: standing.and_then(Standing::describe),
        }
    }
}

// ---------------------------------------------------------------------- tools

#[tool_router]
impl HirdMcp {
    /// List tasks in the queue. Run this first to see what work exists.
    #[tool(name = "task_list")]
    async fn task_list(
        &self,
        Parameters(args): Parameters<TaskListArgs>,
    ) -> Result<String, String> {
        let status = match args
            .status
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            Some(raw) => Some(raw.parse::<Status>().map_err(|e| e.to_string())?),
            None => None,
        };
        let scope = self.scope(args.all_projects);
        let show_project = scope.is_all();

        let actor = self.actor();
        let (released, dispatched, tasks, unmet, questions, recused, standing) =
            self.with_db(|db| {
                let released = db
                    .tasks()
                    .sweep_leases()
                    .map(|s| s.expired)
                    .unwrap_or_default();
                // Expiry is enforced lazily, so this sweep is the moment the
                // queue first knows these tasks are back in the pool — which
                // makes it the herald's moment too.
                let dispatched = self.expired_announcements(db, &released);
                let listed = db.tasks().list(&scope, status);
                // Which of these this session is barred from. Only the open ones
                // are worth asking about: a claimed or finished task's claimability
                // is not the reader's question.
                let recused: BTreeMap<i64, Recusal> = listed
                    .as_ref()
                    .map(|tasks| {
                        tasks
                            .iter()
                            .filter(|t| t.status == Status::Open)
                            .filter_map(|t| {
                                db.recusals()
                                    .bars(t.seq, &actor)
                                    .ok()
                                    .flatten()
                                    .map(|r| (t.seq, r))
                            })
                            .collect()
                    })
                    .unwrap_or_default();
                (
                    released,
                    dispatched,
                    listed,
                    db.deps()
                        .unmet_map(&scope, self.shared.config.clearance())
                        .unwrap_or_default(),
                    db.questions().unanswered_map(&scope).unwrap_or_default(),
                    recused,
                    db.verdicts().standing(&scope).unwrap_or_default(),
                )
            });
        self.announce(&dispatched);
        let tasks = tasks.map_err(stringify)?;

        json(&TaskListResult {
            project: &self.session.project,
            all_projects: scope.is_all(),
            count: tasks.len(),
            tasks: tasks
                .into_iter()
                .map(|t| {
                    let blocked = unmet.get(&t.seq).cloned().unwrap_or_default();
                    let question = questions.get(&t.seq).cloned();
                    let barred = recused.get(&t.seq).cloned();
                    let verdict = standing.get(&t.seq).copied();
                    TaskRow::from_summary(
                        t,
                        show_project,
                        blocked,
                        question,
                        barred,
                        verdict,
                        &self.session.capabilities,
                    )
                })
                .collect(),
            released,
        })
    }

    /// Read one task in full: instructions, dependencies, file scope and history.
    #[tool(name = "task_get")]
    async fn task_get(&self, Parameters(args): Parameters<SeqArgs>) -> Result<String, String> {
        self.sweep_announcing();
        let recall_limit = self.shared.config.recall_limit();
        let detail = self.with_db(|db| {
            let task = db.tasks().get(args.seq)?;
            let (waiting_for, conflicts) = db
                .tasks()
                .readiness(args.seq, self.shared.config.clearance())?;
            Ok::<_, Error>(TaskDetail::new(
                task.clone(),
                TaskContext {
                    waiting_for,
                    ground: db.deps().ground(args.seq)?,
                    blocks: db
                        .deps()
                        .dependents(args.seq)?
                        .into_iter()
                        .map(|b| b.seq)
                        .collect(),
                    paths: db.scopes().for_task(args.seq)?,
                    conflicts,
                    recusals: db.recusals().for_task(args.seq)?,
                    verdicts: db.verdicts().for_task(args.seq)?,
                    delivered: db.verdicts().of_review(args.seq)?,
                    recalled: self.recall(db, args.seq, recall_limit),
                    witness: self.evidence(db, args.seq),
                    events: db.tasks().events(&task.id, EVENT_WINDOW)?,
                    questions: db.questions().for_task(args.seq)?,
                    requirements: db.requirements().for_task(args.seq)?,
                    links: db.links().for_task(args.seq)?,
                },
            ))
        });
        json(&detail.map_err(stringify)?)
    }

    /// Claim a task before working on it. Fails if someone else already holds
    /// it, or if it is still waiting on another task.
    #[tool(name = "task_claim")]
    async fn task_claim(
        &self,
        Parameters(args): Parameters<TaskClaimArgs>,
    ) -> Result<String, String> {
        self.sweep_announcing();
        let actor = self.actor();
        let ttl = self.shared.config.lease_ttl();
        let paths = args.paths.unwrap_or_default();
        let policy = self.shared.config.on_conflict();
        let recall_limit = self.shared.config.recall_limit();
        // Recall runs after the claim, so it sees the paths this call just
        // declared — claiming with `paths` is what makes the file-scope half
        // of recall work on the very first call.
        let (claim, recalled, previously) = self
            .with_db(|db| {
                let claim = db
                    .tasks()
                    .gated(self.session.gate.as_deref())
                    .escalating_after(self.shared.config.max_attempts)
                    .claim_scoped_with_capabilities(
                        args.seq,
                        &actor,
                        ttl,
                        &paths,
                        policy,
                        self.shared.config.clearance(),
                        &self.session.capabilities,
                    )?;
                // The tree as it stands is this task's baseline, so anything
                // that moves from here is inside its window and everything
                // already dirty is not.
                self.begin_witnessing(db, args.seq);
                Ok::<_, Error>((
                    claim,
                    self.recall(db, args.seq, recall_limit),
                    self.inheritance(db, args.seq),
                ))
            })
            .map_err(stringify)?;

        json(&ClaimResult::new(
            claim,
            actor,
            self.heartbeat_minutes(),
            recalled,
            previously,
        ))
    }

    /// Be handed the next task worth doing, already claimed. Use this when the
    /// human says to work the queue without naming a task number.
    #[tool(name = "task_next")]
    async fn task_next(
        &self,
        Parameters(args): Parameters<TaskNextArgs>,
    ) -> Result<String, String> {
        self.sweep_announcing();
        let actor = self.actor();
        let ttl = self.shared.config.lease_ttl();
        let scope = self.scope(args.all_projects);
        let avoid = self.shared.config.avoid_conflicts(args.avoid_conflicts);
        let recall_limit = self.shared.config.recall_limit();
        let (dispatch, recalled, previously) = self
            .with_db(|db| {
                let dispatch = db
                    .tasks()
                    .gated(self.session.gate.as_deref())
                    .escalating_after(self.shared.config.max_attempts)
                    .claim_next_with_capabilities(
                        &actor,
                        ttl,
                        &scope,
                        avoid,
                        self.shared.config.clearance(),
                        &self.session.capabilities,
                    )?;
                let (recalled, previously) = match &dispatch.claim {
                    Some(claim) => {
                        self.begin_witnessing(db, claim.task.seq);
                        (
                            self.recall(db, claim.task.seq, recall_limit),
                            self.inheritance(db, claim.task.seq),
                        )
                    }
                    None => (Vec::new(), None),
                };
                Ok::<_, Error>((dispatch, recalled, previously))
            })
            .map_err(stringify)?;

        json(&NextResult::new(
            dispatch,
            actor,
            self.heartbeat_minutes(),
            recalled,
            previously,
        ))
    }

    /// Say which files a task you hold is going to change, and find out
    /// whether another agent is already working in them.
    #[tool(name = "task_scope")]
    async fn task_scope(
        &self,
        Parameters(args): Parameters<TaskScopeArgs>,
    ) -> Result<String, String> {
        self.sweep_announcing();
        let actor = self.actor();
        let policy = self.shared.config.on_conflict();
        let (paths, conflicts, evidence) = self
            .with_db(|db| {
                // Holder-only, like every other write to a claimed task.
                let task = db.tasks().get(args.seq)?;
                if !task.status.is_active() || task.claimed_by.as_deref() != Some(actor.as_str()) {
                    return Err(Error::NotHolder {
                        seq: args.seq,
                        status: task.status,
                        holder: task.claimed_by,
                        actor: actor.clone(),
                    });
                }
                let conflicts = db.scopes().declare(args.seq, &args.paths, &actor, policy)?;
                // Declaring is the moment the witness has something to say:
                // these patterns are what the contention detector needs, and
                // the tree may already have moved under them.
                Ok::<_, Error>((
                    db.scopes().for_task(args.seq)?,
                    conflicts,
                    self.witnessed(db, args.seq),
                ))
            })
            .map_err(stringify)?;

        let overlaps = describe_all(&conflicts);
        let advice = match (evidence.advice(), overlaps.is_empty()) {
            (Some(urgent), _) => urgent,
            (None, false) => "tell the human about the overlap before editing those files, \
                              and prefer to work elsewhere until it clears"
                .to_string(),
            (None, true) => "no other agent is in these files; go ahead".to_string(),
        };
        json(&ScopeResult {
            seq: args.seq,
            paths,
            overlaps,
            witness: evidence,
            advice,
        })
    }

    /// Break a task you hold into pieces other agents can work in parallel.
    /// The original waits for them and goes back in the pool.
    #[tool(name = "task_split")]
    async fn task_split(
        &self,
        Parameters(args): Parameters<TaskSplitArgs>,
    ) -> Result<String, String> {
        self.sweep_announcing();
        let actor = self.actor();
        let empty: Vec<String> = Vec::new();
        let subtasks: Vec<Subtask<'_>> = args
            .subtasks
            .iter()
            .map(|s| Subtask {
                title: &s.title,
                body: s.body.as_deref().unwrap_or(""),
                priority: s.priority,
                paths: s.paths.as_ref().unwrap_or(&empty),
                requirements: s.requires.as_ref().unwrap_or(&empty),
            })
            .collect();
        let sequential = args.sequential.unwrap_or(false);

        let (parent, children, dispatched) = self
            .with_db(|db| {
                let (parent, children) =
                    db.tasks().split(args.seq, &actor, &subtasks, sequential)?;
                // The pieces are open the moment the split commits — all of
                // them workable at once, or only the first of a sequence.
                let dispatched: Vec<Announcement> = children
                    .iter()
                    .filter_map(|child| self.dispatchable(db, Cause::Filed, child.seq))
                    .collect();
                Ok::<_, Error>((parent, children, dispatched))
            })
            .map_err(stringify)?;
        self.announce(&dispatched);

        let mut previous: Option<i64> = None;
        let rows = children
            .iter()
            .enumerate()
            .map(|(index, child)| {
                let waiting_for = match previous.replace(child.seq) {
                    Some(prior) if sequential => vec![prior],
                    _ => Vec::new(),
                };
                SubtaskRow {
                    seq: child.seq,
                    title: child.title.clone(),
                    waiting_for,
                    requires: args.subtasks[index]
                        .requires
                        .as_ref()
                        .map(|r| {
                            crate::capability::normalize_all(r)
                                .expect("subtask requirements were validated before filing")
                        })
                        .unwrap_or_default(),
                }
            })
            .collect();

        json(&SplitResult {
            seq: parent.seq,
            status: parent.status,
            subtasks: rows,
            note: format!(
                "task {} is back in the pool and now waits for {} piece{}; you no longer \
                 hold it. Call task_next for your own next piece of work",
                parent.seq,
                children.len(),
                if children.len() == 1 { "" } else { "s" }
            ),
        })
    }

    /// Hand back a task you hold without finishing it, so another agent can
    /// take it. Prefer task_fail when the task itself is the problem.
    #[tool(name = "task_release")]
    async fn task_release(
        &self,
        Parameters(args): Parameters<TaskReleaseArgs>,
    ) -> Result<String, String> {
        self.sweep_announcing();
        let actor = self.actor();
        let question = args.question.as_deref().map(str::trim);
        let (task, evidence, dispatched, asked) = self
            .with_db(|db| {
                // Before the release, while this session still holds the lease
                // and the record of what moved under it is still its own.
                let evidence = self.witnessed(db, args.seq);
                let (task, asked) = match question {
                    Some(question) => {
                        let (task, asked) =
                            db.tasks()
                                .release_asking(args.seq, &actor, &args.reason, question)?;
                        (task, Some(asked))
                    }
                    None => (db.tasks().release(args.seq, &actor, &args.reason)?, None),
                };
                // An ordinary release is back in the pool. A question release
                // is deliberately not announced: it is waiting for a human,
                // not another agent.
                let dispatched = asked
                    .is_none()
                    .then(|| self.dispatchable(db, Cause::Released, task.seq))
                    .flatten();
                Ok::<_, Error>((task, evidence, dispatched, asked))
            })
            .map_err(stringify)?;
        self.announce(dispatched.as_slice());
        // The question hook is the announcement's mirror: it fires exactly
        // when dispatch stays quiet, because the one being summoned is the
        // human the task now waits on. After the commit, like every hook, so
        // its own `hird` calls find the question already on the board.
        if let (Some(hook), Some(asked)) = (self.shared.question_herald.as_ref(), asked.as_ref()) {
            hook.announce(&crate::herald::RaisedQuestion {
                seq: task.seq,
                title: task.title.clone(),
                project: task.project.clone(),
                question: asked.question.clone(),
                asked_by: asked.asked_by.clone(),
            });
        }
        json(&ReleaseResult {
            finish: FinishResult::new(
                task.seq,
                task.status,
                args.reason.trim().to_string(),
                evidence,
                // Releasing is not finishing, so nothing is filed to review.
                None,
                &[],
            ),
            awaiting_answer: asked.map(|q| q.question),
        })
    }

    /// Record progress and renew your lease. Only the holder may call this.
    /// Optionally record where the work lives: `branch`, `worktree`, `pr_url`.
    #[tool(name = "task_update")]
    async fn task_update(
        &self,
        Parameters(args): Parameters<TaskUpdateArgs>,
    ) -> Result<String, String> {
        self.sweep_announcing();
        let start = match args
            .status
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            None => false,
            Some(raw) => match raw.parse::<Status>() {
                Ok(Status::InProgress) => true,
                _ => {
                    return Err(format!(
                        "task_update can only set status to \"in_progress\" (got {raw:?}); \
                         use task_complete or task_fail to finish a task"
                    ))
                }
            },
        };
        let actor = self.actor();
        let ttl = self.shared.config.lease_ttl();
        let change = LinkChange {
            branch: args.branch,
            worktree: args.worktree,
            pr_url: args.pr_url,
        };
        let asked_to_link = !change.is_empty();
        let (task, links, evidence, shifted) = self
            .with_db(|db| {
                let (task, links) = db
                    .tasks()
                    .update_linked(args.seq, &actor, start, &args.note, ttl, &change)?;
                // The heartbeat is the natural place to look: the agent is
                // between edits, and this is the last chance to tell it a file
                // moved before it writes the next one. The same goes for the
                // ground: readiness was checked at the claim and never again,
                // so this is where a blocker that has stopped being done —
                // sent back, reopened, cancelled — reaches the one agent
                // building on it. Best-effort like every rider: a failure here
                // may not cost the agent the update it actually asked for.
                let shifted = db.deps().shifted(args.seq).unwrap_or_default();
                Ok::<_, Error>((task, links, self.witnessed(db, args.seq), shifted))
            })
            .map_err(stringify)?;

        let ground_shifted: Vec<String> = shifted.iter().map(Shifted::describe).collect();
        // Shifted ground outranks the witness's advice: a contended file costs
        // an edit, a sent-back foundation costs the task.
        let advice = ground_shifted
            .first()
            .cloned()
            .or_else(|| evidence.advice());
        json(&UpdateResult {
            seq: task.seq,
            status: task.status,
            lease_expires_at: task.lease_expires_at.unwrap_or_default(),
            note_recorded: args.note.trim().to_string(),
            // Echoed only when asked for, so a plain check-in reads as before.
            links: links.filter(|_| asked_to_link),
            ground_shifted,
            advice,
            witness: evidence,
        })
    }

    /// Finish a task you hold, with a summary of what was done. A review must
    /// also carry a verdict: upheld, or sent_back.
    #[tool(name = "task_complete")]
    async fn task_complete(
        &self,
        Parameters(args): Parameters<TaskCompleteArgs>,
    ) -> Result<String, String> {
        self.sweep_announcing();
        let verdict = match args
            .verdict
            .as_deref()
            .map(str::trim)
            .filter(|v| !v.is_empty())
        {
            Some(raw) => Some(raw.parse::<Verdict>().map_err(|e| e.to_string())?),
            None => None,
        };
        let actor = self.actor();
        let (task, evidence, dispatched) = self
            .with_db(|db| {
                // Last look, taken while the task is still live so its
                // footprint is complete and any contention is still true.
                let evidence = self.witnessed(db, args.seq);
                // If finishing will file a review, resolve the diff of the
                // work now — the sweep above has just brought the record and
                // the kept versions up to date, and the reviewer should be
                // handed the change itself rather than a list of file names.
                let exhibit = self.session.witness.as_ref().and_then(|witness| {
                    let marked = db.tasks().get(args.seq).map(|t| t.review).unwrap_or(false);
                    if !marked {
                        return None;
                    }
                    let shown = crate::exhibit::assemble(db, witness, args.seq).ok()?;
                    let text = crate::exhibit::render(&shown);
                    if text.trim().is_empty() {
                        return None;
                    }
                    Some(crate::exhibit::clipped(
                        &text,
                        crate::exhibit::BRIEF_MAX_BYTES,
                        args.seq,
                    ))
                });
                // And the last word on what this task learned: its facts are
                // statements about the tree it is leaving behind, not the one
                // it found halfway through its own edits.
                footing::settle(db, self.footing(), args.seq);
                let task = db
                    .tasks()
                    .gated(self.session.gate.as_deref())
                    .escalating_after(self.shared.config.max_attempts)
                    .complete_showing(
                        args.seq,
                        &actor,
                        &args.result,
                        verdict,
                        exhibit.as_deref(),
                    )?;
                let dispatched = self.dispatched(db, &task);
                Ok::<_, Error>((task, evidence, dispatched))
            })
            .map_err(stringify)?;
        self.announce(&dispatched);
        json(&FinishResult::new(
            task.task.seq,
            task.task.status,
            task.task.result.unwrap_or_default(),
            evidence,
            task.review,
            &task.verdicts,
        ))
    }

    /// Give up on a task you hold, saying why. The human can reopen it later.
    #[tool(name = "task_fail")]
    async fn task_fail(
        &self,
        Parameters(args): Parameters<TaskFailArgs>,
    ) -> Result<String, String> {
        self.sweep_announcing();
        let actor = self.actor();
        let (task, evidence) = self
            .with_db(|db| {
                let evidence = self.witnessed(db, args.seq);
                footing::settle(db, self.footing(), args.seq);
                let task = db
                    .tasks()
                    .gated(self.session.gate.as_deref())
                    .escalating_after(self.shared.config.max_attempts)
                    .fail(args.seq, &actor, &args.reason)?;
                Ok::<_, Error>((task, evidence))
            })
            .map_err(stringify)?;
        json(&FinishResult::new(
            task.task.seq,
            task.task.status,
            task.task.result.unwrap_or_default(),
            evidence,
            task.review,
            &task.verdicts,
        ))
    }

    /// Record one durable fact so other agents and sessions can find it later.
    #[tool(name = "mem_store")]
    async fn mem_store(
        &self,
        Parameters(args): Parameters<MemStoreArgs>,
    ) -> Result<String, String> {
        let actor = self.actor();
        let (recorded, anchored, corroboration) = self
            .with_db(|db| {
                let recorded = db.memory().record(NewAssertion {
                    project: &self.session.project,
                    content: &args.content,
                    tags: args.tags.as_deref().unwrap_or(""),
                    actor: &actor,
                    task_seq: args.task_seq,
                })?;
                // Anchoring runs on both paths, and that is the whole
                // re-grounding loop: an agent that rediscovers a fact says it
                // again, and saying it again is what re-takes its footing
                // against the code as it stands today.
                let ground = footing::ground(db, args.task_seq, args.paths.as_deref());
                let anchored =
                    footing::anchor(db, self.footing(), &recorded.assertion().id, &ground)
                        .unwrap_or_default();
                let corroboration = footing::corroboration(db, recorded.assertion());
                Ok::<_, Error>((recorded, anchored, corroboration))
            })
            .map_err(stringify)?;

        let affirmed = recorded.was_affirmed();
        let assertion = recorded.into_assertion();
        let tags = assertion
            .tag_list()
            .into_iter()
            .map(str::to_string)
            .collect();
        json(&MemStoreResult {
            id: assertion.id,
            project: assertion.project,
            tags,
            content: assertion.content,
            actor: assertion.actor,
            task_seq: args.task_seq,
            created_at: assertion.created_at,
            affirmed,
            anchored_to: anchored.into_iter().map(|a| a.path).collect(),
            corroboration,
        })
    }

    /// Search recorded facts before working something out from scratch.
    #[tool(name = "mem_search")]
    async fn mem_search(
        &self,
        Parameters(args): Parameters<MemSearchArgs>,
    ) -> Result<String, String> {
        let scope = self.scope(args.all_projects);
        let show_project = scope.is_all();
        let query = MemoryQuery::new(&args.query, scope.clone())
            .limit(args.limit.unwrap_or(20).clamp(1, 200))
            .include_superseded(args.include_superseded.unwrap_or(false));

        let (hits, standings) = self
            .with_db(|db| {
                let hits = db.memory().search(&query)?;
                let ids: Vec<String> = hits.iter().map(|a| a.id.clone()).collect();
                let standings = footing::standings(db, self.footing(), &self.session.project, &ids);
                Ok::<_, Error>((hits, standings))
            })
            .map_err(stringify)?;

        json(&MemSearchResult {
            query: &args.query,
            project: &self.session.project,
            all_projects: scope.is_all(),
            count: hits.len(),
            assertions: hits
                .into_iter()
                .map(|a| {
                    let standing = standings.get(&a.id).cloned();
                    AssertionRow::new(a, show_project, standing.as_ref())
                })
                .collect(),
        })
    }
}

#[tool_handler]
impl ServerHandler for HirdMcp {
    fn get_info(&self) -> ServerConfig {
        ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(
                Implementation::new("hird", env!("CARGO_PKG_VERSION"))
                    .with_title("hird work queue & memory"),
            )
            .with_instructions(self.instructions())
    }

    /// Every call is a chance to learn who is calling.
    ///
    /// Written out rather than left to `#[tool_handler]` for one reason: under
    /// the 2026-07-28 lifecycle there is no `initialize`, so this is where a
    /// client's name for itself arrives. It is offered to the identity, which
    /// keeps it only if the environment left the harness unnamed. Nothing here
    /// can fail the call — a session whose client will not say who it is works
    /// exactly as it did before, filed as `unknown`.
    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, ErrorData> {
        if let Some(client) = context.client_info() {
            self.session.agent.name_from_client(&client.name);
        }
        Self::tool_router()
            .call(ToolCallContext::new(self, request, context))
            .await
    }

    /// List tools with the cache hints required by MCP 2026-07-28.
    ///
    /// Tool definitions are fixed for the lifetime of this binary, but the
    /// answer is private to this hird process and cheap to rebuild. A zero TTL
    /// also keeps legacy and modern clients from retaining stale definitions
    /// across an upgrade.
    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, ErrorData> {
        Ok(
            ListToolsResult::with_all_items(Self::tool_router().list_all())
                .with_ttl_ms(0)
                .with_cache_scope(CacheScope::Private),
        )
    }

    /// What `server/discover` answers, for clients that never call `initialize`.
    ///
    /// The default answer is right and this states why, so that a later SDK
    /// default cannot quietly change it: these instructions name this project
    /// and are shaped by this machine's configuration, so they are nobody
    /// else's to reuse. Private, and stale the moment they are read.
    async fn discover(
        &self,
        _context: RequestContext<RoleServer>,
    ) -> Result<DiscoverResult, ErrorData> {
        Ok(DiscoverResult::from_server_info(
            self.supported_protocol_versions().into_owned(),
            self.get_info(),
        )
        .with_ttl_ms(0)
        .with_cache_scope(CacheScope::Private))
    }
}

/// A claimable task as the herald will tell it.
fn announcement(cause: Cause, claimable: Claimable) -> Announcement {
    Announcement {
        cause,
        seq: claimable.seq,
        title: claimable.title,
        project: claimable.project,
        recused: claimable.recused,
        requirements: claimable.requirements,
    }
}

/// Render a payload as compact JSON.
fn json<T: Serialize>(value: &T) -> Result<String, String> {
    serde_json::to_string(value).map_err(|e| format!("failed to encode result: {e}"))
}

/// Repository errors are already written as sentences for the model.
fn stringify(err: Error) -> String {
    err.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;

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

    fn server() -> HirdMcp {
        HirdMcp::new(
            Db::open_in_memory().unwrap(),
            AgentId::new("claude-code", "af31"),
            PROJECT.to_string(),
            Config::default(),
        )
    }

    fn capable_server(capabilities: &[&str]) -> HirdMcp {
        HirdMcp::with_capabilities(
            Db::open_in_memory().unwrap(),
            AgentId::new("codex", "fit1"),
            PROJECT.to_string(),
            Config::default(),
            capabilities.iter().map(|c| c.to_string()).collect(),
        )
        .unwrap()
    }

    /// A claim with no declared file scope, which is most of these tests.
    fn just(seq: i64) -> TaskClaimArgs {
        TaskClaimArgs { seq, paths: None }
    }

    fn parse(raw: Result<String, String>) -> Value {
        serde_json::from_str(&raw.expect("tool call succeeded")).unwrap()
    }

    fn seed(server: &HirdMcp, title: &str, body: &str) -> i64 {
        server
            .with_db(|db| db.tasks().create(PROJECT, title, body, 0, "cli"))
            .unwrap()
            .seq
    }

    /// Refuses every claim, so a test can see the twelve tools obey a gate.
    struct Closed;

    impl crate::gate::Gate for Closed {
        fn may_claim(&self, _: &rusqlite::Connection, _: &Task, _: &str) -> Result<(), String> {
            Err("this connection only reviews".into())
        }
    }

    fn gated_server() -> HirdMcp {
        let config = Config::default();
        let session = Session::new(
            AgentId::new("codex", "g1"),
            PROJECT.to_string(),
            Vec::new(),
            &config,
        )
        .unwrap()
        .with_role("reviewer")
        .with_gate(Arc::new(Closed));
        HirdMcp::connect(
            Arc::new(Shared::new(Db::open_in_memory().unwrap(), config)),
            session,
        )
    }

    #[tokio::test]
    async fn the_existing_tools_obey_the_gate_a_session_carries() {
        let s = gated_server();
        let seq = seed(&s, "write the parser", "");
        let err = s.task_claim(Parameters(just(seq))).await.unwrap_err();
        assert!(err.contains("this connection only reviews"), "{err}");

        let out = parse(
            s.task_next(Parameters(TaskNextArgs {
                all_projects: None,
                avoid_conflicts: None,
            }))
            .await,
        );
        assert!(out["claimed"].is_null(), "{out}");
        assert_eq!(out["gated"][0]["seq"], seq);
        assert!(
            out["idle"].as_str().unwrap().contains("may not take"),
            "{out}"
        );

        // The role it declared is stamped on what it does.
        s.with_db(|db| db.tasks().create(PROJECT, "x", "", 0, &s.actor()))
            .unwrap();
        let trail = s.with_db(|db| db.audit().for_task(2)).unwrap();
        assert_eq!(trail[0].role, "reviewer");
    }

    /// Holds every task whose title starts with "held", whoever asks.
    struct Holding;

    impl crate::gate::Gate for Holding {
        fn holds(&self, _: &rusqlite::Connection, task: &Task) -> Option<String> {
            task.title
                .starts_with("held")
                .then(|| "it waits on something the queue cannot see".into())
        }
    }

    /// The herald consults the session's gate before it summons anyone: a
    /// task every connection would be refused is not announced, while one the
    /// same finish released and the gate lets go is.
    #[tokio::test]
    async fn the_herald_stays_quiet_about_work_the_gate_holds() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("herald.log");
        let config = Config {
            dispatch_hook: format!("echo \"$HIRD_EVENT $HIRD_TASK\" >> {}", log.display()),
            ..Config::default()
        };
        let session = Session::new(
            AgentId::new("claude-code", "h1"),
            PROJECT.to_string(),
            Vec::new(),
            &config,
        )
        .unwrap()
        .with_gate(Arc::new(Holding));
        let s = HirdMcp::connect(
            Arc::new(Shared::new(Db::open_in_memory().unwrap(), config)),
            session,
        );
        let dep = seed(&s, "lay the ground", "");
        let held = seed(&s, "held on the ground", "");
        let free = seed(&s, "free on the ground", "");
        s.with_db(|db| {
            db.deps().add(held, dep, "cli").unwrap();
            db.deps().add(free, dep, "cli").unwrap();
        });
        s.task_claim(Parameters(just(dep))).await.unwrap();
        s.task_complete(Parameters(TaskCompleteArgs {
            seq: dep,
            result: "laid".into(),
            verdict: None,
        }))
        .await
        .unwrap();

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        let contents = loop {
            let contents = std::fs::read_to_string(&log).unwrap_or_default();
            if contents.contains(&format!("unblocked {free}")) {
                break contents;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "the hook never heard the release; log so far:\n{contents}"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        };
        // Hooks run detached and in no promised order: give a stray
        // announcement of the held task time to land before saying it never
        // did.
        std::thread::sleep(std::time::Duration::from_millis(300));
        let contents = std::fs::read_to_string(&log).unwrap_or(contents);
        assert!(!contents.contains(&format!(" {held}")), "{contents}");
        s.with_db(|db| {
            let reason = db.tasks().held_by(held, &Holding).unwrap().unwrap();
            assert!(reason.contains("cannot see"), "{reason}");
            assert!(db.tasks().held_by(free, &Holding).unwrap().is_none());
        });
    }

    #[tokio::test]
    async fn a_claim_hands_over_every_rejected_attempt_and_says_to_read_them() {
        let s = server();
        let seq = seed(&s, "write the parser", "");
        s.with_db(|db| {
            let ttl = std::time::Duration::from_secs(900);
            db.tasks().set_review(seq, true, "cli").unwrap();
            db.scopes()
                .declare(
                    seq,
                    &["src/p.rs".into()],
                    "cli",
                    crate::repo::OnConflict::Report,
                )
                .unwrap();
            db.tasks().claim(seq, "codex:b", ttl).unwrap();
            let review = db.tasks().complete(seq, "codex:b", "built").unwrap();
            let review = review.review.unwrap();
            db.tasks().claim(review, "copilot:r", ttl).unwrap();
            db.tasks()
                .complete_with(
                    review,
                    "copilot:r",
                    "the lexer drops tabs",
                    Some(Verdict::SentBack),
                )
                .unwrap();
        });
        let out = parse(s.task_claim(Parameters(just(seq))).await);
        assert_eq!(out["attempts"][0]["outcome"], "sent_back");
        assert_eq!(out["attempts"][0]["output"], "the lexer drops tabs");
        assert!(
            out["reminder"]
                .as_str()
                .unwrap()
                .contains("read `attempts`"),
            "{out}"
        );
        // A first claim carries no attempts field at all.
        let fresh = seed(&s, "another", "");
        let out = parse(s.task_claim(Parameters(just(fresh))).await);
        assert!(out.get("attempts").is_none(), "{out}");
    }

    #[tokio::test]
    async fn task_list_reports_scope_and_rows() {
        let s = server();
        seed(&s, "write the parser", "full instructions here");

        let out = parse(
            s.task_list(Parameters(TaskListArgs {
                status: None,
                all_projects: None,
            }))
            .await,
        );

        assert_eq!(out["project"], PROJECT);
        assert_eq!(out["all_projects"], false);
        assert_eq!(out["count"], 1);
        assert_eq!(out["tasks"][0]["seq"], 1);
        assert_eq!(out["tasks"][0]["status"], "open");
        // Absent fields are omitted rather than serialized as null.
        assert!(out["tasks"][0].get("holder").is_none());
        assert!(out["tasks"][0].get("project").is_none());
    }

    #[tokio::test]
    async fn task_list_rejects_an_unknown_status_with_the_valid_set() {
        let s = server();
        let err = s
            .task_list(Parameters(TaskListArgs {
                status: Some("blocked".into()),
                all_projects: None,
            }))
            .await
            .unwrap_err();
        assert!(err.contains("unknown status"), "{err}");
        assert!(err.contains("in_progress"), "{err}");
    }

    #[tokio::test]
    async fn task_list_can_widen_to_every_project() {
        let s = server();
        seed(&s, "here", "");
        s.with_db(|db| db.tasks().create("/elsewhere", "there", "", 0, "cli"))
            .unwrap();

        let scoped = parse(
            s.task_list(Parameters(TaskListArgs {
                status: None,
                all_projects: None,
            }))
            .await,
        );
        assert_eq!(scoped["count"], 1);

        let wide = parse(
            s.task_list(Parameters(TaskListArgs {
                status: None,
                all_projects: Some(true),
            }))
            .await,
        );
        assert_eq!(wide["count"], 2);
        // Cross-project listings say which project each task belongs to.
        assert!(wide["tasks"][0]["project"].is_string());
    }

    #[tokio::test]
    async fn task_get_returns_the_body_and_history() {
        let s = server();
        let seq = seed(&s, "write the parser", "start with the lexer");

        let out = parse(s.task_get(Parameters(SeqArgs { seq })).await);
        assert_eq!(out["body"], "start with the lexer");
        assert_eq!(out["events"][0]["kind"], "created");
        assert_eq!(out["events"][0]["actor"], "cli");
    }

    #[tokio::test]
    async fn task_get_on_a_missing_task_is_a_plain_sentence() {
        let s = server();
        assert_eq!(
            s.task_get(Parameters(SeqArgs { seq: 99 }))
                .await
                .unwrap_err(),
            "task 99 not found"
        );
    }

    #[tokio::test]
    async fn claiming_returns_the_body_and_the_heartbeat_reminder() {
        let s = server();
        let seq = seed(&s, "write the parser", "start with the lexer");

        let out = parse(s.task_claim(Parameters(just(seq))).await);
        assert_eq!(out["claimed"], seq);
        assert_eq!(out["holder"], "claude-code:af31");
        assert_eq!(out["body"], "start with the lexer");
        assert!(out["lease_expires_at"].as_str().unwrap().ends_with('Z'));
        assert!(out["reminder"].as_str().unwrap().contains("task_update"));
    }

    #[tokio::test]
    async fn a_losing_claim_names_the_holder_and_the_deadline() {
        let s = server();
        let seq = seed(&s, "t", "");
        s.with_db(|db| {
            db.tasks()
                .claim(seq, "codex:9f2c", Config::default().lease_ttl())
        })
        .unwrap();

        let err = s.task_claim(Parameters(just(seq))).await.unwrap_err();
        assert!(
            err.starts_with("task 1 is claimed by codex:9f2c until "),
            "{err}"
        );
    }

    #[tokio::test]
    async fn update_starts_work_and_renews_the_lease() {
        let s = server();
        let seq = seed(&s, "t", "");
        s.task_claim(Parameters(just(seq))).await.unwrap();

        let out = parse(
            s.task_update(Parameters(TaskUpdateArgs {
                seq,
                note: "  read the lexer  ".into(),
                status: Some("in_progress".into()),
                ..Default::default()
            }))
            .await,
        );
        assert_eq!(out["status"], "in_progress");
        assert_eq!(out["note_recorded"], "read the lexer");
        assert!(out["lease_expires_at"].as_str().unwrap().ends_with('Z'));
    }

    #[tokio::test]
    async fn update_refuses_to_be_used_as_a_finishing_move() {
        let s = server();
        let seq = seed(&s, "t", "");
        s.task_claim(Parameters(just(seq))).await.unwrap();

        let err = s
            .task_update(Parameters(TaskUpdateArgs {
                seq,
                note: "n".into(),
                status: Some("done".into()),
                ..Default::default()
            }))
            .await
            .unwrap_err();
        assert!(err.contains("task_complete or task_fail"), "{err}");
    }

    #[tokio::test]
    async fn only_the_holder_can_update_or_finish() {
        let s = server();
        let seq = seed(&s, "t", "");
        s.with_db(|db| {
            db.tasks()
                .claim(seq, "codex:9f2c", Config::default().lease_ttl())
        })
        .unwrap();

        for err in [
            s.task_update(Parameters(TaskUpdateArgs {
                seq,
                note: "n".into(),
                status: None,
                ..Default::default()
            }))
            .await
            .unwrap_err(),
            s.task_complete(Parameters(TaskCompleteArgs {
                seq,
                result: "r".into(),
                verdict: None,
            }))
            .await
            .unwrap_err(),
            s.task_fail(Parameters(TaskFailArgs {
                seq,
                reason: "r".into(),
            }))
            .await
            .unwrap_err(),
        ] {
            assert!(err.contains("held by codex:9f2c"), "{err}");
        }
    }

    #[tokio::test]
    async fn completing_and_failing_report_the_final_state() {
        let s = server();
        let done = seed(&s, "a", "");
        s.task_claim(Parameters(just(done))).await.unwrap();
        let out = parse(
            s.task_complete(Parameters(TaskCompleteArgs {
                seq: done,
                result: "merged".into(),
                verdict: None,
            }))
            .await,
        );
        assert_eq!(out["status"], "done");
        assert_eq!(out["result"], "merged");

        let bad = seed(&s, "b", "");
        s.task_claim(Parameters(just(bad))).await.unwrap();
        let out = parse(
            s.task_fail(Parameters(TaskFailArgs {
                seq: bad,
                reason: "no credentials".into(),
            }))
            .await,
        );
        assert_eq!(out["status"], "failed");
        assert_eq!(out["result"], "no credentials");
    }

    /// Work another harness finished and this one reviews: the completion is
    /// refused until it carries a verdict, and `sent_back` puts the work back
    /// on the board carrying the findings.
    async fn reviewed_work(s: &HirdMcp) -> (i64, i64) {
        let seq = seed(s, "port the loader", "keep the precedence");
        let review = s
            .with_db(|db| {
                db.tasks().set_review(seq, true, "cli")?;
                db.scopes().declare(
                    seq,
                    &["src/loader.rs".to_string()],
                    "cli",
                    crate::repo::OnConflict::Report,
                )?;
                db.tasks()
                    .claim(seq, "codex:9f2c", Config::default().lease_ttl())?;
                db.tasks().complete(seq, "codex:9f2c", "ported")
            })
            .unwrap()
            .review
            .expect("a review was filed");
        s.task_claim(Parameters(just(review))).await.unwrap();
        (seq, review)
    }

    #[tokio::test]
    async fn a_review_must_end_in_a_verdict_and_sent_back_reopens_the_work() {
        let s = server();
        let (seq, review) = reviewed_work(&s).await;

        let err = s
            .task_complete(Parameters(TaskCompleteArgs {
                seq: review,
                result: "the empty case is missed".into(),
                verdict: None,
            }))
            .await
            .unwrap_err();
        assert!(err.contains("upheld"), "{err}");
        assert!(err.contains("sent_back"), "{err}");

        let out = parse(
            s.task_complete(Parameters(TaskCompleteArgs {
                seq: review,
                result: "the empty case is missed; handle it in parse()".into(),
                verdict: Some("sent_back".into()),
            }))
            .await,
        );
        assert_eq!(out["status"], "done");
        assert!(
            out["verdicts"][0].as_str().unwrap().contains("sent back"),
            "{out}"
        );
        assert!(
            out["advice"].as_str().unwrap().contains("findings"),
            "{out}"
        );

        let detail = parse(s.task_get(Parameters(SeqArgs { seq })).await);
        assert_eq!(detail["status"], "open");
        assert!(
            detail["body"].as_str().unwrap().contains("empty case"),
            "the findings travel in the brief: {detail}"
        );
        assert!(
            detail["verdict"]
                .as_str()
                .unwrap()
                .contains("sent back by claude-code"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn a_claim_arrives_knowing_what_it_builds_on() {
        let s = server();
        let schema = seed(&s, "design the schema", "");
        let api = seed(&s, "port the api", "");
        s.with_db(|db| {
            db.deps().add(api, schema, "cli")?;
            db.tasks()
                .claim(schema, "codex:9f2c", Config::default().lease_ttl())?;
            db.tasks()
                .complete(schema, "codex:9f2c", "the schema lives in db.rs")
        })
        .unwrap();

        let out = parse(s.task_claim(Parameters(just(api))).await);
        assert_eq!(out["built_on"][0]["seq"], schema);
        assert_eq!(out["built_on"][0]["result"], "the schema lives in db.rs");
        assert_eq!(out["built_on"][0]["standing"], "done");
        // Nothing provisional, so the reminder spends no words on it.
        assert!(
            !out["reminder"].as_str().unwrap().contains("under review"),
            "{out}"
        );
    }

    #[tokio::test]
    async fn provisional_ground_is_flagged_on_the_claim_and_shifts_at_the_check_in() {
        let s = server();
        let (work, review) = reviewed_work(&s).await;
        let dependent = seed(&s, "use the loader", "");
        s.with_db(|db| db.deps().add(dependent, work, "cli"))
            .unwrap();

        // Claimed while the review is open: the handover says the ground is
        // provisional, and the reminder says what that means.
        let out = parse(s.task_claim(Parameters(just(dependent))).await);
        let standing = out["built_on"][0]["standing"].as_str().unwrap();
        assert!(
            standing.contains(&format!("under review {review}")),
            "{out}"
        );
        assert!(standing.contains("provisional"), "{out}");
        assert!(
            out["reminder"]
                .as_str()
                .unwrap()
                .contains("still under review"),
            "{out}"
        );

        // The verdict takes the ground away; the next heartbeat says so.
        parse(
            s.task_complete(Parameters(TaskCompleteArgs {
                seq: review,
                result: "the empty case is missed".into(),
                verdict: Some("sent_back".into()),
            }))
            .await,
        );
        let out = parse(
            s.task_update(Parameters(TaskUpdateArgs {
                seq: dependent,
                note: "wiring the loader in".into(),
                status: None,
                ..Default::default()
            }))
            .await,
        );
        let shifted = out["ground_shifted"][0].as_str().unwrap();
        assert!(
            shifted.contains(&format!("sent back by review {review}")),
            "{out}"
        );
        assert_eq!(out["advice"].as_str().unwrap(), shifted, "{out}");
    }

    #[tokio::test]
    async fn holds_keeps_dependents_off_the_board_until_the_verdict() {
        let s = HirdMcp::new(
            Db::open_in_memory().unwrap(),
            AgentId::new("claude-code", "af31"),
            PROJECT.to_string(),
            Config {
                under_review: crate::config::UnderReview::Holds,
                ..Config::default()
            },
        );
        // Work finished by this same harness, so the review that filed itself
        // is recused from us and the dependent is held — the queue has
        // nothing for this session, and has to say why.
        let work = seed(&s, "port the loader", "");
        let dependent = seed(&s, "use the loader", "");
        let review = s
            .with_db(|db| {
                db.deps().add(dependent, work, "cli")?;
                db.tasks().set_review(work, true, "cli")?;
                db.scopes().declare(
                    work,
                    &["src/loader.rs".to_string()],
                    "cli",
                    crate::repo::OnConflict::Report,
                )?;
                db.tasks()
                    .claim(work, "claude-code:9x9x", Config::default().lease_ttl())?;
                db.tasks().complete(work, "claude-code:9x9x", "ported")
            })
            .unwrap()
            .review
            .expect("a review was filed");

        let err = s.task_claim(Parameters(just(dependent))).await.unwrap_err();
        assert!(err.contains(&format!("under review {review}")), "{err}");
        assert!(err.contains("verdict"), "{err}");

        let out = parse(
            s.task_next(Parameters(TaskNextArgs {
                all_projects: None,
                avoid_conflicts: None,
            }))
            .await,
        );
        assert!(out.get("claimed").is_none(), "{out}");
        assert_eq!(out["held"][0]["seq"], dependent);
        assert_eq!(out["held"][0]["review"], review);
        assert!(out["idle"].as_str().unwrap().contains("verdict"), "{out}");
    }

    #[tokio::test]
    async fn an_upheld_verdict_marks_the_work_on_the_board() {
        let s = server();
        let (seq, review) = reviewed_work(&s).await;
        parse(
            s.task_complete(Parameters(TaskCompleteArgs {
                seq: review,
                result: "read it; it holds".into(),
                verdict: Some("upheld".into()),
            }))
            .await,
        );

        let list = parse(
            s.task_list(Parameters(TaskListArgs {
                status: None,
                all_projects: None,
            }))
            .await,
        );
        let row = list["tasks"]
            .as_array()
            .unwrap()
            .iter()
            .find(|t| t["seq"] == seq)
            .unwrap();
        assert_eq!(row["upheld"], true, "{row}");

        let detail = parse(s.task_get(Parameters(SeqArgs { seq: review })).await);
        assert!(
            detail["verdicts_delivered"][0]
                .as_str()
                .unwrap()
                .contains("upheld"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn a_verdict_on_ordinary_work_is_refused() {
        let s = server();
        let seq = seed(&s, "t", "");
        s.task_claim(Parameters(just(seq))).await.unwrap();
        let err = s
            .task_complete(Parameters(TaskCompleteArgs {
                seq,
                result: "done".into(),
                verdict: Some("upheld".into()),
            }))
            .await
            .unwrap_err();
        assert!(err.contains("not a review"), "{err}");
    }

    #[tokio::test]
    async fn mem_store_records_provenance_and_the_task_link() {
        let s = server();
        let seq = seed(&s, "t", "");

        let out = parse(
            s.mem_store(Parameters(MemStoreArgs {
                content: "the lexer lives in src/lex.rs".into(),
                tags: Some(" parser , code ".into()),
                task_seq: Some(seq),
                paths: None,
            }))
            .await,
        );
        assert_eq!(out["actor"], "claude-code:af31");
        assert_eq!(out["project"], PROJECT);
        assert_eq!(out["tags"], serde_json::json!(["parser", "code"]));
        assert_eq!(out["task_seq"], seq);
    }

    #[tokio::test]
    async fn mem_store_rejects_a_link_to_a_task_that_does_not_exist() {
        let s = server();
        let err = s
            .mem_store(Parameters(MemStoreArgs {
                content: "x".into(),
                tags: None,
                task_seq: Some(404),
                paths: None,
            }))
            .await
            .unwrap_err();
        assert_eq!(err, "task 404 not found");
    }

    #[tokio::test]
    async fn mem_search_finds_what_mem_store_wrote() {
        let s = server();
        s.mem_store(Parameters(MemStoreArgs {
            content: "the lexer lives in src/lex.rs".into(),
            tags: None,
            task_seq: None,
            paths: None,
        }))
        .await
        .unwrap();

        let out = parse(
            s.mem_search(Parameters(MemSearchArgs {
                query: "lexer".into(),
                limit: None,
                all_projects: None,
                include_superseded: None,
            }))
            .await,
        );
        assert_eq!(out["count"], 1);
        assert_eq!(
            out["assertions"][0]["content"],
            "the lexer lives in src/lex.rs"
        );
        assert_eq!(out["assertions"][0]["actor"], "claude-code:af31");
    }

    #[tokio::test]
    async fn mem_search_clamps_absurd_limits() {
        let s = server();
        for i in 0..5 {
            s.mem_store(Parameters(MemStoreArgs {
                content: format!("fact {i} about widgets"),
                tags: None,
                task_seq: None,
                paths: None,
            }))
            .await
            .unwrap();
        }
        let out = parse(
            s.mem_search(Parameters(MemSearchArgs {
                query: "widgets".into(),
                limit: Some(0),
                all_projects: None,
                include_superseded: None,
            }))
            .await,
        );
        assert_eq!(out["count"], 1, "limit 0 is clamped to 1, not to nothing");
    }

    /// The autonomous gap the herald must not have: a swarm working entirely
    /// through claim/next/complete never calls `task_list`, so the sweep
    /// those calls already perform has to be the one that announces.
    #[tokio::test]
    async fn an_expiry_noticed_by_task_next_is_announced() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("herald.log");
        let s = HirdMcp::new(
            Db::open_in_memory().unwrap(),
            AgentId::new("claude-code", "af31"),
            PROJECT.to_string(),
            Config {
                dispatch_hook: format!("echo \"$HIRD_EVENT $HIRD_TASK\" >> {}", log.display()),
                ..Config::default()
            },
        );
        let dead = seed(&s, "abandoned", "");
        let other = seed(&s, "other work", "");
        s.with_db(|db| {
            db.tasks()
                .claim(dead, "codex:dead", Config::default().lease_ttl())
                .unwrap();
            db.conn()
                .execute(
                    "UPDATE tasks SET lease_expires_at = '2000-01-01T00:00:00.000Z' WHERE seq = ?1",
                    [dead],
                )
                .unwrap();
        });

        // The agent asking for work is handed one task; the sweep inside the
        // same call is what noticed the other one coming back.
        let out = parse(
            s.task_next(Parameters(TaskNextArgs {
                all_projects: None,
                avoid_conflicts: None,
            }))
            .await,
        );
        assert!(out["claimed"]["claimed"].is_i64(), "{out}");

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        let contents = loop {
            let contents = std::fs::read_to_string(&log).unwrap_or_default();
            if contents.contains("lease_expired") {
                break contents;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "the hook never heard the expiry; log so far:\n{contents}"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        };
        // Exactly one of the two open tasks expired; the herald names it and
        // does not announce the one the sweep never touched.
        assert!(
            contents.contains(&format!("lease_expired {dead}")),
            "{contents}"
        );
        assert!(!contents.contains(&format!(" {other}")), "{contents}");
    }

    #[tokio::test]
    async fn task_list_reports_leases_it_released() {
        let s = server();
        let seq = seed(&s, "t", "");
        s.with_db(|db| {
            db.tasks()
                .claim(seq, "codex:dead", Config::default().lease_ttl())
                .unwrap();
            db.conn()
                .execute(
                    "UPDATE tasks SET lease_expires_at = '2000-01-01T00:00:00.000Z' WHERE seq = ?1",
                    [seq],
                )
                .unwrap();
        });

        let out = parse(
            s.task_list(Parameters(TaskListArgs {
                status: None,
                all_projects: None,
            }))
            .await,
        );
        assert_eq!(out["released"], serde_json::json!([seq]));
        assert_eq!(out["tasks"][0]["status"], "open");
    }

    // ------------------------------------------------- dispatch, scope, split

    fn claim_with(seq: i64, paths: &[&str]) -> TaskClaimArgs {
        TaskClaimArgs {
            seq,
            paths: Some(paths.iter().map(|p| p.to_string()).collect()),
        }
    }

    fn next_args() -> TaskNextArgs {
        TaskNextArgs {
            all_projects: None,
            avoid_conflicts: None,
        }
    }

    #[tokio::test]
    async fn next_claims_the_best_available_task_and_reads_like_a_claim() {
        let s = server();
        seed(&s, "low priority", "");
        let important = s
            .with_db(|db| db.tasks().create(PROJECT, "important", "do it", 5, "cli"))
            .unwrap()
            .seq;

        let out = parse(s.task_next(Parameters(next_args())).await);
        assert_eq!(out["claimed"]["claimed"], important);
        assert_eq!(out["claimed"]["body"], "do it");
        assert_eq!(out["claimed"]["holder"], "claude-code:af31");
        assert!(out.get("idle").is_none());
    }

    #[tokio::test]
    async fn capability_matching_is_visible_on_named_and_next_claims() {
        let s = capable_server(&["network"]);
        let browser = s
            .with_db(|db| db.tasks().create(PROJECT, "visual QA", "", 5, "cli"))
            .unwrap()
            .seq;
        s.with_db(|db| {
            db.requirements()
                .set(browser, &["browser".into()], "cli")
                .unwrap()
        });
        let ordinary = seed(&s, "write docs", "");

        let listed = parse(
            s.task_list(Parameters(TaskListArgs {
                status: None,
                all_projects: None,
            }))
            .await,
        );
        let browser_row = listed["tasks"]
            .as_array()
            .unwrap()
            .iter()
            .find(|row| row["seq"] == browser)
            .unwrap();
        assert_eq!(browser_row["requires"][0], "browser");
        assert_eq!(browser_row["missing_capabilities"][0], "browser");

        let refused = s.task_claim(Parameters(just(browser))).await.unwrap_err();
        assert!(refused.contains("requires browser"), "{refused}");
        assert!(refused.contains("advertises network"), "{refused}");

        let handed = parse(s.task_next(Parameters(next_args())).await);
        assert_eq!(handed["claimed"]["claimed"], ordinary);
        assert_eq!(handed["incompatible"][0]["seq"], browser);
        assert_eq!(handed["incompatible"][0]["missing"][0], "browser");
    }

    #[tokio::test]
    async fn next_explains_an_empty_queue_rather_than_going_quiet() {
        let s = server();
        let out = parse(s.task_next(Parameters(next_args())).await);
        assert!(out.get("claimed").is_none());
        assert_eq!(
            out["idle"],
            "nothing is open in this project; the queue is empty"
        );
    }

    #[tokio::test]
    async fn next_names_the_dependencies_that_left_it_empty_handed() {
        let s = server();
        let gate = seed(&s, "gate", "");
        let waiting = seed(&s, "waiting", "");
        s.with_db(|db| db.deps().add(waiting, gate, "cli")).unwrap();
        // Someone else is already on the only unblocked task.
        s.with_db(|db| {
            db.tasks()
                .claim(gate, "codex:9f2c", Config::default().lease_ttl())
        })
        .unwrap();

        let out = parse(s.task_next(Parameters(next_args())).await);
        assert!(out.get("claimed").is_none());
        assert_eq!(out["blocked"], serde_json::json!([waiting]));
        assert!(
            out["idle"]
                .as_str()
                .unwrap()
                .contains("waiting on unfinished dependencies"),
            "{out}"
        );
    }

    #[tokio::test]
    async fn next_reports_the_files_that_made_it_hold_back() {
        let s = server();
        let held = seed(&s, "held", "");
        let overlapping = seed(&s, "overlapping", "");
        s.with_db(|db| {
            db.scopes().declare(
                held,
                &["src/**".into()],
                "cli",
                crate::repo::OnConflict::Report,
            )?;
            db.scopes().declare(
                overlapping,
                &["src/db.rs".into()],
                "cli",
                crate::repo::OnConflict::Report,
            )?;
            db.tasks()
                .claim(held, "codex:9f2c", Config::default().lease_ttl())
        })
        .unwrap();

        let out = parse(s.task_next(Parameters(next_args())).await);
        assert!(out.get("claimed").is_none());
        assert_eq!(out["deferred"][0]["seq"], overlapping);
        let overlap = out["deferred"][0]["overlaps"][0].as_str().unwrap();
        assert!(overlap.contains("src/db.rs overlaps src/**"), "{overlap}");
        assert!(overlap.contains("codex:9f2c"), "{overlap}");
    }

    #[tokio::test]
    async fn a_blocked_task_cannot_be_claimed_and_the_error_says_what_to_wait_for() {
        let s = server();
        let gate = seed(&s, "write the schema", "");
        let waiting = seed(&s, "write the api", "");
        s.with_db(|db| db.deps().add(waiting, gate, "cli")).unwrap();

        let err = s.task_claim(Parameters(just(waiting))).await.unwrap_err();
        assert!(err.contains("task 2 is blocked by task 1"), "{err}");
        assert!(err.contains("write the schema"), "{err}");
    }

    #[tokio::test]
    async fn claiming_with_paths_records_them_and_warns_about_overlaps() {
        let s = server();
        let held = seed(&s, "held", "");
        let mine = seed(&s, "mine", "");
        s.with_db(|db| {
            db.scopes().declare(
                held,
                &["src/**".into()],
                "cli",
                crate::repo::OnConflict::Report,
            )?;
            db.tasks()
                .claim(held, "codex:9f2c", Config::default().lease_ttl())
        })
        .unwrap();

        let out = parse(
            s.task_claim(Parameters(claim_with(mine, &["src/db.rs"])))
                .await,
        );
        assert_eq!(out["paths"], serde_json::json!(["src/db.rs"]));
        assert!(out["overlaps"][0].as_str().unwrap().contains("codex:9f2c"));
        // The reminder changes shape so the model cannot skim past a collision.
        assert!(out["reminder"]
            .as_str()
            .unwrap()
            .contains("already in some of these files"));
    }

    /// Seed a finished piece of work in `paths` that left a fact behind.
    fn earlier_work(s: &HirdMcp, title: &str, paths: &[&str], learned: &str) -> i64 {
        let seq = seed(s, title, "");
        s.with_db(|db| {
            let owned: Vec<String> = paths.iter().map(|p| p.to_string()).collect();
            db.scopes()
                .declare(seq, &owned, "cli", crate::repo::OnConflict::Report)?;
            db.memory().store(NewAssertion {
                project: PROJECT,
                content: learned,
                tags: "",
                actor: "codex:9f2c",
                task_seq: Some(seq),
            })?;
            // Done and gone: recall reaches back through finished work, which
            // is the only kind that has anything to teach.
            db.tasks()
                .claim(seq, "codex:9f2c", Config::default().lease_ttl())?;
            db.tasks().complete(seq, "codex:9f2c", "done")
        })
        .unwrap();
        seq
    }

    /// Claiming with a file scope is enough to be told what the last agent in
    /// those files learned — without anyone calling `mem_search`.
    #[tokio::test]
    async fn a_claim_arrives_with_what_earlier_work_in_those_files_learned() {
        let s = server();
        let earlier = earlier_work(
            &s,
            "Port the config loader",
            &["src/config.rs"],
            "env vars beat the config file",
        );
        let mine = seed(&s, "Audit the loader", "");

        let out = parse(
            s.task_claim(Parameters(claim_with(mine, &["src/*.rs"])))
                .await,
        );
        let recalled = &out["recalled"][0];
        assert_eq!(recalled["content"], "env vars beat the config file");
        assert_eq!(recalled["task_seq"], earlier);
        assert_eq!(recalled["actor"], "codex:9f2c");
        let why = recalled["why"].as_str().unwrap();
        assert!(why.contains(&format!("task {earlier}")), "{why}");
        assert!(why.contains("src/config.rs"), "{why}");
        // And the model is told to read it before anything else.
        assert!(out["reminder"]
            .as_str()
            .unwrap()
            .starts_with("read `recalled` first"));
    }

    #[tokio::test]
    async fn self_dispatch_carries_the_same_recall_as_a_named_claim() {
        let s = server();
        earlier_work(
            &s,
            "Rewrite the renderer",
            &["src/tui/**"],
            "the renderer redraws on every poll",
        );
        let mine = seed(&s, "Speed up the renderer", "");
        s.with_db(|db| {
            db.scopes().declare(
                mine,
                &["src/tui/view.rs".into()],
                "cli",
                crate::repo::OnConflict::Report,
            )
        })
        .unwrap();

        let out = parse(s.task_next(Parameters(next_args())).await);
        assert_eq!(out["claimed"]["claimed"], mine);
        assert_eq!(
            out["claimed"]["recalled"][0]["content"],
            "the renderer redraws on every poll"
        );
    }

    /// Recall is a courtesy, not a promise: a task nothing relates to simply
    /// leaves the field out rather than sending an empty list.
    #[tokio::test]
    async fn a_claim_with_nothing_to_recall_says_nothing() {
        let s = server();
        let seq = seed(&s, "Xyzzy", "");
        let out = parse(s.task_claim(Parameters(just(seq))).await);
        assert!(out.get("recalled").is_none(), "{out}");
        assert!(out["reminder"]
            .as_str()
            .unwrap()
            .starts_with("call task_update"));
    }

    #[tokio::test]
    async fn task_get_shows_the_same_recall_without_claiming_anything() {
        let s = server();
        earlier_work(
            &s,
            "Port the config loader",
            &["src/config.rs"],
            "env vars beat the config file",
        );
        let mine = seed(&s, "Audit the loader", "");
        s.with_db(|db| {
            db.scopes().declare(
                mine,
                &["src/config.rs".into()],
                "cli",
                crate::repo::OnConflict::Report,
            )
        })
        .unwrap();

        let out = parse(s.task_get(Parameters(SeqArgs { seq: mine })).await);
        assert_eq!(
            out["recalled"][0]["content"],
            "env vars beat the config file"
        );
        assert_eq!(out["status"], "open");
    }

    #[tokio::test]
    async fn recall_can_be_switched_off_in_the_configuration() {
        let s = HirdMcp::new(
            Db::open_in_memory().unwrap(),
            AgentId::new("claude-code", "af31"),
            PROJECT.to_string(),
            Config {
                recall_limit: 0,
                ..Config::default()
            },
        );
        earlier_work(&s, "Port the loader", &["src/config.rs"], "a fact");
        let mine = seed(&s, "Audit the loader", "");
        let out = parse(
            s.task_claim(Parameters(claim_with(mine, &["src/config.rs"])))
                .await,
        );
        assert!(out.get("recalled").is_none(), "{out}");
    }

    #[tokio::test]
    async fn scope_is_holder_only_and_answers_with_advice() {
        let s = server();
        let seq = seed(&s, "t", "");

        let err = s
            .task_scope(Parameters(TaskScopeArgs {
                seq,
                paths: vec!["src/lib.rs".into()],
            }))
            .await
            .unwrap_err();
        assert!(err.contains("must claim it first"), "{err}");

        s.task_claim(Parameters(just(seq))).await.unwrap();
        let out = parse(
            s.task_scope(Parameters(TaskScopeArgs {
                seq,
                paths: vec!["./src/lib.rs".into(), "tests/".into()],
            }))
            .await,
        );
        assert_eq!(out["paths"], serde_json::json!(["src/lib.rs", "tests/**"]));
        assert!(out.get("overlaps").is_none());
        assert!(out["advice"].as_str().unwrap().contains("go ahead"));
    }

    #[tokio::test]
    async fn splitting_files_the_pieces_and_hands_the_parent_back() {
        let s = server();
        let seq = seed(&s, "port the loader", "big job");
        s.task_claim(Parameters(just(seq))).await.unwrap();

        let out = parse(
            s.task_split(Parameters(TaskSplitArgs {
                seq,
                sequential: None,
                subtasks: vec![
                    SubtaskArgs {
                        title: "extract the parser".into(),
                        body: Some("start with the lexer".into()),
                        priority: None,
                        paths: Some(vec!["src/parse.rs".into()]),
                        requires: None,
                    },
                    SubtaskArgs {
                        title: "port the tests".into(),
                        body: None,
                        priority: Some(3),
                        paths: None,
                        requires: None,
                    },
                ],
            }))
            .await,
        );

        assert_eq!(out["seq"], seq);
        assert_eq!(out["status"], "open", "the parent goes back in the pool");
        assert_eq!(out["subtasks"][0]["title"], "extract the parser");
        assert_eq!(out["subtasks"][1]["seq"], 3);
        assert!(out["subtasks"][0].get("waiting_for").is_none());

        // The parent is now blocked by both pieces, so nobody can take it.
        let err = s.task_claim(Parameters(just(seq))).await.unwrap_err();
        assert!(err.contains("is blocked by task 2"), "{err}");

        // And the pieces are ordinary tasks any agent can be handed.
        let handed = parse(s.task_next(Parameters(next_args())).await);
        assert_eq!(handed["claimed"]["claimed"], 3, "priority 3 goes first");
    }

    #[tokio::test]
    async fn a_sequential_split_queues_the_pieces_behind_each_other() {
        let s = server();
        let seq = seed(&s, "migrate", "");
        s.task_claim(Parameters(just(seq))).await.unwrap();

        let out = parse(
            s.task_split(Parameters(TaskSplitArgs {
                seq,
                sequential: Some(true),
                subtasks: vec![
                    SubtaskArgs {
                        title: "write the migration".into(),
                        body: None,
                        priority: None,
                        paths: None,
                        requires: None,
                    },
                    SubtaskArgs {
                        title: "backfill".into(),
                        body: None,
                        priority: None,
                        paths: None,
                        requires: None,
                    },
                ],
            }))
            .await,
        );
        assert_eq!(out["subtasks"][1]["waiting_for"], serde_json::json!([2]));

        // Only the first piece is workable.
        let handed = parse(s.task_next(Parameters(next_args())).await);
        assert_eq!(handed["claimed"]["claimed"], 2);
        let nothing = parse(s.task_next(Parameters(next_args())).await);
        assert!(nothing.get("claimed").is_none());
        assert_eq!(nothing["blocked"], serde_json::json!([1, 3]));
    }

    #[tokio::test]
    async fn splitting_is_holder_only_and_needs_at_least_one_piece() {
        let s = server();
        let seq = seed(&s, "t", "");
        let err = s
            .task_split(Parameters(TaskSplitArgs {
                seq,
                sequential: None,
                subtasks: vec![SubtaskArgs {
                    title: "a piece".into(),
                    body: None,
                    priority: None,
                    paths: None,
                    requires: None,
                }],
            }))
            .await
            .unwrap_err();
        assert!(err.contains("must claim it first"), "{err}");

        s.task_claim(Parameters(just(seq))).await.unwrap();
        let err = s
            .task_split(Parameters(TaskSplitArgs {
                seq,
                sequential: None,
                subtasks: vec![],
            }))
            .await
            .unwrap_err();
        assert!(err.contains("at least one subtask"), "{err}");
    }

    #[tokio::test]
    async fn releasing_puts_a_task_back_without_marking_it_failed() {
        let s = server();
        let seq = seed(&s, "t", "");
        s.task_claim(Parameters(just(seq))).await.unwrap();

        let out = parse(
            s.task_release(Parameters(TaskReleaseArgs {
                seq,
                reason: "needs credentials I do not have".into(),
                question: None,
            }))
            .await,
        );
        assert_eq!(out["status"], "open");
        assert_eq!(out["result"], "needs credentials I do not have");

        // Straight back on the ready list, no human intervention needed.
        let handed = parse(s.task_next(Parameters(next_args())).await);
        assert_eq!(handed["claimed"]["claimed"], seq);
    }

    #[tokio::test]
    async fn a_question_parks_work_until_its_answer_is_handed_to_the_next_claim() {
        let s = server();
        let seq = seed(&s, "choose compatibility", "implement after the decision");
        s.task_claim(Parameters(just(seq))).await.unwrap();

        let released = parse(
            s.task_release(Parameters(TaskReleaseArgs {
                seq,
                reason: "the implementation point is isolated".into(),
                question: Some("Preserve the legacy config format?".into()),
            }))
            .await,
        );
        assert_eq!(
            released["awaiting_answer"],
            "Preserve the legacy config format?"
        );

        let refused = s.task_claim(Parameters(just(seq))).await.unwrap_err();
        assert!(refused.contains("awaiting an answer"), "{refused}");
        let idle = parse(s.task_next(Parameters(next_args())).await);
        assert_eq!(idle["awaiting_answer"][0]["seq"], seq);
        assert!(idle["idle"].as_str().unwrap().contains("human answer"));

        let detail = parse(s.task_get(Parameters(SeqArgs { seq })).await);
        assert_eq!(
            detail["questions"][0]["question"],
            "Preserve the legacy config format?"
        );
        assert!(detail["questions"][0].get("answer").is_none());

        s.with_db(|db| db.questions().answer(seq, "cli", "No; migrate it."))
            .unwrap();
        let claimed = parse(s.task_claim(Parameters(just(seq))).await);
        assert_eq!(claimed["questions"][0]["answer"], "No; migrate it.");
        assert!(claimed["reminder"]
            .as_str()
            .unwrap()
            .contains("`questions`"));
    }

    /// During a recess the queue is standing, not idle — the reply says
    /// which, names no other work, and a claim by number is refused in the
    /// human's own words. Lifting it puts everything back exactly as it was.
    #[tokio::test]
    async fn a_recess_answers_task_next_with_standing_by_not_idle() {
        let s = server();
        let seq = seed(&s, "ready work", "");
        s.with_db(|db| db.recesses().call(PROJECT, "rebasing main", "cli"))
            .unwrap();

        let out = parse(s.task_next(Parameters(next_args())).await);
        assert!(out.get("claimed").is_none());
        let recess = out["recess"].as_str().unwrap();
        assert!(recess.contains("rebasing main"), "{recess}");
        let idle = out["idle"].as_str().unwrap();
        assert!(idle.starts_with("in recess, not idle"), "{idle}");
        assert!(idle.contains("Stand by"), "{idle}");
        assert!(
            out.get("blocked").is_none() && out.get("deferred").is_none(),
            "a recess enumerates nothing: {out}"
        );

        let refused = s.task_claim(Parameters(just(seq))).await.unwrap_err();
        assert!(refused.contains("in recess"), "{refused}");
        assert!(refused.contains("rebasing main"), "{refused}");

        s.with_db(|db| db.recesses().lift(PROJECT)).unwrap();
        let handed = parse(s.task_next(Parameters(next_args())).await);
        assert_eq!(handed["claimed"]["claimed"], seq);
    }

    /// A parked question is not the whole story when the task is also waiting
    /// on work. Told only about the question, a human answers it and watches
    /// nothing move — so the task is named in both buckets, and the idle
    /// sentence stops claiming the answer is all that stands in the way.
    #[tokio::test]
    async fn a_task_both_blocked_and_parked_is_reported_as_both() {
        let s = server();
        let groundwork = seed(&s, "land the migration", "");
        let seq = seed(&s, "choose compatibility", "");

        s.task_claim(Parameters(just(seq))).await.unwrap();
        s.task_release(Parameters(TaskReleaseArgs {
            seq,
            reason: "the implementation point is isolated".into(),
            question: Some("Preserve the legacy config format?".into()),
        }))
        .await
        .unwrap();
        // The graph learns what this work waits on only after the holder let
        // go of it — which is the ordinary way both gates end up on one task.
        s.with_db(|db| db.deps().add(seq, groundwork, "cli"))
            .unwrap();
        // And somebody is already on the groundwork, so it is not what the
        // queue would hand out instead.
        s.with_db(|db| {
            db.tasks().claim(
                groundwork,
                "codex:other",
                std::time::Duration::from_secs(900),
            )
        })
        .unwrap();

        let idle = parse(s.task_next(Parameters(next_args())).await);
        assert_eq!(idle["awaiting_answer"][0]["seq"], seq);
        let reason = idle["idle"].as_str().unwrap();
        assert!(reason.contains("awaiting a human answer"), "{reason}");
        assert!(
            !reason.contains("No agent can make progress"),
            "the answer is not the only thing in the way: {reason}"
        );
    }

    #[tokio::test]
    async fn task_get_shows_dependencies_scope_and_overlaps() {
        let s = server();
        let gate = seed(&s, "gate", "");
        let held = seed(&s, "held", "");
        let mine = seed(&s, "mine", "");
        s.with_db(|db| {
            db.deps().add(mine, gate, "cli")?;
            db.scopes().declare(
                held,
                &["src/**".into()],
                "cli",
                crate::repo::OnConflict::Report,
            )?;
            db.scopes().declare(
                mine,
                &["src/db.rs".into()],
                "cli",
                crate::repo::OnConflict::Report,
            )?;
            db.tasks()
                .claim(held, "codex:9f2c", Config::default().lease_ttl())
        })
        .unwrap();

        let out = parse(s.task_get(Parameters(SeqArgs { seq: mine })).await);
        assert_eq!(out["waiting_for"][0]["seq"], gate);
        assert_eq!(out["waiting_for"][0]["status"], "open");
        assert_eq!(out["paths"], serde_json::json!(["src/db.rs"]));
        assert!(out["overlaps"][0].as_str().unwrap().contains("codex:9f2c"));

        let gate_view = parse(s.task_get(Parameters(SeqArgs { seq: gate })).await);
        assert_eq!(gate_view["blocks"], serde_json::json!([mine]));
    }

    #[tokio::test]
    async fn task_list_marks_the_tasks_nobody_can_start_yet() {
        let s = server();
        let gate = seed(&s, "gate", "");
        let waiting = seed(&s, "waiting", "");
        s.with_db(|db| db.deps().add(waiting, gate, "cli")).unwrap();

        let out = parse(
            s.task_list(Parameters(TaskListArgs {
                status: None,
                all_projects: None,
            }))
            .await,
        );
        let rows = out["tasks"].as_array().unwrap();
        let blocked = rows.iter().find(|r| r["seq"] == waiting).unwrap();
        assert_eq!(blocked["blocked_by"], serde_json::json!([gate]));
        let ready = rows.iter().find(|r| r["seq"] == gate).unwrap();
        assert!(ready.get("blocked_by").is_none());
    }

    #[test]
    fn the_instructions_state_the_queue_rules() {
        let text = server().instructions();
        for expected in [
            "seq",
            "task_claim",
            "BEFORE",
            "task_update",
            "task_complete",
            "mem_store",
            "mem_search",
            "all_projects",
            PROJECT,
        ] {
            assert!(text.contains(expected), "instructions omit {expected:?}");
        }
        // The heartbeat interval must be derived from the configured TTL.
        assert!(text.contains("15 minutes"), "{text}");
        assert!(text.contains("every 7 minutes"), "{text}");
    }

    #[test]
    fn server_info_advertises_tools_and_carries_the_instructions() {
        let s = server();
        let info = s.get_info();
        assert!(info.capabilities.tools.is_some());
        assert_eq!(info.server_info.name, "hird");
        assert_eq!(
            info.instructions.as_deref(),
            Some(s.instructions().as_str())
        );
    }

    /// The tool surface is a promise to every harness that has registered
    /// `hird`, so it changes deliberately or not at all.
    #[test]
    fn exactly_the_designed_tools_are_exposed() {
        let mut names: Vec<String> = HirdMcp::tool_router()
            .list_all()
            .into_iter()
            .map(|t| t.name.to_string())
            .collect();
        names.sort();
        assert_eq!(
            names,
            vec![
                "mem_search",
                "mem_store",
                "task_claim",
                "task_complete",
                "task_fail",
                "task_get",
                "task_list",
                "task_next",
                "task_release",
                "task_scope",
                "task_split",
                "task_update",
            ]
        );
    }

    #[test]
    fn every_tool_has_a_description_and_an_input_schema() {
        for tool in HirdMcp::tool_router().list_all() {
            let name = &tool.name;
            assert!(
                tool.description.as_ref().is_some_and(|d| d.len() > 20),
                "{name} needs a real description"
            );
            assert!(
                tool.input_schema.contains_key("properties")
                    || tool.input_schema.contains_key("type"),
                "{name} has no input schema"
            );
        }
    }
}