codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
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
//! Narrow model-facing agent coordination tools.
//!
//! Keeps `agent` as the creation surface. These five tools wrap existing
//! SubAgentManager / mailbox / checkpoint machinery without restoring the
//! retired lifecycle theater (`agent_open` / `agent_eval` / …).

use std::collections::BTreeSet;
use std::sync::Arc;
use std::time::{Duration, Instant};

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::{
    COMPLETED_AGENT_RETENTION, ParentMailReceipt, SharedSubAgentManager, SubAgentRuntime,
    SubAgentStatus, parse_agent_ref, subagent_session_projection, subagent_status_name,
    wait_for_subagents_from_input,
};
use crate::tools::registry::ToolRegistryBuilder;
use crate::tools::spec::{
    ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
};

/// Bounds for `agents/wait`. Short on purpose: a blocked wait makes the
/// session deaf to typed input, and settled children already report back as
/// `<codewhale:subagent.done>` sentinels that start a fresh turn (#4097).
const COORD_WAIT_DEFAULT_TIMEOUT_SECS: u64 = 30;
const COORD_WAIT_MIN_TIMEOUT_SECS: u64 = 1;
const COORD_WAIT_MAX_TIMEOUT_SECS: u64 = 120;
const COORD_WAIT_CHECK_INTERVAL: Duration = Duration::from_millis(250);
const RECENT_PROGRESS_LIMIT: usize = 8;
pub(super) const COORDINATION_RECORD_LIMIT: usize = 128;
const COORDINATION_INSPECT_LIMIT: usize = 24;
pub(super) const COORDINATION_PROJECTION_DECISION_LIMIT: usize = 8;
pub(super) const COORDINATION_PROJECTION_BYTE_LIMIT: usize = 4096;

// ── agents/list ──────────────────────────────────────────────────────────

pub struct AgentsListTool {
    manager: SharedSubAgentManager,
}

impl AgentsListTool {
    #[must_use]
    pub fn new(manager: SharedSubAgentManager) -> Self {
        Self { manager }
    }
}

#[async_trait]
impl ToolSpec for AgentsListTool {
    fn name(&self) -> &'static str {
        "agents/list"
    }

    fn description(&self) -> &'static str {
        "List child agents: ids, parent hierarchy, state, bounded recent progress, and token budget. Read-only coordination view — does not spawn or wake workers."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "include_archived": {
                    "type": "boolean",
                    "description": "Include prior-session / archived agents. Default false."
                },
                "agent_id": {
                    "type": "string",
                    "description": "Optional single agent id or session name to inspect."
                }
            },
            "required": []
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::ReadOnly]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Auto
    }

    fn is_read_only_for(&self, _input: &Value) -> bool {
        true
    }

    fn supports_parallel_for(&self, _input: &Value) -> bool {
        true
    }

    async fn execute(&self, input: Value, _context: &ToolContext) -> Result<ToolResult, ToolError> {
        let include_archived = input
            .get("include_archived")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        let agent_ref = parse_agent_ref(&input)?;

        let mut manager = self.manager.write().await;
        manager.cleanup(COMPLETED_AGENT_RETENTION);
        let summaries = if let Some(agent_ref) = agent_ref {
            let summary = manager
                .coordination_summary_for(&agent_ref, RECENT_PROGRESS_LIMIT)
                .map_err(|err| ToolError::invalid_input(err.to_string()))?;
            vec![summary]
        } else {
            manager.list_coordination_summaries(include_archived, RECENT_PROGRESS_LIMIT)
        };
        drop(manager);

        let payload = json!({
            "action": "list",
            "count": summaries.len(),
            "agents": summaries,
        });
        let mut tool_result = ToolResult::json(&payload)
            .map_err(|err| ToolError::execution_failed(err.to_string()))?;
        tool_result.metadata = Some(json!({
            "action": "list",
            "count": summaries.len(),
        }));
        Ok(tool_result)
    }
}

// ── agents/message ───────────────────────────────────────────────────────

pub struct AgentsMessageTool {
    manager: SharedSubAgentManager,
    caller_agent_id: Option<String>,
}

impl AgentsMessageTool {
    #[must_use]
    pub fn new(manager: SharedSubAgentManager) -> Self {
        Self {
            manager,
            caller_agent_id: None,
        }
    }

    #[must_use]
    pub(crate) fn with_optional_caller(mut self, caller_agent_id: Option<String>) -> Self {
        self.caller_agent_id = caller_agent_id;
        self
    }
}

#[async_trait]
impl ToolSpec for AgentsMessageTool {
    fn name(&self) -> &'static str {
        "agents/message"
    }

    fn description(&self) -> &'static str {
        "Queue a parent message onto a running child without waking it. The message stays queued until a later agents/followup delivers it through the child's live input channel. Use agents/followup directly when you want immediate delivery."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "agent_id": {
                    "type": "string",
                    "description": "Target child agent id or session name."
                },
                "message": {
                    "type": "string",
                    "description": "Message text to queue."
                }
            },
            "required": ["agent_id", "message"]
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::RequiresApproval]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Required
    }

    async fn execute(&self, input: Value, _context: &ToolContext) -> Result<ToolResult, ToolError> {
        let agent_ref =
            parse_agent_ref(&input)?.ok_or_else(|| ToolError::missing_field("agent_id"))?;
        let message = input
            .get("message")
            .or_else(|| input.get("text"))
            .and_then(Value::as_str)
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| ToolError::missing_field("message"))?
            .to_string();

        let receipt = {
            let mut manager = self.manager.write().await;
            manager
                .ensure_caller_controls_descendant(
                    &agent_ref,
                    self.caller_agent_id.as_deref(),
                    "agents/message",
                )
                .map_err(|err| ToolError::invalid_input(err.to_string()))?;
            manager
                .queue_running_parent_message(&agent_ref, message)
                .map_err(|err| ToolError::invalid_input(err.to_string()))?
        };

        let payload = json!({
            "action": "message",
            "agent_id": receipt.agent_id,
            "queued": true,
            "woke": false,
            "queue_depth": receipt.queue_depth,
            "status": receipt.status,
            "note": "Message queued without waking the child.",
        });
        let mut tool_result = ToolResult::json(&payload)
            .map_err(|err| ToolError::execution_failed(err.to_string()))?;
        tool_result.metadata = Some(json!({
            "action": "message",
            "agent_id": receipt.agent_id,
            "woke": false,
            "queue_depth": receipt.queue_depth,
        }));
        Ok(tool_result)
    }
}

// ── agents/followup ──────────────────────────────────────────────────────

pub struct AgentsFollowupTool {
    manager: SharedSubAgentManager,
    caller_agent_id: Option<String>,
    /// Runtime for checkpoint resume. `None` (legacy/test construction)
    /// keeps the queue-only followup behavior.
    runtime: Option<SubAgentRuntime>,
}

impl AgentsFollowupTool {
    #[must_use]
    pub fn new(manager: SharedSubAgentManager) -> Self {
        Self {
            manager,
            caller_agent_id: None,
            runtime: None,
        }
    }

    #[must_use]
    pub fn with_runtime(mut self, runtime: SubAgentRuntime) -> Self {
        self.runtime = Some(runtime);
        self
    }

    #[must_use]
    pub(crate) fn with_optional_caller(mut self, caller_agent_id: Option<String>) -> Self {
        self.caller_agent_id = caller_agent_id;
        self
    }
}

#[async_trait]
impl ToolSpec for AgentsFollowupTool {
    fn name(&self) -> &'static str {
        "agents/followup"
    }

    fn description(&self) -> &'static str {
        "Queue a message and attempt to resume an idle or interrupted child. Running children receive the message on their next step; interrupted_continuable children are resumed from their checkpoint into a fresh agent loop (new agent id, original prompt plus prior conversation tail) when a runtime is attached, and otherwise keep queue-only semantics with the continuation_handle returned."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "agent_id": {
                    "type": "string",
                    "description": "Target child agent id or session name."
                },
                "message": {
                    "type": "string",
                    "description": "Follow-up message text."
                }
            },
            "required": ["agent_id", "message"]
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::RequiresApproval]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Required
    }

    async fn execute(&self, input: Value, _context: &ToolContext) -> Result<ToolResult, ToolError> {
        let agent_ref =
            parse_agent_ref(&input)?.ok_or_else(|| ToolError::missing_field("agent_id"))?;
        let message = input
            .get("message")
            .or_else(|| input.get("text"))
            .and_then(Value::as_str)
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| ToolError::missing_field("message"))?
            .to_string();

        // Enforce the caller hierarchy, then decide between checkpoint resume
        // (interrupted_continuable with a runtime attached) and queue-only
        // followup while holding only the read lock. The resume path takes
        // the write lock itself via the manager method.
        let should_resume = {
            let manager = self.manager.read().await;
            manager
                .ensure_caller_controls_descendant(
                    &agent_ref,
                    self.caller_agent_id.as_deref(),
                    "agents/followup",
                )
                .map_err(|err| ToolError::invalid_input(err.to_string()))?;
            manager
                .get_result_by_ref(&agent_ref)
                .ok()
                .is_some_and(|snapshot| {
                    matches!(snapshot.status, SubAgentStatus::Interrupted(_))
                        && snapshot
                            .checkpoint
                            .as_ref()
                            .is_some_and(|cp| cp.continuable && !cp.messages.is_empty())
                })
        };

        let receipt = if should_resume {
            match self.runtime.clone() {
                Some(runtime) => {
                    let mut manager = self.manager.write().await;
                    let snapshot = manager
                        .resume_from_checkpoint(
                            Arc::clone(&self.manager),
                            runtime,
                            &agent_ref,
                            &message,
                        )
                        .map_err(|err| ToolError::execution_failed(err.to_string()))?;
                    ParentMailReceipt {
                        agent_id: snapshot.agent_id.clone(),
                        status: subagent_status_name(&snapshot.status).to_string(),
                        queue_depth: 0,
                        woke: true,
                        continued_from_checkpoint: true,
                        continuation_handle: None,
                        note: format!(
                            "resumed from checkpoint as new agent {} ({}); prior terminal record {} stays intact",
                            snapshot.agent_id, snapshot.model, agent_ref
                        ),
                    }
                }
                None => {
                    let mut manager = self.manager.write().await;
                    manager
                        .followup_child(&agent_ref, message)
                        .map_err(|err| ToolError::invalid_input(err.to_string()))?
                }
            }
        } else {
            let mut manager = self.manager.write().await;
            manager
                .followup_child(&agent_ref, message)
                .map_err(|err| ToolError::invalid_input(err.to_string()))?
        };

        let payload = json!({
            "action": "followup",
            "agent_id": receipt.agent_id,
            "queued": true,
            "woke": receipt.woke,
            "queue_depth": receipt.queue_depth,
            "status": receipt.status,
            "continued_from_checkpoint": receipt.continued_from_checkpoint,
            "continuation_handle": receipt.continuation_handle,
            "note": receipt.note,
            "child_route": self.manager.read().await.get_worker_record(&receipt.agent_id)
                .and_then(|record| record.spec.child_route),
        });
        let mut tool_result = ToolResult::json(&payload)
            .map_err(|err| ToolError::execution_failed(err.to_string()))?;
        tool_result.metadata = Some(json!({
            "action": "followup",
            "agent_id": receipt.agent_id,
            "woke": receipt.woke,
            "continued_from_checkpoint": receipt.continued_from_checkpoint,
            "continuation_handle": receipt.continuation_handle,
            "child_route": self.manager.read().await.get_worker_record(&receipt.agent_id)
                .and_then(|record| record.spec.child_route),
        }));
        Ok(tool_result)
    }
}

// ── agents/interrupt ─────────────────────────────────────────────────────

pub struct AgentsInterruptTool {
    manager: SharedSubAgentManager,
    /// Optional caller identity for fail-closed self-interrupt checks.
    caller_agent_id: Option<String>,
}

impl AgentsInterruptTool {
    #[must_use]
    pub fn new(manager: SharedSubAgentManager) -> Self {
        Self {
            manager,
            caller_agent_id: None,
        }
    }

    #[must_use]
    #[allow(dead_code)] // arms self-interrupt fail-closed when child registries thread caller (P1.2)
    pub fn with_caller(mut self, caller_agent_id: impl Into<String>) -> Self {
        self.caller_agent_id = Some(caller_agent_id.into());
        self
    }

    #[must_use]
    pub(crate) fn with_optional_caller(mut self, caller_agent_id: Option<String>) -> Self {
        self.caller_agent_id = caller_agent_id;
        self
    }
}

#[async_trait]
impl ToolSpec for AgentsInterruptTool {
    fn name(&self) -> &'static str {
        "agents/interrupt"
    }

    fn description(&self) -> &'static str {
        "Interrupt a running child agent, preserve its checkpoint, and return the prior state. Fails closed on root or self targets. Prefer this over cancel when you may resume later."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "agent_id": {
                    "type": "string",
                    "description": "Child agent id or session name to interrupt."
                },
                "reason": {
                    "type": "string",
                    "description": "Optional interrupt reason recorded on the checkpoint."
                }
            },
            "required": ["agent_id"]
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::RequiresApproval]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Required
    }

    async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
        let agent_ref =
            parse_agent_ref(&input)?.ok_or_else(|| ToolError::missing_field("agent_id"))?;
        let reason = input
            .get("reason")
            .and_then(Value::as_str)
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .unwrap_or("interrupted by parent via agents/interrupt")
            .to_string();

        let (prior, snapshot) = {
            let mut manager = self.manager.write().await;
            manager
                .interrupt_child(&agent_ref, self.caller_agent_id.as_deref(), reason)
                .map_err(|err| ToolError::invalid_input(err.to_string()))?
        };

        let worker_record = {
            let manager = self.manager.read().await;
            manager.get_worker_record(&snapshot.agent_id)
        };
        let projection = subagent_session_projection(snapshot, false, context, worker_record).await;
        let payload = json!({
            "action": "interrupt",
            "agent_id": projection.agent_id,
            "prior_status": subagent_status_name(&prior.status),
            "prior_steps_taken": prior.steps_taken,
            "status": projection.status,
            "checkpoint_preserved": projection.checkpoint.is_some(),
            "continuable": projection.continuable,
            "projection": projection,
            "child_route": projection.child_route,
        });
        let mut tool_result = ToolResult::json(&payload)
            .map_err(|err| ToolError::execution_failed(err.to_string()))?;
        tool_result.metadata = Some(json!({
            "action": "interrupt",
            "agent_id": payload["agent_id"],
            "checkpoint_preserved": payload["checkpoint_preserved"],
            "child_route": payload["child_route"],
        }));
        Ok(tool_result)
    }
}

// ── agents/wait ──────────────────────────────────────────────────────────

pub struct AgentsWaitTool {
    manager: SharedSubAgentManager,
}

impl AgentsWaitTool {
    #[must_use]
    pub fn new(manager: SharedSubAgentManager) -> Self {
        Self { manager }
    }
}

#[async_trait]
impl ToolSpec for AgentsWaitTool {
    fn name(&self) -> &'static str {
        "agents/wait"
    }

    fn description(&self) -> &'static str {
        "Block briefly until watched children settle or the timeout elapses. Keep waits short: on timeout, end your turn — settled children wake you automatically as completion sentinels; polling agents/list in a loop is not the right shape either. until=all is the fan-out join: it returns only when every child running at call time has left running, with each child's outcome. until=completion (default) returns as soon as any one child settles. until=activity also returns on progress."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "agent_id": {
                    "type": "string",
                    "description": "Optional specific child. When omitted, watches every child running at call time."
                },
                "timeout_secs": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 120,
                    "description": "Maximum seconds to block. Default 30. Keep it short — on timeout, end your turn; settled children report back as completion sentinels."
                },
                "until": {
                    "type": "string",
                    "enum": ["completion", "all", "activity"],
                    "description": "completion (default): return when any one child leaves running. all: return only when every watched child has left running — use this after a fan-out so one wait covers the whole batch. activity: also return when recent progress changes. Children spawned after the call are not watched; no children means an immediate return."
                }
            },
            "required": []
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::ReadOnly]
    }

    fn approval_requirement(&self) -> ApprovalRequirement {
        ApprovalRequirement::Auto
    }

    fn is_read_only_for(&self, _input: &Value) -> bool {
        true
    }

    async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
        dispatch_wait(&input, Arc::clone(&self.manager), context).await
    }
}

/// Single entry point for every blocking wait, shared by `agents/wait` and
/// `agent(action="wait")` so the two surfaces cannot drift.
///
/// `until` selects the join shape:
/// - `completion` (default) — return as soon as any one watched child settles.
/// - `all` — return only when every watched child has settled (the fan-out
///   join the parent should use after dispatching a batch).
/// - `activity` — also return when a running child makes visible progress.
pub(super) async fn dispatch_wait(
    input: &Value,
    manager: SharedSubAgentManager,
    context: &ToolContext,
) -> Result<ToolResult, ToolError> {
    let until = input
        .get("until")
        .and_then(Value::as_str)
        .unwrap_or("completion")
        .trim()
        .to_ascii_lowercase();

    match until.as_str() {
        "" | "completion" => {
            let mut wait_input = input.clone();
            if wait_input.get("action").is_none() {
                wait_input["action"] = json!("wait");
            }
            wait_for_subagents_from_input(&wait_input, manager, context).await
        }
        "all" => wait_for_all_children(input, manager, context).await,
        "activity" => wait_for_activity(input, manager, context).await,
        other => Err(ToolError::invalid_input(format!(
            "Invalid until '{other}'. Use completion, all, or activity."
        ))),
    }
}

/// `until=all`: block until every child that was running when the call was
/// made has left `Running`.
///
/// The watch set is fixed at call time. A child spawned while this wait is
/// blocked is deliberately **not** joined — the parent asked to join the batch
/// it had just dispatched, and silently extending the set would make the call
/// unbounded in a way the caller never asked for. Callers that fan out again
/// simply issue another wait.
///
/// Cancel-safe (no lock is held across an await), honours `timeout_secs`, and
/// returns immediately with `all_settled: true` when nothing is running.
async fn wait_for_all_children(
    input: &Value,
    manager: SharedSubAgentManager,
    context: &ToolContext,
) -> Result<ToolResult, ToolError> {
    let timeout_secs = input
        .get("timeout_secs")
        .or_else(|| input.get("timeout"))
        .and_then(Value::as_u64)
        .unwrap_or(COORD_WAIT_DEFAULT_TIMEOUT_SECS)
        .clamp(COORD_WAIT_MIN_TIMEOUT_SECS, COORD_WAIT_MAX_TIMEOUT_SECS);
    let timeout = Duration::from_secs(timeout_secs);
    let agent_ref = parse_agent_ref(input)?;

    // Resolve the watch set up front so a bad reference fails immediately
    // rather than blocking for the whole timeout.
    let watched: Vec<String> = {
        let manager = manager.read().await;
        if let Some(agent_ref) = &agent_ref {
            let snapshot = manager
                .get_result_by_ref(agent_ref)
                .map_err(|err| ToolError::invalid_input(err.to_string()))?;
            if snapshot.status != SubAgentStatus::Running {
                // Already settled: hand back its outcome rather than an empty
                // "nothing to join" that hides what the caller asked about.
                let settled = json!({
                    "agent_id": snapshot.agent_id,
                    "name": snapshot.name,
                    "status": subagent_status_name(&snapshot.status),
                    "steps_taken": snapshot.steps_taken,
                });
                drop(manager);
                return wait_all_payload(&[settled], &[], 0, false);
            }
            vec![snapshot.agent_id]
        } else {
            manager
                .list_filtered(false)
                .into_iter()
                .filter(|snapshot| snapshot.status == SubAgentStatus::Running)
                .map(|snapshot| snapshot.agent_id)
                .collect()
        }
    };

    // Zero children is an immediate return, never a hang.
    if watched.is_empty() {
        return wait_all_payload(&[], &[], 0, false);
    }

    let started = Instant::now();
    let cancelled = async {
        match &context.cancel_token {
            Some(token) => token.cancelled().await,
            None => std::future::pending().await,
        }
    };
    tokio::pin!(cancelled);

    loop {
        let (settled, still_running) = {
            let manager = manager.read().await;
            let mut settled = Vec::new();
            let mut still_running = Vec::new();
            for agent_id in &watched {
                match manager.get_result_by_ref(agent_id) {
                    Ok(snapshot) if snapshot.status == SubAgentStatus::Running => {
                        still_running.push(json!({
                            "agent_id": snapshot.agent_id,
                            "name": snapshot.name,
                            "status": "running",
                        }));
                    }
                    Ok(snapshot) => settled.push(json!({
                        "agent_id": snapshot.agent_id,
                        "name": snapshot.name,
                        "status": subagent_status_name(&snapshot.status),
                        "steps_taken": snapshot.steps_taken,
                    })),
                    // A watched child that vanished from the ledger (retention
                    // cleanup) is no longer running; report it rather than
                    // blocking on a record that will never settle.
                    Err(_) => settled.push(json!({
                        "agent_id": agent_id,
                        "status": "gone",
                    })),
                }
            }
            (settled, still_running)
        };

        if still_running.is_empty() {
            return wait_all_payload(&settled, &[], started.elapsed().as_millis(), false);
        }
        if started.elapsed() >= timeout {
            return wait_all_payload(
                &settled,
                &still_running,
                started.elapsed().as_millis(),
                true,
            );
        }

        tokio::select! {
            biased;
            () = &mut cancelled => {
                return Err(ToolError::cancelled(
                    "Wait interrupted by user cancellation before every child settled.".to_string(),
                ));
            }
            () = tokio::time::sleep(COORD_WAIT_CHECK_INTERVAL) => {}
        }
    }
}

/// `until=all` result: every watched child with its own outcome, so the parent
/// can synthesize from one return instead of re-inspecting each child.
fn wait_all_payload(
    settled: &[Value],
    still_running: &[Value],
    waited_ms: u128,
    timed_out: bool,
) -> Result<ToolResult, ToolError> {
    let note = if timed_out {
        "Timed out with children still running. Do not poll — wait again (until=all), or end your turn; results arrive as <codewhale:subagent.done> sentinels."
    } else if settled.is_empty() {
        "No sub-agents were running; nothing to join."
    } else {
        "Every watched child has settled. Full results arrive as <codewhale:subagent.done> sentinels — synthesize from those."
    };
    let payload = json!({
        "action": "wait",
        "until": "all",
        "all_settled": still_running.is_empty(),
        "settled": settled,
        "still_running": still_running,
        "waited_ms": u64::try_from(waited_ms).unwrap_or(u64::MAX),
        "timed_out": timed_out,
        "note": note,
    });
    let mut tool_result =
        ToolResult::json(&payload).map_err(|err| ToolError::execution_failed(err.to_string()))?;
    tool_result.metadata = Some(json!({
        "action": "wait",
        "until": "all",
        "all_settled": still_running.is_empty(),
        "settled": settled.len(),
        "running": still_running.len(),
        "timed_out": timed_out,
    }));
    Ok(tool_result)
}

async fn wait_for_activity(
    input: &Value,
    manager: SharedSubAgentManager,
    context: &ToolContext,
) -> Result<ToolResult, ToolError> {
    let timeout_secs = input
        .get("timeout_secs")
        .or_else(|| input.get("timeout"))
        .and_then(Value::as_u64)
        .unwrap_or(COORD_WAIT_DEFAULT_TIMEOUT_SECS)
        .clamp(COORD_WAIT_MIN_TIMEOUT_SECS, COORD_WAIT_MAX_TIMEOUT_SECS);
    let timeout = Duration::from_secs(timeout_secs);
    let agent_ref = parse_agent_ref(input)?;

    let (watched, baseline): (Vec<String>, Vec<(String, u64)>) = {
        let manager = manager.read().await;
        if let Some(agent_ref) = &agent_ref {
            let snap = manager
                .get_result_by_ref(agent_ref)
                .map_err(|err| ToolError::invalid_input(err.to_string()))?;
            let fp = manager.activity_fingerprint(&snap.agent_id).unwrap_or(0);
            if snap.status != SubAgentStatus::Running {
                let payload = json!({
                    "action": "wait",
                    "until": "activity",
                    "reason": "already_settled",
                    "timed_out": false,
                    "agent_id": snap.agent_id,
                    "status": subagent_status_name(&snap.status),
                });
                let mut tool_result = ToolResult::json(&payload)
                    .map_err(|err| ToolError::execution_failed(err.to_string()))?;
                tool_result.metadata = Some(json!({ "action": "wait", "timed_out": false }));
                return Ok(tool_result);
            }
            (vec![snap.agent_id.clone()], vec![(snap.agent_id, fp)])
        } else {
            let running = manager
                .list_filtered(false)
                .into_iter()
                .filter(|s| s.status == SubAgentStatus::Running)
                .map(|s| s.agent_id)
                .collect::<Vec<_>>();
            let baseline = running
                .iter()
                .map(|id| {
                    let fp = manager.activity_fingerprint(id).unwrap_or(0);
                    (id.clone(), fp)
                })
                .collect();
            (running, baseline)
        }
    };

    if watched.is_empty() {
        let payload = json!({
            "action": "wait",
            "until": "activity",
            "note": "No running sub-agents; nothing to wait for.",
            "timed_out": false,
        });
        let mut tool_result = ToolResult::json(&payload)
            .map_err(|err| ToolError::execution_failed(err.to_string()))?;
        tool_result.metadata = Some(json!({ "action": "wait", "timed_out": false }));
        return Ok(tool_result);
    }

    let started = Instant::now();
    let cancelled = async {
        match &context.cancel_token {
            Some(token) => token.cancelled().await,
            None => std::future::pending().await,
        }
    };
    tokio::pin!(cancelled);

    loop {
        let outcome = {
            let manager = manager.read().await;
            let mut settled = Vec::new();
            let mut activity = Vec::new();
            for (id, base_fp) in &baseline {
                if let Ok(snap) = manager.get_result_by_ref(id) {
                    if snap.status != SubAgentStatus::Running {
                        settled.push(snap);
                        continue;
                    }
                    let fp = manager.activity_fingerprint(id).unwrap_or(0);
                    if fp != *base_fp {
                        activity.push(json!({
                            "agent_id": id,
                            "status": "running",
                            "activity_fingerprint": fp,
                        }));
                    }
                }
            }
            (settled, activity, manager.running_count())
        };

        if !outcome.0.is_empty() || !outcome.1.is_empty() {
            let payload = json!({
                "action": "wait",
                "until": "activity",
                "settled": outcome.0.iter().map(|s| json!({
                    "agent_id": s.agent_id,
                    "status": subagent_status_name(&s.status),
                })).collect::<Vec<_>>(),
                "activity": outcome.1,
                "running": outcome.2,
                "elapsed_ms": started.elapsed().as_millis(),
                "timed_out": false,
            });
            let mut tool_result = ToolResult::json(&payload)
                .map_err(|err| ToolError::execution_failed(err.to_string()))?;
            tool_result.metadata = Some(json!({
                "action": "wait",
                "timed_out": false,
                "settled": outcome.0.len(),
                "activity": outcome.1.len(),
            }));
            return Ok(tool_result);
        }

        if started.elapsed() >= timeout {
            let payload = json!({
                "action": "wait",
                "until": "activity",
                "settled": [],
                "activity": [],
                "running": outcome.2,
                "elapsed_ms": started.elapsed().as_millis(),
                "timed_out": true,
                "note": "Timed out before child activity or completion.",
            });
            let mut tool_result = ToolResult::json(&payload)
                .map_err(|err| ToolError::execution_failed(err.to_string()))?;
            tool_result.metadata = Some(json!({ "action": "wait", "timed_out": true }));
            return Ok(tool_result);
        }

        tokio::select! {
            biased;
            () = &mut cancelled => {
                return Err(ToolError::cancelled(
                    "Wait interrupted by user cancellation before child activity.".to_string(),
                ));
            }
            () = tokio::time::sleep(COORD_WAIT_CHECK_INTERVAL) => {}
        }
    }
}

/// Register the narrow coordination tools alongside `agent`.
pub fn register_coordination_tools(
    builder: ToolRegistryBuilder,
    manager: SharedSubAgentManager,
    runtime: SubAgentRuntime,
) -> ToolRegistryBuilder {
    // `runtime.parent_agent_id` is the identity of the agent this registry is
    // being built FOR: `runtime_for_nested_agent_tools` stamps the child's own
    // id there before `new_with_owner` registers tools, so anything that agent
    // spawns records it as parent. Thread that identity through every mutating
    // hierarchy tool: a child may control only its own descendants, while the
    // root registry (`None`) may control any child (TUI-DOG-017).
    let caller = runtime.parent_agent_id.clone();
    let message = AgentsMessageTool::new(Arc::clone(&manager)).with_optional_caller(caller.clone());
    let followup = AgentsFollowupTool::new(Arc::clone(&manager))
        .with_optional_caller(caller.clone())
        .with_runtime(runtime.clone());
    let interrupt =
        AgentsInterruptTool::new(Arc::clone(&manager)).with_optional_caller(caller.clone());
    let coordinate = AgentsCoordinateTool::new(Arc::clone(&manager), caller);
    builder
        .with_tool(Arc::new(AgentsListTool::new(Arc::clone(&manager))))
        .with_tool(Arc::new(message))
        .with_tool(Arc::new(followup))
        .with_tool(Arc::new(interrupt))
        .with_tool(Arc::new(coordinate))
        .with_tool(Arc::new(AgentsWaitTool::new(manager)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::spec::ToolContext;
    use tempfile::tempdir;

    #[test]
    fn coordinate_tool_does_not_declare_read_only() {
        // #5123-class: the tool mutates the coordination ledger and expands
        // write claims; its declared capabilities must not say ReadOnly.
        let manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(std::path::PathBuf::from("."), 1),
        ));
        let tool = AgentsCoordinateTool::new(manager, None);
        let capabilities = ToolSpec::capabilities(&tool);
        assert!(
            !capabilities.contains(&ToolCapability::ReadOnly),
            "agents/coordinate mutates the ledger — ReadOnly is a lie: {capabilities:?}"
        );
        // …but the dynamic check still marks inspect as read-only.
        assert!(tool.is_read_only_for(&json!({"action": "inspect"})));
        assert!(!tool.is_read_only_for(&json!({"action": "propose"})));
    }

    #[test]
    fn coordination_descriptions_match_implemented_resume_behavior() {
        // Checkpoint resume is implemented (#5242): the descriptions must
        // describe the real behavior, including the honest queue-only
        // fallback when no runtime is attached.
        let manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(std::env::temp_dir(), 1),
        ));
        let message = AgentsMessageTool::new(Arc::clone(&manager));
        let followup = AgentsFollowupTool::new(manager);

        assert!(!message.description().contains("natural resume"));
        assert!(message.description().contains("stays queued"));
        assert!(followup.description().contains("attempt to resume"));
        assert!(
            followup
                .description()
                .contains("resumed from their checkpoint")
        );
        assert!(followup.description().contains("queue-only semantics"));
    }

    async fn manager_with_running_child(
        workspace: &std::path::Path,
    ) -> (SharedSubAgentManager, String) {
        let manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(workspace.to_path_buf(), 4),
        ));
        let agent_id = {
            let mut guard = manager.write().await;
            guard.insert_test_running_agent("coord_child", workspace)
        };
        (manager, agent_id)
    }

    async fn manager_with_agent_hierarchy(
        workspace: &std::path::Path,
    ) -> (SharedSubAgentManager, String, String, String) {
        let manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(workspace.to_path_buf(), 8),
        ));
        let (parent, child, sibling) = {
            let mut guard = manager.write().await;
            let parent = guard.insert_test_running_agent("hierarchy_parent", workspace);
            let child = guard.insert_test_running_agent("hierarchy_child", workspace);
            let sibling = guard.insert_test_running_agent("hierarchy_sibling", workspace);
            for (agent_id, parent_id) in [
                (&parent, "root"),
                (&child, parent.as_str()),
                (&sibling, "root"),
            ] {
                let record = guard
                    .worker_records
                    .get_mut(agent_id)
                    .expect("hierarchy worker record");
                record.parent_run_id = Some(parent_id.to_string());
                record.spec.parent_run_id = Some(parent_id.to_string());
            }
            (parent, child, sibling)
        };
        (manager, parent, child, sibling)
    }

    #[tokio::test]
    async fn message_queues_without_waking() {
        let tmp = tempdir().unwrap();
        let (manager, agent_id) = manager_with_running_child(tmp.path()).await;
        let tool = AgentsMessageTool::new(Arc::clone(&manager));
        let result = tool
            .execute(
                json!({ "agent_id": agent_id, "message": "hold this" }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect("message ok");
        let body: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(body["woke"], json!(false));
        assert_eq!(body["queued"], json!(true));
        assert_eq!(body["queue_depth"], json!(1));

        let guard = manager.read().await;
        let depth = guard.queued_mail_depth(&agent_id).unwrap();
        assert_eq!(depth, 1);
        assert!(!guard.child_was_woken(&agent_id));
    }

    #[tokio::test]
    async fn followup_does_not_claim_wake_when_live_channel_is_closed() {
        let tmp = tempdir().unwrap();
        let (manager, agent_id) = manager_with_running_child(tmp.path()).await;
        let result = AgentsFollowupTool::new(Arc::clone(&manager))
            .execute(
                json!({ "agent_id": agent_id, "message": "try to wake" }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect("truthful closed-channel receipt");
        let body: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(body["woke"], json!(false));
        assert_eq!(body["queue_depth"], json!(1));
        assert!(
            body["note"].as_str().unwrap_or_default().contains("closed"),
            "{body}"
        );

        let guard = manager.read().await;
        assert_eq!(guard.queued_mail_depth(&agent_id), Some(1));
        assert!(!guard.child_was_woken(&agent_id));
    }

    #[tokio::test]
    async fn hierarchy_mutations_allow_own_descendants_and_deny_siblings_or_ancestors() {
        let tmp = tempdir().unwrap();
        let (manager, parent, child, sibling) = manager_with_agent_hierarchy(tmp.path()).await;
        let context = ToolContext::new(tmp.path());

        AgentsMessageTool::new(Arc::clone(&manager))
            .with_optional_caller(Some(parent.clone()))
            .execute(
                json!({ "agent_id": child, "message": "bounded parent note" }),
                &context,
            )
            .await
            .expect("parent may message its own child");
        AgentsFollowupTool::new(Arc::clone(&manager))
            .with_optional_caller(Some(parent.clone()))
            .execute(
                json!({ "agent_id": child, "message": "resume own child" }),
                &context,
            )
            .await
            .expect("parent may follow up its own child");

        let sibling_message = AgentsMessageTool::new(Arc::clone(&manager))
            .with_optional_caller(Some(parent.clone()))
            .execute(
                json!({ "agent_id": sibling, "message": "cross branch" }),
                &context,
            )
            .await
            .expect_err("sibling message must fail closed")
            .to_string();
        assert!(
            sibling_message.contains("own descendants"),
            "{sibling_message}"
        );

        let ancestor_followup = AgentsFollowupTool::new(Arc::clone(&manager))
            .with_optional_caller(Some(child.clone()))
            .execute(
                json!({ "agent_id": parent, "message": "wake ancestor" }),
                &context,
            )
            .await
            .expect_err("ancestor followup must fail closed")
            .to_string();
        assert!(
            ancestor_followup.contains("own descendants"),
            "{ancestor_followup}"
        );

        let sibling_interrupt = AgentsInterruptTool::new(Arc::clone(&manager))
            .with_optional_caller(Some(parent.clone()))
            .execute(json!({ "agent_id": sibling }), &context)
            .await
            .expect_err("sibling interrupt must fail closed")
            .to_string();
        assert!(
            sibling_interrupt.contains("own descendants"),
            "{sibling_interrupt}"
        );

        let interrupted = AgentsInterruptTool::new(Arc::clone(&manager))
            .with_optional_caller(Some(parent))
            .execute(json!({ "agent_id": child }), &context)
            .await
            .expect("parent may interrupt its own child");
        let body: Value = serde_json::from_str(&interrupted.content).unwrap();
        assert_eq!(body["status"], json!("interrupted"));
    }

    #[tokio::test]
    async fn coordinate_inspect_is_side_effect_free_and_mutations_are_synchronously_durable() {
        let tmp = tempdir().unwrap();
        let blocked_state_path = tmp.path().join("blocked-state");
        std::fs::create_dir(&blocked_state_path).unwrap();
        let blocked_manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
                .with_state_path(blocked_state_path),
        ));
        let blocked_tool = AgentsCoordinateTool::new(Arc::clone(&blocked_manager), None);

        blocked_tool
            .execute(
                json!({ "action": "inspect" }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect("read-only inspect must not attempt persistence");
        let error = blocked_tool
            .execute(
                json!({
                    "action": "propose",
                    "decision_id": "durable-decision",
                    "subject": "durability",
                    "constraints": ["persist before acknowledgement"]
                }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect_err("mutation must fail when its receipt cannot persist")
            .to_string();
        assert!(error.contains("failed to persist"), "{error}");
        assert!(
            blocked_manager
                .read()
                .await
                .coordination
                .decisions
                .is_empty(),
            "failed persistence must roll the in-memory decision back"
        );

        let durable_workspace = tempdir().unwrap();
        let state_path = durable_workspace.path().join("subagents.v1.json");
        let manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(durable_workspace.path().to_path_buf(), 4)
                .with_state_path(state_path.clone()),
        ));
        AgentsCoordinateTool::new(Arc::clone(&manager), None)
            .execute(
                json!({
                    "action": "propose",
                    "decision_id": "durable-decision",
                    "subject": "durability",
                    "constraints": ["persist before acknowledgement"]
                }),
                &ToolContext::new(durable_workspace.path()),
            )
            .await
            .expect("durable mutation");
        let mut replayed =
            super::super::SubAgentManager::new(durable_workspace.path().to_path_buf(), 4)
                .with_state_path(state_path);
        replayed.load_state().expect("reload durable action");
        assert_eq!(replayed.coordination.decisions.len(), 1);
        assert_eq!(
            replayed.coordination.decisions[0].decision_id,
            "durable-decision"
        );
    }

    #[tokio::test]
    async fn rejected_claim_contention_is_persisted_before_returning_the_error() {
        let tmp = tempdir().unwrap();
        let state_path = tmp.path().join("subagents.v1.json");
        let manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
                .with_state_path(state_path.clone()),
        ));
        let (claimant, owner) = {
            let mut guard = manager.write().await;
            let claimant = guard.insert_test_running_agent("claimant", tmp.path());
            let owner = guard.insert_test_running_agent("owner", tmp.path());
            let active = [claimant.clone(), owner.clone()]
                .into_iter()
                .collect::<BTreeSet<_>>();
            for claim in [
                WriteScopeClaim {
                    owner: claimant.clone(),
                    roots: vec!["src/claimant".into()],
                    exact_files: Vec::new(),
                    contracts: Vec::new(),
                },
                WriteScopeClaim {
                    owner: owner.clone(),
                    roots: vec!["src/shared".into()],
                    exact_files: Vec::new(),
                    contracts: Vec::new(),
                },
            ] {
                guard
                    .coordination
                    .register_claim(claim, false, |candidate| active.contains(candidate))
                    .expect("initial non-overlapping claim");
            }
            (claimant, owner)
        };

        let error = AgentsCoordinateTool::new(Arc::clone(&manager), Some(claimant.clone()))
            .execute(
                json!({ "action": "claim", "roots": ["src/shared/nested"] }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect_err("overlap must block")
            .to_string();
        assert!(
            error.contains(&owner) && error.contains("contention"),
            "{error}"
        );

        let mut replayed = super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
            .with_state_path(state_path);
        replayed.load_state().expect("reload contention receipt");
        assert_eq!(replayed.coordination.contentions.len(), 1);
        assert_eq!(replayed.coordination.contentions[0].claimant, claimant);
        assert_eq!(
            replayed.coordination.contentions[0].conflicting_owner,
            owner
        );
    }

    #[tokio::test]
    async fn coordination_resolution_survives_reload_and_resolving_claim_eviction() {
        let tmp = tempdir().unwrap();
        let state_path = tmp.path().join("subagents.v1.json");
        let manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
                .with_state_path(state_path.clone()),
        ));
        let claimant = {
            let mut guard = manager.write().await;
            let claimant = guard.insert_test_running_agent("claimant", tmp.path());
            let owner = guard.insert_test_running_agent("owner", tmp.path());
            let active = [claimant.clone(), owner.clone()]
                .into_iter()
                .collect::<BTreeSet<_>>();
            for claim in [
                WriteScopeClaim {
                    owner: claimant.clone(),
                    roots: vec!["src/claimant".into()],
                    exact_files: Vec::new(),
                    contracts: Vec::new(),
                },
                WriteScopeClaim {
                    owner: owner.clone(),
                    roots: vec!["src/shared".into()],
                    exact_files: Vec::new(),
                    contracts: Vec::new(),
                },
            ] {
                guard
                    .coordination
                    .register_claim(claim, false, |candidate| active.contains(candidate))
                    .expect("initial non-overlapping claim");
            }
            claimant
        };

        AgentsCoordinateTool::new(Arc::clone(&manager), Some(claimant.clone()))
            .execute(
                json!({ "action": "claim", "roots": ["src/shared/nested"] }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect_err("overlap must block and persist its receipt");

        let resolution_sequence = {
            let mut guard = manager.write().await;
            let record = guard
                .coordination
                .register_claim(
                    WriteScopeClaim {
                        owner: claimant.clone(),
                        roots: vec!["src/isolated".into()],
                        exact_files: Vec::new(),
                        contracts: Vec::new(),
                    },
                    true,
                    |_| true,
                )
                .expect("later isolated claim resolves contention");
            guard
                .persist_state_synchronously()
                .expect("persist resolved contention");
            record.sequence
        };

        let mut replayed = super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
            .with_state_path(state_path.clone());
        replayed.load_state().expect("reload resolved contention");
        assert_eq!(replayed.coordination.contentions.len(), 1);
        assert_eq!(
            replayed.coordination.contentions[0].disposition,
            WriteContentionDisposition::ResolvedBySuccessfulClaim
        );
        assert_eq!(
            replayed.coordination.contentions[0].resolution_sequence,
            Some(resolution_sequence)
        );

        let slots = COORDINATION_RECORD_LIMIT - replayed.coordination.write_claims.len();
        for index in 0..slots {
            replayed
                .coordination
                .register_claim(
                    WriteScopeClaim {
                        owner: format!("inactive-fill-{index:03}"),
                        roots: vec![format!("pkg/fill-{index:03}")],
                        exact_files: Vec::new(),
                        contracts: Vec::new(),
                    },
                    true,
                    |_| false,
                )
                .expect("fill inactive claim capacity");
        }
        for index in 0..2 {
            replayed
                .coordination
                .register_claim(
                    WriteScopeClaim {
                        owner: format!("inactive-overflow-{index}"),
                        roots: vec![format!("pkg/overflow-{index}")],
                        exact_files: Vec::new(),
                        contracts: Vec::new(),
                    },
                    true,
                    |_| false,
                )
                .expect("evict oldest inactive claim at capacity");
        }
        assert!(
            !replayed
                .coordination
                .write_claims
                .iter()
                .any(|claim| claim.claim.owner == claimant),
            "the resolving claimant claim must be evicted for the durability regression"
        );
        replayed
            .persist_state_synchronously()
            .expect("persist after inactive claim eviction");

        let mut final_replay = super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4)
            .with_state_path(state_path);
        final_replay
            .load_state()
            .expect("reload after resolving claim eviction");
        let projection = final_replay.coordination_detail_projection(None, 24);
        assert!(
            !projection
                .write_claims
                .iter()
                .any(|claim| claim.claim.owner == claimant)
        );
        assert_eq!(projection.contentions.len(), 1);
        assert_eq!(
            projection.contentions[0].disposition,
            WriteContentionDisposition::ResolvedBySuccessfulClaim
        );
        assert_eq!(
            projection.contentions[0].resolution_sequence,
            Some(resolution_sequence)
        );
        assert!(!crate::tui::coordination_detail::needs_attention(
            &projection
        ));
        let pager =
            crate::tui::coordination_detail::format(crate::localization::Locale::En, &projection);
        assert!(
            pager.contains("disposition resolved_by_successful_claim"),
            "{pager}"
        );
        assert!(!pager.contains("disposition blocked_pending"), "{pager}");
    }

    #[tokio::test]
    async fn interrupt_fails_closed_on_self() {
        let tmp = tempdir().unwrap();
        let (manager, agent_id) = manager_with_running_child(tmp.path()).await;
        let tool = AgentsInterruptTool::new(Arc::clone(&manager)).with_caller(agent_id.clone());
        let err = tool
            .execute(
                json!({ "agent_id": agent_id }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect_err("self interrupt must fail");
        let msg = err.to_string().to_ascii_lowercase();
        assert!(
            msg.contains("self") || msg.contains("own"),
            "unexpected error: {err}"
        );
    }

    #[tokio::test]
    async fn interrupt_fails_closed_on_missing_target() {
        let tmp = tempdir().unwrap();
        let manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(tmp.path().to_path_buf(), 2),
        ));
        let tool = AgentsInterruptTool::new(manager);
        let err = tool
            .execute(
                json!({ "agent_id": "agent_missing" }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect_err("missing target");
        assert!(err.to_string().contains("not found") || err.to_string().contains("Agent"));
    }

    #[tokio::test]
    async fn wait_times_out_when_child_stays_running() {
        let tmp = tempdir().unwrap();
        let (manager, agent_id) = manager_with_running_child(tmp.path()).await;
        let tool = AgentsWaitTool::new(manager);
        let result = tool
            .execute(
                json!({
                    "agent_id": agent_id,
                    "timeout_secs": 1,
                    "until": "activity"
                }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect("wait returns");
        let body: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(body["timed_out"], json!(true));
    }

    #[tokio::test]
    async fn list_resolves_target_and_reports_queue() {
        let tmp = tempdir().unwrap();
        let (manager, agent_id) = manager_with_running_child(tmp.path()).await;
        {
            let mut guard = manager.write().await;
            guard
                .queue_parent_message(&agent_id, "note".into(), false)
                .unwrap();
        }
        let tool = AgentsListTool::new(manager);
        let result = tool
            .execute(
                json!({ "agent_id": agent_id }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect("list ok");
        let body: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(body["count"], json!(1));
        assert_eq!(body["agents"][0]["agent_id"], json!(agent_id));
        assert!(body["agents"][0]["queued_mail"].as_u64().unwrap_or(0) >= 1);
    }

    #[tokio::test]
    async fn followup_interrupted_continuable_without_runtime_queues_honestly() {
        let tmp = tempdir().unwrap();
        let manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4),
        ));
        let (agent_id, handle) = {
            let mut guard = manager.write().await;
            guard.insert_test_interrupted_continuable_agent(
                "paused_child",
                tmp.path(),
                vec![crate::models::Message {
                    role: "user".to_string(),
                    content: vec![crate::models::ContentBlock::Text {
                        text: "prior work".to_string(),
                        cache_control: None,
                    }],
                }],
            )
        };
        // No runtime attached: checkpoint resume is unavailable, so followup
        // keeps the honest queue-only semantics with the continuation handle.
        let tool = AgentsFollowupTool::new(Arc::clone(&manager));
        let result = tool
            .execute(
                json!({ "agent_id": agent_id, "message": "please continue" }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect("followup ok");
        let body: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(body["queued"], json!(true));
        assert_eq!(body["woke"], json!(false));
        assert_eq!(body["continued_from_checkpoint"], json!(false));
        assert_eq!(body["continuation_handle"], json!(handle));
        let note = body["note"].as_str().unwrap_or_default();
        assert!(
            note.contains("attach a runtime") && note.contains(&handle),
            "note must point at the resume path with the continuation handle: {note}"
        );

        let guard = manager.read().await;
        assert_eq!(guard.queued_mail_depth(&agent_id).unwrap(), 1);
        assert!(!guard.child_was_woken(&agent_id));
    }

    // === until="all": the fan-out join ===================================
    //
    // Before this existed a parent with five children had to issue five
    // waits — while the prompt told it not to poll. These lock the join in.

    fn empty_manager(workspace: &std::path::Path) -> SharedSubAgentManager {
        Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(workspace.to_path_buf(), 8),
        ))
    }

    async fn settle(manager: &SharedSubAgentManager, agent_id: &str, status: SubAgentStatus) {
        let mut guard = manager.write().await;
        if let Some(agent) = guard.agents.get_mut(agent_id) {
            agent.status = status;
        }
    }

    #[test]
    fn wait_schema_offers_all_as_a_first_class_until() {
        let tmp = tempdir().unwrap();
        let tool = AgentsWaitTool::new(empty_manager(tmp.path()));
        let schema = tool.input_schema();
        let until = &schema["properties"]["until"];
        assert_eq!(
            until["enum"],
            json!(["completion", "all", "activity"]),
            "until must expose all alongside completion/activity: {schema}"
        );
        let described = until["description"].as_str().unwrap_or_default();
        assert!(
            described.contains("every watched child") && described.contains("any one child"),
            "the schema must make completion vs all unmistakable: {described}"
        );
    }

    #[tokio::test]
    async fn wait_until_all_on_an_already_settled_child_reports_its_outcome() {
        let tmp = tempdir().unwrap();
        let manager = empty_manager(tmp.path());
        let agent_id = {
            let mut guard = manager.write().await;
            guard.insert_test_running_agent("all_already_done", tmp.path())
        };
        settle(&manager, &agent_id, SubAgentStatus::Completed).await;

        let result = dispatch_wait(
            &json!({ "until": "all", "agent_id": agent_id, "timeout_secs": 60 }),
            Arc::clone(&manager),
            &ToolContext::new(tmp.path()),
        )
        .await
        .expect("a settled child is an immediate return");
        let body: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(body["all_settled"], json!(true), "{body}");
        let settled = body["settled"].as_array().unwrap();
        assert_eq!(settled.len(), 1, "{body}");
        assert_eq!(settled[0]["status"], json!("completed"), "{body}");
    }

    #[tokio::test]
    async fn wait_until_all_returns_immediately_with_no_children() {
        let tmp = tempdir().unwrap();
        let started = Instant::now();
        let result = dispatch_wait(
            &json!({ "until": "all", "timeout_secs": 60 }),
            empty_manager(tmp.path()),
            &ToolContext::new(tmp.path()),
        )
        .await
        .expect("wait-for-all with zero children must return, not hang");
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "zero children must not burn the timeout"
        );
        let body: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(body["all_settled"], json!(true));
        assert_eq!(body["timed_out"], json!(false));
        assert!(body["settled"].as_array().unwrap().is_empty(), "{body}");
    }

    #[tokio::test]
    async fn wait_until_all_blocks_until_every_child_settles() {
        let tmp = tempdir().unwrap();
        let manager = empty_manager(tmp.path());
        let (first, second, third) = {
            let mut guard = manager.write().await;
            (
                guard.insert_test_running_agent("all_first", tmp.path()),
                guard.insert_test_running_agent("all_second", tmp.path()),
                guard.insert_test_running_agent("all_third", tmp.path()),
            )
        };

        // Staggered settles: an `until=completion` wait would return after the
        // first one. `until=all` must stay blocked through the last.
        let flip = Arc::clone(&manager);
        let (a, b, c) = (first.clone(), second.clone(), third.clone());
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            settle(&flip, &a, SubAgentStatus::Completed).await;
            tokio::time::sleep(Duration::from_millis(150)).await;
            settle(&flip, &b, SubAgentStatus::Failed("boom".to_string())).await;
            tokio::time::sleep(Duration::from_millis(150)).await;
            settle(&flip, &c, SubAgentStatus::Cancelled).await;
        });

        let result = dispatch_wait(
            &json!({ "until": "all", "timeout_secs": 30 }),
            Arc::clone(&manager),
            &ToolContext::new(tmp.path()),
        )
        .await
        .expect("wait-for-all should succeed");
        let body: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(body["all_settled"], json!(true), "{body}");
        assert_eq!(body["timed_out"], json!(false), "{body}");
        assert!(
            body["still_running"].as_array().unwrap().is_empty(),
            "{body}"
        );

        // Per-child outcomes come back on the single return.
        let settled = body["settled"].as_array().unwrap();
        assert_eq!(settled.len(), 3, "{body}");
        let outcomes: std::collections::BTreeMap<&str, &str> = settled
            .iter()
            .map(|entry| {
                (
                    entry["agent_id"].as_str().unwrap(),
                    entry["status"].as_str().unwrap(),
                )
            })
            .collect();
        assert_eq!(outcomes.get(first.as_str()), Some(&"completed"), "{body}");
        assert_eq!(outcomes.get(second.as_str()), Some(&"failed"), "{body}");
        assert_eq!(outcomes.get(third.as_str()), Some(&"cancelled"), "{body}");
    }

    #[tokio::test]
    async fn wait_until_all_times_out_reporting_settled_and_still_running() {
        let tmp = tempdir().unwrap();
        let manager = empty_manager(tmp.path());
        let (done, stuck) = {
            let mut guard = manager.write().await;
            (
                guard.insert_test_running_agent("all_done", tmp.path()),
                guard.insert_test_running_agent("all_stuck", tmp.path()),
            )
        };

        let flip = Arc::clone(&manager);
        let done_id = done.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            settle(&flip, &done_id, SubAgentStatus::Completed).await;
        });

        let result = dispatch_wait(
            &json!({ "until": "all", "timeout_secs": 1 }),
            Arc::clone(&manager),
            &ToolContext::new(tmp.path()),
        )
        .await
        .expect("a timeout is a partial receipt, not an error");
        let body: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(body["timed_out"], json!(true), "{body}");
        assert_eq!(body["all_settled"], json!(false), "{body}");

        let settled = body["settled"].as_array().unwrap();
        assert_eq!(settled.len(), 1, "{body}");
        assert_eq!(settled[0]["agent_id"], json!(done), "{body}");
        assert_eq!(settled[0]["status"], json!("completed"), "{body}");

        let running = body["still_running"].as_array().unwrap();
        assert_eq!(running.len(), 1, "{body}");
        assert_eq!(running[0]["agent_id"], json!(stuck), "{body}");
    }

    #[tokio::test]
    async fn wait_until_all_ignores_children_spawned_mid_wait() {
        let tmp = tempdir().unwrap();
        let manager = empty_manager(tmp.path());
        let original = {
            let mut guard = manager.write().await;
            guard.insert_test_running_agent("all_original", tmp.path())
        };

        let flip = Arc::clone(&manager);
        let tmp_path = tmp.path().to_path_buf();
        let original_id = original.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            {
                let mut guard = flip.write().await;
                guard.insert_test_running_agent("all_latecomer", &tmp_path);
            }
            settle(&flip, &original_id, SubAgentStatus::Completed).await;
        });

        let result = dispatch_wait(
            &json!({ "until": "all", "timeout_secs": 30 }),
            Arc::clone(&manager),
            &ToolContext::new(tmp.path()),
        )
        .await
        .expect("wait-for-all should succeed");
        let body: Value = serde_json::from_str(&result.content).unwrap();
        // The watch set is the batch as of call time: the latecomer must not
        // extend a wait the caller never asked to include it in.
        assert_eq!(body["all_settled"], json!(true), "{body}");
        assert_eq!(body["timed_out"], json!(false), "{body}");
        let settled = body["settled"].as_array().unwrap();
        assert_eq!(settled.len(), 1, "{body}");
        assert_eq!(settled[0]["agent_id"], json!(original), "{body}");
    }

    #[tokio::test]
    async fn wait_rejects_unknown_until_naming_every_supported_mode() {
        let tmp = tempdir().unwrap();
        let error = dispatch_wait(
            &json!({ "until": "forever" }),
            empty_manager(tmp.path()),
            &ToolContext::new(tmp.path()),
        )
        .await
        .expect_err("an unknown until must fail loudly");
        let message = error.to_string();
        for mode in ["completion", "all", "activity"] {
            assert!(message.contains(mode), "{message}");
        }
    }

    #[tokio::test]
    async fn followup_interrupted_continuable_resumes_with_runtime() {
        let tmp = tempdir().unwrap();
        let manager = Arc::new(tokio::sync::RwLock::new(
            super::super::SubAgentManager::new(tmp.path().to_path_buf(), 4),
        ));
        let (agent_id, _handle) = {
            let mut guard = manager.write().await;
            guard.insert_test_interrupted_continuable_agent(
                "paused_child",
                tmp.path(),
                vec![crate::models::Message {
                    role: "user".to_string(),
                    content: vec![crate::models::ContentBlock::Text {
                        text: "prior work".to_string(),
                        cache_control: None,
                    }],
                }],
            )
        };
        let mut runtime = super::super::tests::stub_runtime();
        runtime.manager = Arc::clone(&manager);
        let tool = AgentsFollowupTool::new(Arc::clone(&manager)).with_runtime(runtime);
        let result = tool
            .execute(
                json!({ "agent_id": agent_id, "message": "please continue" }),
                &ToolContext::new(tmp.path()),
            )
            .await
            .expect("followup ok");
        let body: Value = serde_json::from_str(&result.content).unwrap();
        assert_eq!(body["queued"], json!(true));
        assert_eq!(body["woke"], json!(true));
        assert_eq!(body["continued_from_checkpoint"], json!(true));
        let note = body["note"].as_str().unwrap_or_default();
        assert!(note.contains("resumed from checkpoint"), "{note}");
        let resumed_id = body["agent_id"].as_str().unwrap_or_default();
        assert_ne!(
            resumed_id, agent_id,
            "resume re-dispatches under a new agent id"
        );

        // A fresh record exists for the resumed session; the prior terminal
        // record stays immutable (receipts are never rewritten).
        let guard = manager.read().await;
        guard.get_result(resumed_id).expect("resumed agent exists");
        let prior = guard.get_result(&agent_id).expect("prior record");
        assert!(matches!(prior.status, SubAgentStatus::Interrupted(_)));
    }
}

/// Coordination records for delegated Work (#4647).
///
/// Decision records, write-scope claims, and contention detection for parallel
/// agent work. Parallel work may proceed only when scopes and contracts do not
/// collide silently.
/// Status of a coordination decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionStatus {
    Proposed,
    Accepted,
    Superseded,
}

/// Serialized coordination state schema. Increment only with an explicit
/// migration; restart/replay must never infer a newer contract from old data.
pub const COORDINATION_SCHEMA_VERSION: u32 = 1;

const MAX_RECONCILIATION_RETRIES: u32 = 3;

const fn coordination_schema_version() -> u32 {
    COORDINATION_SCHEMA_VERSION
}

/// A bounded coordination decision record (#4647).
///
/// Persisted with stable subject, concise constraints, one active owner,
/// applicability scope, evidence handles, and sequence/version.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DecisionRecord {
    pub decision_id: String,
    pub subject: String,
    pub status: DecisionStatus,
    pub owner: String,
    pub scope: Vec<String>,
    pub constraints: Vec<String>,
    pub evidence_handles: Vec<String>,
    pub version: u32,
    pub sequence: u64,
}

/// A write-scope claim for a write-capable child (#4647).
///
/// Declares expected repo-relative paths/trees and named contracts.
/// This is coordination metadata, not another approval system.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WriteScopeClaim {
    pub owner: String,
    pub roots: Vec<String>,
    pub exact_files: Vec<String>,
    pub contracts: Vec<String>,
}

impl WriteScopeClaim {
    /// Check whether this claim overlaps with another. A claim overlaps when
    /// either normalized tree contains the other or exact files collide.
    #[must_use]
    pub fn overlaps(&self, other: &WriteScopeClaim) -> bool {
        for root_a in &self.roots {
            for root_b in &other.roots {
                if paths_overlap_by_containment(root_a, root_b)
                    || paths_overlap_by_containment(root_b, root_a)
                {
                    return true;
                }
            }
        }
        for file_a in &self.exact_files {
            if other
                .exact_files
                .iter()
                .any(|file| paths_overlap_equal(file, file_a))
                || other
                    .roots
                    .iter()
                    .any(|root| paths_overlap_by_containment(root, file_a))
            {
                return true;
            }
        }
        for file_b in &other.exact_files {
            if self
                .roots
                .iter()
                .any(|root| paths_overlap_by_containment(root, file_b))
            {
                return true;
            }
        }
        if self
            .contracts
            .iter()
            .any(|contract| other.contracts.iter().any(|other| other == contract))
        {
            return true;
        }
        false
    }

    #[must_use]
    pub fn contains_path(&self, path: &str) -> bool {
        self.exact_files.iter().any(|file| file == path)
            || self.roots.iter().any(|root| path_contains(root, path))
    }
}

fn path_contains(root: &str, candidate: &str) -> bool {
    let root = root.trim_end_matches('/');
    let candidate = candidate.trim_end_matches('/');
    root == "."
        || root == candidate
        || candidate
            .strip_prefix(root)
            .is_some_and(|suffix| suffix.starts_with('/'))
}

fn paths_overlap_equal(left: &str, right: &str) -> bool {
    left == right || left.to_lowercase() == right.to_lowercase()
}

fn paths_overlap_by_containment(root: &str, candidate: &str) -> bool {
    path_contains(root, candidate) || path_contains(&root.to_lowercase(), &candidate.to_lowercase())
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PersistedWriteClaim {
    pub claim: WriteScopeClaim,
    pub sequence: u64,
    #[serde(default)]
    pub isolated_worktree: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ReconciliationReceipt {
    pub reconciliation_id: String,
    pub subject: String,
    pub owner: String,
    pub input_decisions: Vec<String>,
    pub outcome: String,
    pub evidence_handles: Vec<String>,
    /// Preserved candidate branches, patches, or artifact handles. A fan-in
    /// receipt is not valid if either conflicting candidate was discarded.
    #[serde(default)]
    pub candidate_handles: Vec<String>,
    #[serde(default)]
    pub retry_count: u32,
    #[serde(default)]
    pub retry_limit: u32,
    #[serde(default)]
    pub reviewer_evidence_handles: Vec<String>,
    #[serde(default)]
    pub verifier_evidence_handles: Vec<String>,
    #[serde(default)]
    pub verification_outcome: String,
    pub sequence: u64,
}

/// Durable receipt for the minimal accepted-decision context projected into a
/// child. It records counts and stable ids, never the child's transcript.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ContextProjectionReceipt {
    pub child_id: String,
    pub decision_ids: Vec<String>,
    pub projected_bytes: usize,
    /// Repeated constraint facts elided across otherwise distinct decisions.
    /// Decision records themselves are never collapsed by this count.
    pub deduplicated: usize,
    /// Relevant unique decisions omitted solely because the hard count or
    /// byte bound was reached. This must not be conflated with deduplication.
    #[serde(default)]
    pub omitted: usize,
    pub sequence: u64,
}

/// Admission outcome persisted with a write-contention receipt.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum WriteContentionDisposition {
    BlockedPendingIsolationOrSerialization,
    ResolvedBySuccessfulClaim,
}

impl WriteContentionDisposition {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::BlockedPendingIsolationOrSerialization => {
                "blocked_pending_isolation_or_serialization"
            }
            Self::ResolvedBySuccessfulClaim => "resolved_by_successful_claim",
        }
    }

    #[must_use]
    pub const fn blocks_admission(self) -> bool {
        matches!(self, Self::BlockedPendingIsolationOrSerialization)
    }
}

/// Durable non-secret receipt emitted when two active shared-workspace claims
/// collide. Rejected scope expansion remains visible after restart.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WriteContentionReceipt {
    pub claimant: String,
    pub conflicting_owner: String,
    pub roots: Vec<String>,
    pub exact_files: Vec<String>,
    pub contracts: Vec<String>,
    pub disposition: WriteContentionDisposition,
    /// Sequence of the later successful claim that resolved this receipt.
    /// It intentionally references that claim's sequence instead of consuming
    /// another ledger sequence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolution_sequence: Option<u64>,
    pub sequence: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CoordinationHotPath {
    pub path: String,
    pub active_claims: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CoordinationDetailMetrics {
    pub hottest_paths: Vec<CoordinationHotPath>,
    pub package_or_module_growth: Option<Value>,
    pub route_or_cost: Option<Value>,
    pub note: String,
}

/// One bounded typed projection shared by headless inspection and the TUI.
/// It contains durable coordination facts only, never raw reasoning or a
/// delegated transcript.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CoordinationDetailProjection {
    pub schema_version: u32,
    pub sequence: u64,
    pub decisions: Vec<DecisionRecord>,
    pub write_claims: Vec<PersistedWriteClaim>,
    pub reconciliations: Vec<ReconciliationReceipt>,
    pub context_projections: Vec<ContextProjectionReceipt>,
    pub contentions: Vec<WriteContentionReceipt>,
    pub metrics: CoordinationDetailMetrics,
    pub bounded: bool,
    pub limit: usize,
    /// Whether this process currently holds the workspace coordination flock.
    /// When false, durable ledger writes are skipped and the UI must say so —
    /// a counter must never tick on a turn the engine has already settled.
    #[serde(default = "default_process_lock_held")]
    pub process_lock_held: bool,
    /// Human-readable reason when [`Self::process_lock_held`] is false.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub process_lock_note: Option<String>,
}

fn default_process_lock_held() -> bool {
    // Legacy projections (tests, older sessions) assume the lock is held so
    // they do not spuriously light the unavailable banner.
    true
}

/// Durable, bounded coordination state owned by `SubAgentManager`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordinationLedger {
    #[serde(default = "coordination_schema_version")]
    pub schema_version: u32,
    #[serde(default)]
    pub sequence: u64,
    #[serde(default)]
    pub decisions: Vec<DecisionRecord>,
    #[serde(default)]
    pub write_claims: Vec<PersistedWriteClaim>,
    #[serde(default)]
    pub reconciliations: Vec<ReconciliationReceipt>,
    #[serde(default)]
    pub projections: Vec<ContextProjectionReceipt>,
    #[serde(default)]
    pub contentions: Vec<WriteContentionReceipt>,
}

impl Default for CoordinationLedger {
    fn default() -> Self {
        Self {
            schema_version: COORDINATION_SCHEMA_VERSION,
            sequence: 0,
            decisions: Vec::new(),
            write_claims: Vec::new(),
            reconciliations: Vec::new(),
            projections: Vec::new(),
            contentions: Vec::new(),
        }
    }
}

impl CoordinationLedger {
    fn next_sequence(&mut self) -> u64 {
        self.sequence = self.sequence.saturating_add(1);
        self.sequence
    }

    pub fn record_decision(
        &mut self,
        mut decision: DecisionRecord,
    ) -> Result<DecisionRecord, String> {
        self.validate_schema()?;
        decision.decision_id = decision.decision_id.trim().to_string();
        if !decision.decision_id.is_empty() {
            decision.decision_id = bounded_coordination_atom("decision id", &decision.decision_id)?;
        }
        decision.subject = bounded_coordination_atom("decision subject", &decision.subject)?;
        decision.owner = bounded_coordination_atom("decision owner", &decision.owner)?;
        decision.scope = normalize_coordination_values("decision scope", &decision.scope, 24)?;
        decision.constraints =
            normalize_coordination_values("decision constraints", &decision.constraints, 24)?;
        decision.evidence_handles = normalize_coordination_values(
            "decision evidence handles",
            &decision.evidence_handles,
            24,
        )?;
        reject_sensitive_coordination_values(&decision.constraints)?;
        reject_sensitive_coordination_values(&decision.evidence_handles)?;
        if decision.subject.trim().is_empty() || decision.owner.trim().is_empty() {
            return Err("decision subject and owner are required".to_string());
        }
        if !decision.decision_id.trim().is_empty()
            && self
                .decisions
                .iter()
                .any(|existing| existing.decision_id == decision.decision_id)
        {
            return Err(format!(
                "decision id '{}' already exists",
                decision.decision_id
            ));
        }
        if decision.status == DecisionStatus::Accepted
            && let Some(existing) = self.decisions.iter().find(|existing| {
                existing.subject == decision.subject
                    && existing.status == DecisionStatus::Accepted
                    && existing.decision_id != decision.decision_id
            })
        {
            return Err(format!(
                "subject '{}' already has accepted decision '{}' owned by '{}'; preserve both candidates and use neutral reconciliation",
                decision.subject, existing.decision_id, existing.owner
            ));
        }
        let next_version = self
            .decisions
            .iter()
            .filter(|existing| existing.subject == decision.subject)
            .map(|existing| existing.version)
            .max()
            .unwrap_or(0)
            .saturating_add(1);
        decision.version = decision.version.max(next_version);
        decision.sequence = self.next_sequence();
        if decision.decision_id.trim().is_empty() {
            decision.decision_id = format!("decision_{}", decision.sequence);
        }
        self.decisions.push(decision.clone());
        if self.decisions.len() > COORDINATION_RECORD_LIMIT {
            let referenced = self
                .reconciliations
                .iter()
                .flat_map(|receipt| receipt.input_decisions.iter())
                .cloned()
                .collect::<BTreeSet<_>>();
            if let Some(index) = self.decisions.iter().position(|existing| {
                existing.status != DecisionStatus::Accepted
                    && !referenced.contains(&existing.decision_id)
            }) {
                self.decisions.remove(index);
            } else {
                self.decisions.pop();
                return Err(
                    "coordination decision capacity is occupied by accepted or reconciled records"
                        .to_string(),
                );
            }
        }
        Ok(decision)
    }

    pub fn update_decision_status(
        &mut self,
        decision_id: &str,
        status: DecisionStatus,
        owner: &str,
        expected_version: u32,
    ) -> Result<DecisionRecord, String> {
        self.validate_schema()?;
        let Some(index) = self
            .decisions
            .iter()
            .position(|decision| decision.decision_id == decision_id)
        else {
            return Err(format!("decision '{decision_id}' not found"));
        };
        if self.decisions[index].owner != owner {
            return Err(format!(
                "decision '{decision_id}' is owned by '{}'; caller '{owner}' cannot change it",
                self.decisions[index].owner
            ));
        }
        if self.decisions[index].version != expected_version {
            return Err(format!(
                "decision '{decision_id}' version changed: expected {expected_version}, current {}",
                self.decisions[index].version
            ));
        }
        let subject = self.decisions[index].subject.clone();
        if status == DecisionStatus::Accepted
            && let Some(existing) =
                self.decisions
                    .iter()
                    .enumerate()
                    .find_map(|(other_index, existing)| {
                        (other_index != index
                            && existing.subject == subject
                            && existing.status == DecisionStatus::Accepted)
                            .then_some(existing)
                    })
        {
            return Err(format!(
                "subject '{subject}' already has accepted decision '{}' owned by '{}'; preserve both candidates and use neutral reconciliation",
                existing.decision_id, existing.owner
            ));
        }
        let sequence = self.next_sequence();
        let decision = &mut self.decisions[index];
        decision.status = status;
        decision.version = decision.version.saturating_add(1);
        decision.sequence = sequence;
        Ok(decision.clone())
    }

    pub fn register_claim<F>(
        &mut self,
        mut claim: WriteScopeClaim,
        isolated_worktree: bool,
        mut owner_is_active: F,
    ) -> Result<PersistedWriteClaim, String>
    where
        F: FnMut(&str) -> bool,
    {
        self.validate_schema()?;
        claim.owner = bounded_coordination_atom("write claim owner", &claim.owner)?;
        claim.roots = normalize_claim_paths(&claim.roots)?;
        claim.exact_files = normalize_claim_paths(&claim.exact_files)?;
        claim.contracts = normalize_claim_strings(&claim.contracts, 16, 128, "contracts")?;
        if claim.roots.is_empty() && claim.exact_files.is_empty() && claim.contracts.is_empty() {
            return Err(
                "write claim requires an owner and at least one root, file, or contract"
                    .to_string(),
            );
        }
        let replacing_existing_owner = self
            .write_claims
            .iter()
            .any(|existing| existing.claim.owner == claim.owner);
        if !replacing_existing_owner && self.write_claims.len() >= COORDINATION_RECORD_LIMIT {
            let mut inactive = Vec::new();
            for existing in &self.write_claims {
                if !owner_is_active(&existing.claim.owner) {
                    inactive.push((existing.sequence, existing.claim.owner.clone()));
                }
            }
            inactive.sort_by_key(|(sequence, _)| *sequence);
            for (_, owner) in inactive {
                if self.write_claims.len() < COORDINATION_RECORD_LIMIT {
                    break;
                }
                self.write_claims
                    .retain(|existing| existing.claim.owner != owner);
            }
            if self.write_claims.len() >= COORDINATION_RECORD_LIMIT {
                return Err(format!(
                    "write-claim capacity is {COORDINATION_RECORD_LIMIT} active owners; complete, serialize, or isolate existing work before admitting another writer"
                ));
            }
        }
        if !isolated_worktree
            && let Some(existing) = self
                .write_claims
                .iter()
                .find(|existing| {
                    !existing.isolated_worktree
                        && existing.claim.owner != claim.owner
                        && owner_is_active(&existing.claim.owner)
                        && existing.claim.overlaps(&claim)
                })
                .cloned()
        {
            let receipt = WriteContentionReceipt {
                claimant: claim.owner.clone(),
                conflicting_owner: existing.claim.owner.clone(),
                roots: claim.roots.clone(),
                exact_files: claim.exact_files.clone(),
                contracts: claim.contracts.clone(),
                disposition: WriteContentionDisposition::BlockedPendingIsolationOrSerialization,
                resolution_sequence: None,
                sequence: self.next_sequence(),
            };
            self.contentions.push(receipt);
            trim_front(&mut self.contentions, COORDINATION_RECORD_LIMIT);
            return Err(format!(
                "write-scope contention with {} (roots: {:?}, files: {:?}, contracts: {:?}); serialize the work, narrow the claim, or use worktree isolation",
                existing.claim.owner,
                existing.claim.roots,
                existing.claim.exact_files,
                existing.claim.contracts
            ));
        }
        self.write_claims
            .retain(|existing| existing.claim.owner != claim.owner);
        let record = PersistedWriteClaim {
            claim,
            sequence: self.next_sequence(),
            isolated_worktree,
        };
        for contention in &mut self.contentions {
            if contention.claimant == record.claim.owner
                && contention.disposition.blocks_admission()
            {
                contention.disposition = WriteContentionDisposition::ResolvedBySuccessfulClaim;
                contention.resolution_sequence = Some(record.sequence);
            }
        }
        self.write_claims.push(record.clone());
        Ok(record)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn reconcile(
        &mut self,
        subject: String,
        owner: String,
        input_decisions: Vec<String>,
        outcome: String,
        evidence_handles: Vec<String>,
        candidate_handles: Vec<String>,
        retry_count: u32,
        retry_limit: u32,
        reviewer_evidence_handles: Vec<String>,
        verifier_evidence_handles: Vec<String>,
        verification_outcome: String,
    ) -> Result<ReconciliationReceipt, String> {
        self.validate_schema()?;
        let subject = bounded_coordination_atom("reconciliation subject", &subject)?;
        let owner = bounded_coordination_atom("reconciliation owner", &owner)?;
        let outcome = bounded_coordination_atom("reconciliation outcome", &outcome)?;
        let verification_outcome = bounded_coordination_atom(
            "reconciliation verification outcome",
            &verification_outcome,
        )?;
        if input_decisions.len() < 2 {
            return Err("neutral fan-in requires at least two input decisions".to_string());
        }
        if input_decisions.iter().collect::<BTreeSet<_>>().len() != input_decisions.len() {
            return Err("neutral fan-in decision ids must be distinct".to_string());
        }
        if candidate_handles.len() < 2
            || candidate_handles
                .iter()
                .any(|handle| handle.trim().is_empty())
        {
            return Err(
                "neutral fan-in must preserve at least two candidate branch, patch, or artifact handles"
                    .to_string(),
            );
        }
        if candidate_handles.iter().collect::<BTreeSet<_>>().len() != candidate_handles.len() {
            return Err("neutral fan-in candidate handles must be distinct".to_string());
        }
        let input_decisions =
            normalize_coordination_values("input decision ids", &input_decisions, 24)?;
        let evidence_handles = normalize_coordination_values(
            "reconciliation evidence handles",
            &evidence_handles,
            24,
        )?;
        let candidate_handles =
            normalize_coordination_values("candidate handles", &candidate_handles, 24)?;
        if input_decisions.len() < 2 {
            return Err(
                "neutral fan-in requires at least two distinct normalized input decisions"
                    .to_string(),
            );
        }
        if candidate_handles.len() < 2 {
            return Err(
                "neutral fan-in must preserve at least two distinct normalized candidate handles"
                    .to_string(),
            );
        }
        let reviewer_evidence_handles = normalize_coordination_values(
            "Reviewer evidence handles",
            &reviewer_evidence_handles,
            24,
        )?;
        let verifier_evidence_handles = normalize_coordination_values(
            "Verifier evidence handles",
            &verifier_evidence_handles,
            24,
        )?;
        reject_sensitive_coordination_values(&evidence_handles)?;
        reject_sensitive_coordination_values(&candidate_handles)?;
        reject_sensitive_coordination_values(&reviewer_evidence_handles)?;
        reject_sensitive_coordination_values(&verifier_evidence_handles)?;
        if retry_limit == 0 || retry_limit > MAX_RECONCILIATION_RETRIES {
            return Err(format!(
                "reconciliation retry_limit must be between 1 and {MAX_RECONCILIATION_RETRIES}"
            ));
        }
        if retry_count > retry_limit {
            return Err("reconciliation retry_count exceeds retry_limit".to_string());
        }
        if reviewer_evidence_handles.is_empty() || verifier_evidence_handles.is_empty() {
            return Err(
                "neutral fan-in requires independent Reviewer and Verifier evidence handles"
                    .to_string(),
            );
        }
        if reviewer_evidence_handles.iter().any(|review| {
            verifier_evidence_handles
                .iter()
                .any(|verify| verify == review)
        }) {
            return Err("Reviewer and Verifier evidence handles must be independent".to_string());
        }
        if !matches!(
            verification_outcome.as_str(),
            "verified" | "failed" | "blocked"
        ) {
            return Err(
                "neutral fan-in verification_outcome must be verified, failed, or blocked"
                    .to_string(),
            );
        }
        if input_decisions.iter().any(|id| {
            !self
                .decisions
                .iter()
                .any(|decision| &decision.decision_id == id)
        }) {
            return Err("reconciliation references an unknown decision".to_string());
        }
        let inputs = input_decisions
            .iter()
            .filter_map(|id| {
                self.decisions
                    .iter()
                    .find(|decision| &decision.decision_id == id)
            })
            .collect::<Vec<_>>();
        if inputs.iter().any(|decision| decision.subject != subject) {
            return Err("reconciliation inputs must share the requested subject".to_string());
        }
        if inputs.iter().any(|decision| decision.owner == owner) {
            return Err(
                "neutral fan-in owner must differ from every input decision owner".to_string(),
            );
        }
        let sequence = self.next_sequence();
        let receipt = ReconciliationReceipt {
            reconciliation_id: format!("reconcile_{sequence}"),
            subject,
            owner,
            input_decisions,
            outcome,
            evidence_handles,
            candidate_handles,
            retry_count,
            retry_limit,
            reviewer_evidence_handles,
            verifier_evidence_handles,
            verification_outcome,
            sequence,
        };
        self.reconciliations.push(receipt.clone());
        trim_front(&mut self.reconciliations, COORDINATION_RECORD_LIMIT);
        Ok(receipt)
    }

    pub fn project_relevant_decisions(
        &mut self,
        child_id: &str,
        claim: Option<&WriteScopeClaim>,
        capabilities: &[String],
    ) -> (String, ContextProjectionReceipt) {
        const HEADER: &str = "Accepted coordination decisions relevant to this child (bounded):\n";
        let mut seen_constraint_facts = BTreeSet::new();
        let mut decision_ids = Vec::new();
        let mut lines = Vec::new();
        let mut projected_bytes = 0usize;
        let mut deduplicated = 0usize;
        let mut omitted = 0usize;
        for decision in self
            .decisions
            .iter()
            .rev()
            .filter(|decision| decision.status == DecisionStatus::Accepted)
            .filter(|decision| decision_is_relevant(decision, claim, capabilities))
        {
            if decision_ids.len() >= COORDINATION_PROJECTION_DECISION_LIMIT {
                omitted = omitted.saturating_add(1);
                continue;
            }
            let constraints = decision
                .constraints
                .iter()
                .filter_map(|value| {
                    let value = bounded_utf8(value, 192);
                    if seen_constraint_facts.insert(value.clone()) {
                        Some(value)
                    } else {
                        deduplicated = deduplicated.saturating_add(1);
                        None
                    }
                })
                .take(8)
                .collect::<Vec<_>>()
                .join("; ");
            let mut line = format!(
                "- {} v{} [{}] owner={}",
                decision.subject, decision.version, decision.decision_id, decision.owner,
            );
            if !constraints.is_empty() {
                line.push_str(": ");
                line.push_str(&constraints);
            }
            let line = bounded_utf8(&line, 512);
            let added_bytes = line.len().saturating_add(1);
            if HEADER
                .len()
                .saturating_add(projected_bytes)
                .saturating_add(added_bytes)
                > COORDINATION_PROJECTION_BYTE_LIMIT
            {
                omitted = omitted.saturating_add(1);
                continue;
            }
            projected_bytes = projected_bytes.saturating_add(added_bytes);
            decision_ids.push(decision.decision_id.clone());
            lines.push(line);
        }
        let projection = if lines.is_empty() {
            String::new()
        } else {
            format!("{HEADER}{}", lines.join("\n"))
        };
        let receipt = ContextProjectionReceipt {
            child_id: child_id.to_string(),
            decision_ids,
            projected_bytes: projection.len(),
            deduplicated,
            omitted,
            sequence: self.next_sequence(),
        };
        self.projections.push(receipt.clone());
        trim_front(&mut self.projections, COORDINATION_RECORD_LIMIT);
        (projection, receipt)
    }

    pub(super) fn validate_replay(&mut self) -> Result<(), String> {
        self.validate_schema()?;
        if self.decisions.len() > COORDINATION_RECORD_LIMIT
            || self.write_claims.len() > COORDINATION_RECORD_LIMIT
            || self.reconciliations.len() > COORDINATION_RECORD_LIMIT
            || self.projections.len() > COORDINATION_RECORD_LIMIT
            || self.contentions.len() > COORDINATION_RECORD_LIMIT
        {
            return Err("coordination record count exceeds the durable bound".to_string());
        }

        let mut sequences = BTreeSet::new();
        let mut max_sequence = 0_u64;
        let mut decision_ids = BTreeSet::new();
        let mut accepted_subjects = BTreeSet::new();
        for decision in &self.decisions {
            bounded_coordination_atom("decision id", &decision.decision_id)?;
            bounded_coordination_atom("decision subject", &decision.subject)?;
            bounded_coordination_atom("decision owner", &decision.owner)?;
            if decision.version == 0 {
                return Err(format!(
                    "decision '{}' has zero version",
                    decision.decision_id
                ));
            }
            validate_sequence(
                decision.sequence,
                "decision",
                &mut sequences,
                &mut max_sequence,
            )?;
            if !decision_ids.insert(decision.decision_id.clone()) {
                return Err(format!("duplicate decision id '{}'", decision.decision_id));
            }
            if decision.status == DecisionStatus::Accepted
                && !accepted_subjects.insert(decision.subject.clone())
            {
                return Err(format!(
                    "multiple accepted decisions own subject '{}'",
                    decision.subject
                ));
            }
            validate_normalized_coordination_values("decision scope", &decision.scope, 24)?;
            validate_normalized_coordination_values(
                "decision constraints",
                &decision.constraints,
                24,
            )?;
            validate_normalized_coordination_values(
                "decision evidence handles",
                &decision.evidence_handles,
                24,
            )?;
            reject_sensitive_coordination_values(&decision.constraints)?;
            reject_sensitive_coordination_values(&decision.evidence_handles)?;
        }

        let mut claim_owners = BTreeSet::new();
        for claim in &self.write_claims {
            validate_sequence(
                claim.sequence,
                "write claim",
                &mut sequences,
                &mut max_sequence,
            )?;
            bounded_coordination_atom("write claim owner", &claim.claim.owner)?;
            if !claim_owners.insert(claim.claim.owner.clone()) {
                return Err(format!(
                    "duplicate write claim owner '{}'",
                    claim.claim.owner
                ));
            }
            let roots = normalize_claim_paths(&claim.claim.roots)?;
            let exact_files = normalize_claim_paths(&claim.claim.exact_files)?;
            let contracts = normalize_claim_strings(&claim.claim.contracts, 16, 128, "contracts")?;
            if roots != claim.claim.roots
                || exact_files != claim.claim.exact_files
                || contracts != claim.claim.contracts
                || (roots.is_empty() && exact_files.is_empty() && contracts.is_empty())
            {
                return Err(format!(
                    "write claim for '{}' is not normalized and bounded",
                    claim.claim.owner
                ));
            }
        }

        for receipt in &self.reconciliations {
            validate_sequence(
                receipt.sequence,
                "reconciliation",
                &mut sequences,
                &mut max_sequence,
            )?;
            validate_reconciliation_receipt(receipt, &self.decisions)?;
        }
        for projection in &self.projections {
            validate_sequence(
                projection.sequence,
                "context projection",
                &mut sequences,
                &mut max_sequence,
            )?;
            bounded_coordination_atom("projection child", &projection.child_id)?;
            if projection.decision_ids.len() > COORDINATION_PROJECTION_DECISION_LIMIT
                || projection.projected_bytes > COORDINATION_PROJECTION_BYTE_LIMIT
                || projection
                    .decision_ids
                    .iter()
                    .collect::<BTreeSet<_>>()
                    .len()
                    != projection.decision_ids.len()
            {
                return Err(format!(
                    "context projection for '{}' exceeds its bounds or duplicates decisions",
                    projection.child_id
                ));
            }
        }
        for contention in &self.contentions {
            validate_sequence(
                contention.sequence,
                "contention",
                &mut sequences,
                &mut max_sequence,
            )?;
            bounded_coordination_atom("contention claimant", &contention.claimant)?;
            bounded_coordination_atom(
                "contention conflicting owner",
                &contention.conflicting_owner,
            )?;
            match (contention.disposition, contention.resolution_sequence) {
                (WriteContentionDisposition::BlockedPendingIsolationOrSerialization, None) => {}
                (WriteContentionDisposition::ResolvedBySuccessfulClaim, Some(sequence))
                    if sequence > contention.sequence && sequence <= self.sequence => {}
                (WriteContentionDisposition::BlockedPendingIsolationOrSerialization, Some(_)) => {
                    return Err(
                        "blocked contention receipt cannot carry a resolution sequence".to_string(),
                    );
                }
                (WriteContentionDisposition::ResolvedBySuccessfulClaim, _) => {
                    return Err(
                        "resolved contention receipt requires a later valid resolution sequence"
                            .to_string(),
                    );
                }
            }
            if normalize_claim_paths(&contention.roots)? != contention.roots
                || normalize_claim_paths(&contention.exact_files)? != contention.exact_files
                || normalize_claim_strings(&contention.contracts, 16, 128, "contracts")?
                    != contention.contracts
            {
                return Err("contention receipt paths/contracts are not normalized".to_string());
            }
        }
        if self.sequence < max_sequence {
            return Err(format!(
                "coordination sequence {} is behind record sequence {max_sequence}",
                self.sequence
            ));
        }
        Ok(())
    }

    fn validate_schema(&self) -> Result<(), String> {
        if self.schema_version != COORDINATION_SCHEMA_VERSION {
            return Err(format!(
                "unsupported coordination schema {}; expected {}",
                self.schema_version, COORDINATION_SCHEMA_VERSION
            ));
        }
        Ok(())
    }
}

fn normalize_claim_paths(paths: &[String]) -> Result<Vec<String>, String> {
    if paths.len() > 32 {
        return Err("write claim paths accept at most 32 entries".to_string());
    }
    let mut normalized = Vec::new();
    for path in paths {
        let path = super::normalize_claim_path(path)?;
        if !normalized.contains(&path) {
            normalized.push(path);
        }
    }
    Ok(normalized)
}

fn normalize_claim_strings(
    values: &[String],
    count_limit: usize,
    char_limit: usize,
    field: &str,
) -> Result<Vec<String>, String> {
    if values.len() > count_limit {
        return Err(format!(
            "write claim {field} accepts at most {count_limit} entries"
        ));
    }
    let mut normalized = Vec::new();
    for value in values {
        let value = value.trim();
        if value.is_empty()
            || value.chars().count() > char_limit
            || value.chars().any(char::is_control)
        {
            return Err(format!(
                "write claim {field} entries must be 1..={char_limit} characters"
            ));
        }
        if !normalized.iter().any(|existing| existing == value) {
            normalized.push(value.to_string());
        }
    }
    Ok(normalized)
}

fn bounded_coordination_atom(field: &str, value: &str) -> Result<String, String> {
    let value = value.trim();
    if value.is_empty()
        || value.chars().count() > 512
        || value.chars().any(|ch| matches!(ch, '\r' | '\n'))
    {
        return Err(format!(
            "{field} must be one non-empty line of at most 512 characters"
        ));
    }
    Ok(value.to_string())
}

fn normalize_coordination_values(
    field: &str,
    values: &[String],
    limit: usize,
) -> Result<Vec<String>, String> {
    if values.len() > limit {
        return Err(format!("{field} accepts at most {limit} entries"));
    }
    let mut normalized = Vec::new();
    for value in values {
        let value = bounded_coordination_atom(field, value)?;
        if !normalized.contains(&value) {
            normalized.push(value);
        }
    }
    Ok(normalized)
}

fn validate_normalized_coordination_values(
    field: &str,
    values: &[String],
    limit: usize,
) -> Result<(), String> {
    if normalize_coordination_values(field, values, limit)? != values {
        return Err(format!("{field} is not trimmed and deduplicated"));
    }
    Ok(())
}

fn reject_sensitive_coordination_values(values: &[String]) -> Result<(), String> {
    const SENSITIVE_MARKERS: &[&str] = &[
        "secret",
        "password",
        "api_key",
        "api-key",
        "authorization:",
        "bearer ",
        "token=",
        "sk-",
        "ghp_",
        "xoxb-",
        "<thinking",
        "chain of thought",
        "raw reasoning",
    ];
    for value in values {
        let lower = value.to_ascii_lowercase();
        if let Some(marker) = SENSITIVE_MARKERS
            .iter()
            .find(|marker| lower.contains(**marker))
        {
            return Err(format!(
                "coordination metadata rejected sensitive or raw-reasoning marker '{marker}'"
            ));
        }
    }
    Ok(())
}

fn validate_sequence(
    sequence: u64,
    kind: &str,
    sequences: &mut BTreeSet<u64>,
    max_sequence: &mut u64,
) -> Result<(), String> {
    if sequence == 0 || !sequences.insert(sequence) {
        return Err(format!(
            "{kind} has a zero or duplicate sequence {sequence}"
        ));
    }
    *max_sequence = (*max_sequence).max(sequence);
    Ok(())
}

fn validate_reconciliation_receipt(
    receipt: &ReconciliationReceipt,
    decisions: &[DecisionRecord],
) -> Result<(), String> {
    bounded_coordination_atom("reconciliation id", &receipt.reconciliation_id)?;
    bounded_coordination_atom("reconciliation subject", &receipt.subject)?;
    bounded_coordination_atom("reconciliation owner", &receipt.owner)?;
    bounded_coordination_atom("reconciliation outcome", &receipt.outcome)?;
    if receipt.input_decisions.len() < 2
        || receipt
            .input_decisions
            .iter()
            .collect::<BTreeSet<_>>()
            .len()
            != receipt.input_decisions.len()
    {
        return Err("reconciliation requires at least two distinct decision ids".to_string());
    }
    let inputs = receipt
        .input_decisions
        .iter()
        .map(|id| {
            decisions
                .iter()
                .find(|decision| &decision.decision_id == id)
                .ok_or_else(|| format!("reconciliation references unknown decision '{id}'"))
        })
        .collect::<Result<Vec<_>, _>>()?;
    if inputs
        .iter()
        .any(|decision| decision.subject != receipt.subject)
    {
        return Err("reconciliation inputs must share the requested subject".to_string());
    }
    if inputs
        .iter()
        .any(|decision| decision.owner == receipt.owner)
    {
        return Err("neutral fan-in owner must differ from every candidate owner".to_string());
    }
    if receipt.candidate_handles.len() < 2
        || receipt
            .candidate_handles
            .iter()
            .collect::<BTreeSet<_>>()
            .len()
            != receipt.candidate_handles.len()
    {
        return Err("reconciliation requires at least two distinct candidate handles".to_string());
    }
    validate_normalized_coordination_values("candidate handles", &receipt.candidate_handles, 24)?;
    validate_normalized_coordination_values(
        "reconciliation evidence handles",
        &receipt.evidence_handles,
        24,
    )?;
    validate_normalized_coordination_values(
        "Reviewer evidence handles",
        &receipt.reviewer_evidence_handles,
        24,
    )?;
    validate_normalized_coordination_values(
        "Verifier evidence handles",
        &receipt.verifier_evidence_handles,
        24,
    )?;
    reject_sensitive_coordination_values(&receipt.candidate_handles)?;
    reject_sensitive_coordination_values(&receipt.evidence_handles)?;
    reject_sensitive_coordination_values(&receipt.reviewer_evidence_handles)?;
    reject_sensitive_coordination_values(&receipt.verifier_evidence_handles)?;
    if receipt.retry_limit == 0
        || receipt.retry_limit > MAX_RECONCILIATION_RETRIES
        || receipt.retry_count > receipt.retry_limit
    {
        return Err("reconciliation retry count/limit is invalid".to_string());
    }
    if receipt.reviewer_evidence_handles.is_empty()
        || receipt.verifier_evidence_handles.is_empty()
        || receipt.reviewer_evidence_handles.iter().any(|review| {
            receipt
                .verifier_evidence_handles
                .iter()
                .any(|verify| verify == review)
        })
    {
        return Err("Reviewer and Verifier evidence must be present and independent".to_string());
    }
    if !matches!(
        receipt.verification_outcome.as_str(),
        "verified" | "failed" | "blocked"
    ) {
        return Err("reconciliation verification outcome is invalid".to_string());
    }
    Ok(())
}

fn decision_is_relevant(
    decision: &DecisionRecord,
    claim: Option<&WriteScopeClaim>,
    capabilities: &[String],
) -> bool {
    if decision.scope.is_empty() {
        return true;
    }
    decision.scope.iter().any(|raw| {
        let value = raw.trim();
        let (kind, value) = value
            .split_once(':')
            .map_or(("", value), |(kind, value)| (kind.trim(), value.trim()));
        match kind {
            "capability" => capabilities.iter().any(|capability| capability == value),
            "contract" => {
                claim.is_some_and(|claim| claim.contracts.iter().any(|contract| contract == value))
            }
            "path" => claim.is_some_and(|claim| claim_reaches_path(claim, value)),
            _ => {
                capabilities.iter().any(|capability| capability == value)
                    || claim.is_some_and(|claim| {
                        claim.contracts.iter().any(|contract| contract == value)
                            || claim_reaches_path(claim, value)
                    })
            }
        }
    })
}

fn claim_reaches_path(claim: &WriteScopeClaim, path: &str) -> bool {
    let Ok(path) = super::normalize_claim_path(path) else {
        return false;
    };
    claim.contains_path(&path)
        || claim.roots.iter().any(|root| path_contains(&path, root))
        || claim
            .exact_files
            .iter()
            .any(|file| path_contains(&path, file))
}

fn bounded_utf8(value: &str, byte_limit: usize) -> String {
    if value.len() <= byte_limit {
        return value.to_string();
    }
    let mut end = byte_limit;
    while !value.is_char_boundary(end) {
        end = end.saturating_sub(1);
    }
    value[..end].to_string()
}

fn trim_front<T>(records: &mut Vec<T>, limit: usize) {
    if records.len() > limit {
        records.drain(..records.len() - limit);
    }
}

pub struct AgentsCoordinateTool {
    manager: SharedSubAgentManager,
    caller: Option<String>,
}

impl AgentsCoordinateTool {
    #[must_use]
    pub fn new(manager: SharedSubAgentManager, caller: Option<String>) -> Self {
        Self { manager, caller }
    }
}

#[async_trait]
impl ToolSpec for AgentsCoordinateTool {
    fn name(&self) -> &'static str {
        "agents/coordinate"
    }

    fn description(&self) -> &'static str {
        "Record or inspect bounded coordination state: propose/accept/supersede decisions, expand the caller's write claim before mutation, or reconcile multiple decision records into one neutral fan-in receipt."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "action": { "type": "string", "enum": ["inspect", "propose", "accept", "supersede", "claim", "reconcile"] },
                "decision_id": { "type": "string" },
                "subject": { "type": "string" },
                "expected_version": { "type": "integer", "minimum": 1 },
                "scope": { "type": "array", "items": { "type": "string" } },
                "constraints": { "type": "array", "items": { "type": "string" } },
                "evidence_handles": { "type": "array", "items": { "type": "string" } },
                "roots": { "type": "array", "items": { "type": "string" } },
                "exact_files": { "type": "array", "items": { "type": "string" } },
                "contracts": { "type": "array", "items": { "type": "string" } },
                "input_decisions": { "type": "array", "items": { "type": "string" } },
                "outcome": { "type": "string" },
                "candidate_handles": { "type": "array", "items": { "type": "string" } },
                "retry_count": { "type": "integer", "minimum": 0, "maximum": 3 },
                "retry_limit": { "type": "integer", "minimum": 1, "maximum": 3 },
                "reviewer_evidence_handles": { "type": "array", "items": { "type": "string" } },
                "verifier_evidence_handles": { "type": "array", "items": { "type": "string" } },
                "verification_outcome": { "type": "string" },
                "limit": { "type": "integer", "minimum": 1, "maximum": 24 }
            },
            "required": ["action"]
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        // #5123-class: this tool mutates the coordination ledger and expands
        // the caller's write claim (actions propose/accept/supersede/claim/
        // reconcile) — declaring ReadOnly was a lie that let policy layers
        // treat a mutating call as a safe read. Only `inspect` is read-only,
        // which is what is_read_only_for reports.
        vec![ToolCapability::WritesFiles]
    }
    fn approval_requirement(&self) -> ApprovalRequirement {
        // Stays Auto: coordination records are session-scoped in-memory
        // state, and gating them would deadlock autonomous sub-agent fan-in.
        ApprovalRequirement::Auto
    }
    fn is_read_only_for(&self, input: &Value) -> bool {
        input.get("action").and_then(Value::as_str) == Some("inspect")
    }

    async fn execute(&self, input: Value, _context: &ToolContext) -> Result<ToolResult, ToolError> {
        let action = input
            .get("action")
            .and_then(Value::as_str)
            .unwrap_or("inspect");
        let bounded_text = |key: &str| {
            input
                .get(key)
                .and_then(Value::as_str)
                .map(|value| value.chars().take(512).collect::<String>())
        };
        // Tool authority is the runtime caller identity. Root cannot supply an
        // arbitrary child owner and mutate that child's decisions/claim.
        let owner = self.caller.clone().unwrap_or_else(|| "root".to_string());
        let strings = |key: &str| {
            input
                .get(key)
                .and_then(Value::as_array)
                .map(|items| {
                    items
                        .iter()
                        .take(24)
                        .filter_map(Value::as_str)
                        .map(|value| value.chars().take(512).collect::<String>())
                        .collect::<Vec<_>>()
                })
                .unwrap_or_default()
        };
        if action == "inspect" {
            let manager = self.manager.read().await;
            let value = manager.inspect_coordination(
                bounded_text("subject").as_deref(),
                input
                    .get("limit")
                    .and_then(Value::as_u64)
                    .unwrap_or(COORDINATION_INSPECT_LIMIT as u64) as usize,
            );
            return ToolResult::json(&value)
                .map_err(|e| ToolError::execution_failed(e.to_string()));
        }
        if !matches!(
            action,
            "propose" | "accept" | "supersede" | "claim" | "reconcile"
        ) {
            return Err(ToolError::invalid_input(format!(
                "unknown coordination action '{action}'"
            )));
        }

        let mut manager = self.manager.write().await;
        let coordination_before = manager.coordination.clone();
        let mutation = match action {
            "propose" => manager
                .record_coordination_decision(DecisionRecord {
                    decision_id: bounded_text("decision_id").unwrap_or_default(),
                    subject: bounded_text("subject").unwrap_or_default(),
                    status: DecisionStatus::Proposed,
                    owner,
                    scope: strings("scope"),
                    constraints: strings("constraints"),
                    evidence_handles: strings("evidence_handles"),
                    version: 1,
                    sequence: 0,
                })
                .map_err(ToolError::invalid_input)
                .and_then(|record| {
                    serde_json::to_value(record)
                        .map_err(|e| ToolError::execution_failed(e.to_string()))
                }),
            "accept" | "supersede" => input
                .get("expected_version")
                .and_then(Value::as_u64)
                .and_then(|value| u32::try_from(value).ok())
                .ok_or_else(|| {
                    ToolError::invalid_input(
                        "accept/supersede requires expected_version".to_string(),
                    )
                })
                .and_then(|expected_version| {
                    manager
                        .update_coordination_decision(
                            &bounded_text("decision_id").unwrap_or_default(),
                            if action == "accept" {
                                DecisionStatus::Accepted
                            } else {
                                DecisionStatus::Superseded
                            },
                            &owner,
                            expected_version,
                        )
                        .map_err(ToolError::invalid_input)
                })
                .and_then(|record| {
                    serde_json::to_value(record)
                        .map_err(|e| ToolError::execution_failed(e.to_string()))
                }),
            "claim" => manager
                .expand_write_claim(
                    &owner,
                    strings("roots"),
                    strings("exact_files"),
                    strings("contracts"),
                )
                .map_err(ToolError::invalid_input)
                .and_then(|claim| {
                    serde_json::to_value(claim)
                        .map_err(|e| ToolError::execution_failed(e.to_string()))
                }),
            "reconcile" => manager
                .reconcile_coordination(
                    bounded_text("subject").unwrap_or_default(),
                    owner,
                    strings("input_decisions"),
                    bounded_text("outcome").unwrap_or_default(),
                    strings("evidence_handles"),
                    strings("candidate_handles"),
                    input
                        .get("retry_count")
                        .and_then(Value::as_u64)
                        .and_then(|value| u32::try_from(value).ok())
                        .unwrap_or_default(),
                    input
                        .get("retry_limit")
                        .and_then(Value::as_u64)
                        .and_then(|value| u32::try_from(value).ok())
                        .unwrap_or(MAX_RECONCILIATION_RETRIES),
                    strings("reviewer_evidence_handles"),
                    strings("verifier_evidence_handles"),
                    bounded_text("verification_outcome").unwrap_or_default(),
                )
                .map_err(ToolError::invalid_input)
                .and_then(|receipt| {
                    serde_json::to_value(receipt)
                        .map_err(|e| ToolError::execution_failed(e.to_string()))
                }),
            _ => unreachable!("coordination action validated above"),
        };
        if let Err(error) = manager.persist_state_synchronously() {
            manager.coordination = coordination_before;
            return Err(ToolError::execution_failed(format!(
                "failed to persist coordination action '{action}': {error}"
            )));
        }
        let value = mutation?;
        ToolResult::json(&value).map_err(|e| ToolError::execution_failed(e.to_string()))
    }
}

#[cfg(test)]
mod records_tests {
    use super::*;

    #[test]
    fn overlapping_roots_detected() {
        let a = WriteScopeClaim {
            owner: "agent-a".into(),
            roots: vec!["src/tui/".into()],
            exact_files: vec![],
            contracts: vec![],
        };
        let b = WriteScopeClaim {
            owner: "agent-b".into(),
            roots: vec!["src/tui/widgets/".into()],
            exact_files: vec![],
            contracts: vec![],
        };
        assert!(a.overlaps(&b));
    }

    #[test]
    fn disjoint_roots_no_overlap() {
        let a = WriteScopeClaim {
            owner: "agent-a".into(),
            roots: vec!["src/tui/".into()],
            exact_files: vec![],
            contracts: vec![],
        };
        let b = WriteScopeClaim {
            owner: "agent-b".into(),
            roots: vec!["src/core/".into()],
            exact_files: vec![],
            contracts: vec![],
        };
        assert!(!a.overlaps(&b));
    }

    #[test]
    fn exact_file_collision_detected() {
        let a = WriteScopeClaim {
            owner: "agent-a".into(),
            roots: vec![],
            exact_files: vec!["src/main.rs".into()],
            contracts: vec![],
        };
        let b = WriteScopeClaim {
            owner: "agent-b".into(),
            roots: vec![],
            exact_files: vec!["src/main.rs".into()],
            contracts: vec![],
        };
        assert!(a.overlaps(&b));
    }

    #[test]
    fn path_overlap_respects_component_boundaries_and_root_coverage() {
        let root = WriteScopeClaim {
            owner: "agent-a".into(),
            roots: vec!["src".into()],
            exact_files: vec![],
            contracts: vec![],
        };
        let sibling = WriteScopeClaim {
            owner: "agent-b".into(),
            roots: vec!["src2".into()],
            exact_files: vec![],
            contracts: vec![],
        };
        let child_file = WriteScopeClaim {
            owner: "agent-c".into(),
            roots: vec![],
            exact_files: vec!["src/lib.rs".into()],
            contracts: vec![],
        };
        assert!(!root.overlaps(&sibling));
        assert!(root.overlaps(&child_file));
    }

    #[test]
    fn legacy_blocked_contention_wire_defaults_to_unresolved() {
        let receipt: WriteContentionReceipt = serde_json::from_value(json!({
            "claimant": "agent-b",
            "conflicting_owner": "agent-a",
            "roots": ["src"],
            "exact_files": [],
            "contracts": ["public-api"],
            "disposition": "blocked_pending_isolation_or_serialization",
            "sequence": 3
        }))
        .expect("existing blocked wire receipt remains readable");

        assert_eq!(
            receipt.disposition,
            WriteContentionDisposition::BlockedPendingIsolationOrSerialization
        );
        assert_eq!(receipt.resolution_sequence, None);
        assert!(receipt.disposition.blocks_admission());
    }

    #[test]
    fn active_shared_claims_contend_but_isolated_claims_do_not() {
        let mut ledger = CoordinationLedger::default();
        let first = WriteScopeClaim {
            owner: "agent-a".into(),
            roots: vec!["src".into()],
            exact_files: vec![],
            contracts: vec!["public-api".into()],
        };
        ledger.register_claim(first, false, |_| false).unwrap();
        let second = WriteScopeClaim {
            owner: "agent-b".into(),
            roots: vec!["docs".into()],
            exact_files: vec![],
            contracts: vec!["public-api".into()],
        };
        let err = ledger
            .register_claim(second.clone(), false, |owner| owner == "agent-a")
            .unwrap_err();
        assert!(
            err.contains("contention") && err.contains("agent-a"),
            "{err}"
        );
        assert_eq!(ledger.contentions.len(), 1);
        assert_eq!(ledger.contentions[0].claimant, "agent-b");
        assert_eq!(ledger.contentions[0].conflicting_owner, "agent-a");
        assert_eq!(
            ledger.contentions[0].disposition,
            WriteContentionDisposition::BlockedPendingIsolationOrSerialization
        );
        assert_eq!(
            serde_json::to_value(&ledger.contentions[0]).unwrap()["disposition"],
            json!("blocked_pending_isolation_or_serialization")
        );
        let resolving_claim = ledger
            .register_claim(second, true, |owner| owner == "agent-a")
            .expect("isolated claim resolves the blocked admission");
        assert_eq!(
            ledger.contentions[0].disposition,
            WriteContentionDisposition::ResolvedBySuccessfulClaim
        );
        assert_eq!(
            ledger.contentions[0].resolution_sequence,
            Some(resolving_claim.sequence)
        );
    }

    #[test]
    fn active_write_claims_are_never_evicted_by_receipt_retention() {
        let mut ledger = CoordinationLedger::default();
        for index in 0..COORDINATION_RECORD_LIMIT {
            ledger
                .register_claim(
                    WriteScopeClaim {
                        owner: format!("agent-{index:03}"),
                        roots: vec![format!("pkg-{index:03}")],
                        exact_files: vec![],
                        contracts: vec![],
                    },
                    false,
                    |_| true,
                )
                .unwrap();
        }
        let error = ledger
            .register_claim(
                WriteScopeClaim {
                    owner: "agent-over-cap".into(),
                    roots: vec!["new-package".into()],
                    exact_files: vec![],
                    contracts: vec![],
                },
                false,
                |_| true,
            )
            .expect_err("all-active capacity must fail before evicting ownership");
        assert!(error.contains("active owners"), "{error}");
        assert_eq!(ledger.write_claims.len(), COORDINATION_RECORD_LIMIT);
        assert!(
            ledger
                .write_claims
                .iter()
                .any(|record| record.claim.owner == "agent-000")
        );
    }

    #[test]
    fn accepted_decisions_require_owner_and_explicit_neutral_reconciliation() {
        let mut ledger = CoordinationLedger::default();
        let make = |id: &str, owner: &str, status| DecisionRecord {
            decision_id: id.into(),
            subject: "storage".into(),
            status,
            owner: owner.into(),
            scope: vec!["router".into()],
            constraints: vec![],
            evidence_handles: vec![format!("receipt:{id}")],
            version: 1,
            sequence: 0,
        };
        ledger
            .record_decision(make("a", "agent-a", DecisionStatus::Accepted))
            .unwrap();
        ledger
            .record_decision(make("b", "agent-b", DecisionStatus::Proposed))
            .unwrap();
        let owner_error = ledger
            .update_decision_status("b", DecisionStatus::Accepted, "root", 2)
            .unwrap_err();
        assert!(owner_error.contains("owned by 'agent-b'"), "{owner_error}");
        let stale = ledger
            .update_decision_status("b", DecisionStatus::Accepted, "agent-b", 1)
            .unwrap_err();
        assert!(stale.contains("expected 1, current 2"), "{stale}");
        let conflict = ledger
            .update_decision_status("b", DecisionStatus::Accepted, "agent-b", 2)
            .unwrap_err();
        assert!(conflict.contains("neutral reconciliation"), "{conflict}");
        ledger
            .update_decision_status("a", DecisionStatus::Superseded, "agent-a", 1)
            .unwrap();
        ledger
            .update_decision_status("b", DecisionStatus::Accepted, "agent-b", 2)
            .unwrap();
        let receipt = ledger
            .reconcile(
                "storage".into(),
                "root".into(),
                vec!["a".into(), "b".into()],
                "use bounded origin-session artifacts".into(),
                vec!["test:coord".into()],
                vec!["branch:agent-a".into(), "branch:agent-b".into()],
                1,
                3,
                vec!["review:independent".into()],
                vec!["verify:locked".into()],
                "verified".into(),
            )
            .unwrap();
        assert_eq!(receipt.input_decisions.len(), 2);
        assert!(receipt.sequence > ledger.decisions[1].sequence);
    }

    #[test]
    fn relevant_decision_projection_is_deduplicated_bounded_and_receipted() {
        let mut ledger = CoordinationLedger::default();
        for (id, subject, scope) in [
            ("file", "file-contract", "path:src"),
            ("docs", "docs-contract", "path:docs"),
            ("api", "api-contract", "contract:public-api"),
        ] {
            ledger
                .record_decision(DecisionRecord {
                    decision_id: id.into(),
                    subject: subject.into(),
                    status: DecisionStatus::Accepted,
                    owner: "planner".into(),
                    scope: vec![scope.into()],
                    constraints: vec!["bounded".into(), "bounded".into()],
                    evidence_handles: vec![format!("receipt:{id}")],
                    version: 1,
                    sequence: 0,
                })
                .unwrap();
        }
        let claim = WriteScopeClaim {
            owner: "worker".into(),
            roots: vec!["src/tui".into()],
            exact_files: vec![],
            contracts: vec!["public-api".into()],
        };
        let (projection, receipt) =
            ledger.project_relevant_decisions("worker", Some(&claim), &["File".into()]);
        assert!(projection.contains("file-contract"), "{projection}");
        assert!(projection.contains("api-contract"), "{projection}");
        assert!(!projection.contains("docs-contract"), "{projection}");
        assert!(projection.len() <= COORDINATION_PROJECTION_BYTE_LIMIT);
        assert_eq!(receipt.decision_ids, vec!["api", "file"]);
        assert_eq!(receipt.deduplicated, 1);
        assert_eq!(ledger.projections.last(), Some(&receipt));
    }

    #[test]
    fn projection_receipt_distinguishes_unique_omissions_from_deduplication() {
        let mut ledger = CoordinationLedger::default();
        for index in 0..(COORDINATION_PROJECTION_DECISION_LIMIT + 2) {
            ledger
                .record_decision(DecisionRecord {
                    decision_id: format!("decision-{index}"),
                    subject: format!("subject-{index}"),
                    status: DecisionStatus::Accepted,
                    owner: "planner".into(),
                    scope: vec!["path:src".into()],
                    constraints: vec![format!("constraint-{index}")],
                    evidence_handles: vec![format!("receipt:{index}")],
                    version: 1,
                    sequence: 0,
                })
                .unwrap();
        }
        let claim = WriteScopeClaim {
            owner: "worker".into(),
            roots: vec!["src".into()],
            exact_files: vec![],
            contracts: vec![],
        };

        let (projection, receipt) = ledger.project_relevant_decisions("worker", Some(&claim), &[]);

        assert!(projection.len() <= COORDINATION_PROJECTION_BYTE_LIMIT);
        assert_eq!(
            receipt.decision_ids.len(),
            COORDINATION_PROJECTION_DECISION_LIMIT
        );
        assert_eq!(receipt.deduplicated, 0);
        assert_eq!(receipt.omitted, 2);
    }

    #[test]
    fn coordination_schema_drift_fails_closed_before_mutation() {
        let mut ledger = CoordinationLedger {
            schema_version: COORDINATION_SCHEMA_VERSION + 1,
            ..CoordinationLedger::default()
        };
        let error = ledger
            .register_claim(
                WriteScopeClaim {
                    owner: "worker".into(),
                    roots: vec!["src".into()],
                    exact_files: vec![],
                    contracts: vec![],
                },
                false,
                |_| false,
            )
            .unwrap_err();
        assert!(error.contains("unsupported coordination schema"), "{error}");
        assert!(ledger.write_claims.is_empty());
    }
}