batty-cli 0.11.63

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

use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::Path;
use std::time::Instant;

use anyhow::Result;
use regex::Regex;
use tracing::{debug, info, warn};

use super::super::super::policy::check_wip_limit;
use super::super::super::task_loop::engineer_worktree_ready_for_dispatch_from_trunk;
use super::super::task_cmd::{
    StatusTransitionAttribution, append_task_dependencies, assign_task_owners,
    transition_task_with_attribution,
};
use super::super::*;
use crate::team::allocation::{
    EngineerProfile, load_engineer_profiles, predict_task_file_paths, rank_engineers_for_task,
};
use crate::team::config::AllocationStrategy;
use serde::Deserialize;

/// #696: partition `blocking_task_ids` into (safe, rejected) by walking
/// the on-disk `depends_on` graph. An edge `candidate -> blocking` is
/// unsafe when `blocking` already depends on `candidate` (directly or
/// transitively), because persisting it would close a cycle. Returns
/// the edges that can be safely appended and the rejected ones for
/// logging.
fn split_acyclic_blocking_ids(
    board_dir: &Path,
    candidate_id: u32,
    blocking_task_ids: &[u32],
) -> Result<(Vec<u32>, Vec<u32>)> {
    let tasks = crate::task::load_tasks_from_dir(&board_dir.join("tasks"))?;
    let deps_by_id: HashMap<u32, Vec<u32>> = tasks
        .iter()
        .map(|task| (task.id, task.depends_on.clone()))
        .collect();

    let reaches_candidate = |start: u32| -> bool {
        if start == candidate_id {
            return true;
        }
        let mut visited: HashSet<u32> = HashSet::new();
        let mut stack: Vec<u32> = vec![start];
        while let Some(node) = stack.pop() {
            if !visited.insert(node) {
                continue;
            }
            let Some(neighbors) = deps_by_id.get(&node) else {
                continue;
            };
            for next in neighbors {
                if *next == candidate_id {
                    return true;
                }
                if !visited.contains(next) {
                    stack.push(*next);
                }
            }
        }
        false
    };

    let mut safe = Vec::new();
    let mut rejected = Vec::new();
    for id in blocking_task_ids {
        if reaches_candidate(*id) {
            rejected.push(*id);
        } else {
            safe.push(*id);
        }
    }
    Ok((safe, rejected))
}

/// Tokens that are hyphen-lowercase-shaped but are NOT engineer roles —
/// architects use them as descriptive tags inside routing preambles.
/// Guard so `first_role_token_after` doesn't mis-extract them as the owner.
const NON_ROLE_HYPHEN_TOKENS: &[&str] = &[
    "role-flexible",
    "strategic-analysis",
    "narrative-audit",
    "north-star",
    "any-engineer",
];

/// Seed tags derived from an engineer's `role_name` for `domain_tags`.
///
/// #708: #691 seeded the full `role_name` (`sam-designer`) but tasks
/// tagged with natural-language tokens (`design`, `writing`) scored
/// zero tag-overlap and fell through to alphabetical tiebreaker —
/// observed 2026-04-17 12:27:30 UTC, task #572 tagged `design` was
/// dispatched to alex-dev-1-1 instead of sam-designer-1-1. Fix: also
/// seed the hyphen-suffix token (`designer`) and common word-family
/// variants derived from `-er` noun-agent stemming (`design`,
/// `designing`). Short stems (<3 chars) skipped to avoid noise.
fn role_name_seed_tags(role_name: &str) -> Vec<String> {
    let mut seeds = vec![role_name.to_string()];
    let Some(suffix) = role_name.rsplit('-').next() else {
        return seeds;
    };
    if suffix == role_name || suffix.is_empty() {
        return seeds;
    }
    seeds.push(suffix.to_string());
    if let Some(stem) = suffix.strip_suffix("er")
        && stem.len() >= 3
    {
        seeds.push(stem.to_string());
        seeds.push(format!("{stem}ing"));
    }
    seeds
}

/// Scan `text` for the first contiguous run of ASCII lowercase letters
/// and `-` that contains a hyphen and is not on `NON_ROLE_HYPHEN_TOKENS`.
fn first_role_token_after(text: &str) -> Option<String> {
    let bytes = text.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        while i < bytes.len() && !bytes[i].is_ascii_lowercase() {
            i += 1;
        }
        if i >= bytes.len() {
            break;
        }
        let start = i;
        while i < bytes.len() && (bytes[i].is_ascii_lowercase() || bytes[i] == b'-') {
            i += 1;
        }
        // Trim trailing hyphens so tokens like `alex-dev-` (from the
        // `alex-dev-1-1` instance-id shape) normalise to `alex-dev` instead
        // of being rejected outright.
        let token = text[start..i].trim_end_matches('-');
        if token.contains('-')
            && !token.starts_with('-')
            && !NON_ROLE_HYPHEN_TOKENS.contains(&token)
        {
            return Some(token.to_string());
        }
    }
    None
}

/// Parse an explicit routing-cue declaration from a task body, returning
/// the first role-name-looking token (lowercase letters + hyphens) that
/// follows the cue.
///
/// Recognised cues, ordered most-specific first:
///
/// - `Owner:` / `OWNER:` — canonical declaration (#695/#699)
/// - `Route:` — imperative routing line (`- Route: dispatch to priya-writer.`)
/// - `Primary:` — inside an `Owner routing` preamble
///   (`Primary: priya-writer (narrative audit lens)`)
/// - `Owner routing` — multi-phrase preamble without a direct colon-role
///   pair; falls through to "first hyphen-role token in rest of line"
/// - `route to` / `dispatch to` / `assign to` — inline prose imperatives
///
/// #695: architects routinely author tasks whose frontmatter `tags:` are
/// thematic (e.g. `[content, pillar-b, x, writing]`) but whose body prose
/// names the actual owner role. Without a route-seed from this prose,
/// `tag_overlap` scores 0 for every engineer and the task lands on whichever
/// engineer wins scoring tiebreakers — observed: task #553
/// ("Owner: priya-writer drafts") dispatched to sam-designer-1-1.
///
/// #699: Maya-style round headers wrap the owner declaration inside a
/// prose preamble, e.g. `**Round-8 task from maya-lead. Owner: alex-dev.
/// Skeptic-defuser …**`. The line doesn't START with `Owner:` after
/// markdown trimming, so the earlier line-prefix parser missed these and
/// the tasks got round-robined to the wrong role.
///
/// #700: jordan-pm-authored tasks use richer routing syntax — "Owner
/// routing: ...", "Route: dispatch to <role>", "Primary: <role>" — none of
/// which surface `Owner:` as a literal substring with a role right after.
/// Observed 2026-04-17 09:13:35 UTC: four-task wave where #547
/// ("Owner routing: route to priya-writer") went to alex-dev, #548
/// ("Primary: priya-writer … NOT Sam") went to sam-designer (explicitly
/// excluded), #549 ("Route: dispatch to priya-writer") went to kai-devrel.
/// jordan-pm then spent a full turn reassigning each via inbox —
/// workaround but expensive. Expanded cue list catches these three
/// patterns plus the generic inline-prose forms.
///
/// Word-boundary guard: the cue must be preceded by start-of-line, ASCII
/// whitespace, or one of `- * _ ( [ . ; : ,` so longer compounds like
/// `CoOwner:` / `DataOwner:` / `rerouter:` can't masquerade as cues.
///
/// The returned role-name is merged into the task's tag set for the
/// duration of one ranking call (see `rank_dispatch_engineers`), which
/// triggers the #692 tag-match bypass so the matching engineer wins.
pub(crate) fn parse_body_owner_role(body: &str) -> Option<String> {
    const ROUTING_CUES: &[&str] = &[
        "Owner:",
        "OWNER:",
        "Route:",
        "Primary:",
        "Owner routing",
        "route to",
        "dispatch to",
        "assign to",
    ];
    for line in body.lines() {
        for cue in ROUTING_CUES {
            let mut search_from = 0;
            while let Some(rel_idx) = line[search_from..].find(cue) {
                let idx = search_from + rel_idx;
                search_from = idx + cue.len();
                let boundary_ok = idx == 0
                    || line[..idx]
                        .chars()
                        .next_back()
                        .map(|c| {
                            c.is_whitespace()
                                || matches!(c, '-' | '*' | '_' | '(' | '[' | '.' | ';' | ':' | ',')
                        })
                        .unwrap_or(true);
                if !boundary_ok {
                    continue;
                }
                if let Some(role) = first_role_token_after(&line[search_from..]) {
                    return Some(role);
                }
            }
        }
    }
    None
}

/// Parse task IDs from "Blocked on:" or "Depends on:" lines in the task body.
/// Returns None if no dependency line is found. Returns Some(vec) when a
/// dependency line is present, with an empty vec for non-task-id blockers.
pub(crate) fn parse_body_dependency_ids(body: &str) -> Option<Vec<u32>> {
    for line in body.lines() {
        if let Some(trimmed) = body_dependency_reference(line) {
            let ids: Vec<u32> = trimmed
                .split('#')
                .skip(1)
                .filter_map(|s| {
                    s.chars()
                        .take_while(|c| c.is_ascii_digit())
                        .collect::<String>()
                        .parse()
                        .ok()
                })
                .collect();
            return Some(ids);
        }
    }
    None
}

fn body_dependency_reference(line: &str) -> Option<&str> {
    let trimmed = line.trim().trim_start_matches('-').trim();
    let lower = trimmed.to_ascii_lowercase();
    if lower.starts_with("blocked on:") || lower.starts_with("depends on:") {
        Some(trimmed)
    } else {
        None
    }
}
use super::{DISPATCH_QUEUE_FAILURE_LIMIT, DispatchQueueEntry, dispatch_priority_rank};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OverlapConflict {
    pub task_id: String,
    pub conflicting_files: Vec<String>,
    pub in_progress_engineer: String,
}

#[derive(Debug, Default, Deserialize)]
struct ChangedPathsFrontmatter {
    #[serde(default)]
    changed_paths: Vec<String>,
}

fn board_tasks_dir(project_root: &Path) -> std::path::PathBuf {
    project_root
        .join(".batty")
        .join("team_config")
        .join("board")
        .join("tasks")
}

fn extract_frontmatter(content: &str) -> Option<&str> {
    let trimmed = content.trim_start();
    if !trimmed.starts_with("---") {
        return None;
    }
    let after_open = trimmed[3..].strip_prefix('\n').unwrap_or(&trimmed[3..]);
    let end = after_open.find("\n---")?;
    Some(&after_open[..end])
}

fn load_changed_paths(path: &Path) -> Vec<String> {
    let Ok(content) = std::fs::read_to_string(path) else {
        return Vec::new();
    };
    let Some(frontmatter) = extract_frontmatter(&content) else {
        return Vec::new();
    };
    serde_yaml::from_str::<ChangedPathsFrontmatter>(frontmatter)
        .map(|parsed| parsed.changed_paths)
        .unwrap_or_default()
}

fn normalize_predicted_path(path: &str) -> String {
    path.trim_matches(|ch: char| matches!(ch, '.' | ',' | ';' | ':' | ')' | ']'))
        .to_string()
}

fn has_glob_magic(path: &str) -> bool {
    path.contains('*') || path.contains('?')
}

fn glob_to_regex(pattern: &str) -> Option<Regex> {
    let mut regex = String::from("^");
    let mut chars = pattern.chars().peekable();
    while let Some(ch) = chars.next() {
        match ch {
            '*' => {
                if chars.peek() == Some(&'*') {
                    chars.next();
                    if chars.peek() == Some(&'/') {
                        chars.next();
                        regex.push_str("(?:.*/)?");
                    } else {
                        regex.push_str(".*");
                    }
                } else {
                    regex.push_str("[^/]*");
                }
            }
            '?' => regex.push_str("[^/]"),
            '.' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '^' | '$' | '|' | '\\' => {
                regex.push('\\');
                regex.push(ch);
            }
            _ => regex.push(ch),
        }
    }
    regex.push('$');
    Regex::new(&regex).ok()
}

fn glob_matches_path(pattern: &str, path: &str) -> bool {
    if !has_glob_magic(pattern) {
        return pattern == path;
    }
    glob_to_regex(pattern)
        .map(|regex| regex.is_match(path))
        .unwrap_or(false)
}

fn glob_literal_prefix(pattern: &str) -> Option<&str> {
    let idx = pattern
        .char_indices()
        .find_map(|(idx, ch)| matches!(ch, '*' | '?').then_some(idx))
        .unwrap_or(pattern.len());
    let prefix = pattern[..idx].trim_end_matches('/');
    (!prefix.is_empty()).then_some(prefix)
}

fn paths_overlap(left: &str, right: &str) -> bool {
    match (has_glob_magic(left), has_glob_magic(right)) {
        (false, false) => left == right,
        (true, false) => glob_matches_path(left, right),
        (false, true) => glob_matches_path(right, left),
        (true, true) => {
            if left == right {
                return true;
            }
            match (glob_literal_prefix(left), glob_literal_prefix(right)) {
                (Some(left_prefix), Some(right_prefix)) => {
                    left_prefix.starts_with(right_prefix) || right_prefix.starts_with(left_prefix)
                }
                _ => true,
            }
        }
    }
}

fn describe_overlap(left: &str, right: &str) -> String {
    match (has_glob_magic(left), has_glob_magic(right)) {
        (false, false) => left.to_string(),
        (true, false) => right.to_string(),
        (false, true) => left.to_string(),
        (true, true) if left == right => left.to_string(),
        (true, true) => format!("{left} <> {right}"),
    }
}

pub fn predicted_files(task: &crate::task::Task, project_root: &Path) -> Vec<String> {
    let mut paths = predict_task_file_paths(project_root, task)
        .unwrap_or_default()
        .into_iter()
        .map(|path| normalize_predicted_path(&path))
        .collect::<Vec<_>>();
    if let Ok(tasks) = crate::task::load_tasks_from_dir(&board_tasks_dir(project_root)) {
        for historical in tasks {
            if historical.id == task.id || historical.tags.is_empty() {
                continue;
            }
            if !task
                .tags
                .iter()
                .any(|tag| historical.tags.iter().any(|candidate| candidate == tag))
            {
                continue;
            }
            paths.extend(
                load_changed_paths(historical.source_path.as_path())
                    .into_iter()
                    .map(|path| normalize_predicted_path(&path)),
            );
        }
    }
    paths.retain(|path| !path.is_empty());
    paths.sort();
    paths.dedup();
    paths
}

fn overlapping_files(candidate_paths: &[String], active_paths: &[String]) -> Vec<String> {
    let mut overlaps = BTreeSet::new();
    for candidate in candidate_paths {
        for active in active_paths {
            if paths_overlap(candidate, active) {
                overlaps.insert(describe_overlap(candidate, active));
            }
        }
    }
    overlaps.into_iter().collect()
}

pub fn find_overlapping_tasks(
    candidate: &crate::task::Task,
    in_progress: &[crate::task::Task],
    project_root: &Path,
) -> Vec<OverlapConflict> {
    let candidate_paths = predicted_files(candidate, project_root);
    let mut conflicts = Vec::new();

    for active_task in in_progress {
        if active_task.id == candidate.id {
            continue;
        }
        let active_paths = predicted_files(active_task, project_root);
        let conflicting_files = overlapping_files(&candidate_paths, &active_paths);
        if conflicting_files.is_empty() {
            continue;
        }
        conflicts.push(OverlapConflict {
            task_id: active_task.id.to_string(),
            conflicting_files,
            in_progress_engineer: active_task
                .claimed_by
                .clone()
                .unwrap_or_else(|| "unknown".to_string()),
        });
    }

    conflicts.sort_by(|left, right| left.task_id.cmp(&right.task_id));
    conflicts
}

fn available_dispatch_tasks(
    board_dir: &Path,
    queued_task_ids: &HashSet<u32>,
    excluded_tags: &[String],
    non_engineer_assignees: &HashSet<String>,
    rescued_task_ids: &HashSet<u32>,
    verification_retry_task_ids: &HashSet<u32>,
) -> Result<Vec<crate::task::Task>> {
    let tasks = crate::task::load_tasks_from_dir(&board_dir.join("tasks"))?;
    let task_status_by_id: HashMap<u32, String> = tasks
        .iter()
        .map(|task| (task.id, task.status.clone()))
        .collect();

    let mut available: Vec<crate::task::Task> = tasks
        .into_iter()
        .filter(|task| {
            matches!(task.status.as_str(), "backlog" | "todo")
                || verification_retry_task_ids.contains(&task.id)
        })
        .filter(|task| task.claimed_by.is_none() || verification_retry_task_ids.contains(&task.id))
        .filter(|task| task.blocked.is_none())
        .filter(|task| task.blocked_on.is_none())
        .filter(|task| !task.is_schedule_blocked())
        .filter(|task| !queued_task_ids.contains(&task.id))
        .filter(|task| !task_has_excluded_tag(task, excluded_tags))
        // #684: tasks orphan-rescued back to todo within the cooldown
        // window are held off dispatch so the releasing engineer or
        // manager can reclaim/re-route before an auto-redispatch to a
        // peer (which is almost always the wrong answer when the
        // original claimer parked intentionally).
        .filter(|task| !rescued_task_ids.contains(&task.id))
        // #682: tasks with `assignee:` pointing at a non-engineer (manager,
        // architect, writer, …) are messages for that member's inbox, not
        // dispatch candidates. Leaving them in the pool causes repeated
        // wrong-role dispatches that burn engineer context re-reading and
        // rejecting a task they can't take.
        .filter(|task| {
            task.assignee
                .as_deref()
                .is_none_or(|name| !non_engineer_assignees.contains(name))
        })
        // #703: same principle as #682 but for body-owner declarations.
        // A task whose body reads `**Owner:** maya-lead` names the architect
        // as the owner — it should live on Maya's plate, not an engineer's
        // queue. `assignee:` on this task is empty so the #682 filter above
        // passes it through, then `rank_dispatch_engineers` splices
        // "maya-lead" into task tags for scoring, but no engineer has that
        // role → tag_overlap scores 0 for all and the task lands on
        // whichever engineer wins tiebreakers, who immediately refuses.
        // Observed batty-marketing 2026-04-17 10:18:42 UTC: task #542
        // (STRATEGY — Star-velocity Tue 04-21 mid-window gate decision,
        // `**Owner:** maya-lead (this task)`) dispatched to sam-designer-1-1,
        // burning a full claim + refuse turn on information sam had no
        // context for. Only apply this filter when `assignee:` is unset —
        // an explicit engineer assignee always wins over body prose.
        .filter(|task| {
            if task.assignee.is_some() {
                return true;
            }
            match parse_body_owner_role(&task.description) {
                Some(owner) => !non_engineer_assignees.contains(&owner),
                None => true,
            }
        })
        .filter(|task| {
            task.depends_on.iter().all(|dep_id| {
                task_status_by_id
                    .get(dep_id)
                    .is_none_or(|status| dep_status_satisfied(status))
            })
        })
        .filter(|task| body_dependencies_satisfied(task, &task_status_by_id))
        .collect();

    available.sort_by_key(|task| (dispatch_priority_rank(&task.priority), task.id));
    Ok(available)
}

/// #681: A dependency in `done` or `archived` state is fully satisfied.
/// Archived tasks are terminal (completed then cleaned up) and should
/// unblock dependents the same way `done` does — otherwise downstream
/// work stays stuck after a long-running project winds down.
fn dep_status_satisfied(status: &str) -> bool {
    matches!(status, "done" | "archived")
}

fn body_dependencies_satisfied(
    task: &crate::task::Task,
    task_status_by_id: &HashMap<u32, String>,
) -> bool {
    let Some(blocked_ids) = parse_body_dependency_ids(&task.description) else {
        return true;
    };
    !blocked_ids.is_empty()
        && blocked_ids.iter().all(|dep_id| {
            task_status_by_id
                .get(dep_id)
                .is_some_and(|status| dep_status_satisfied(status))
        })
}

/// #677: A task matches the excluded tags list (case-insensitive) when any
/// of its tags appears in the operator's `board.dispatch_excluded_tags`.
/// Matched tasks are held off the dispatch queue until an operator claims
/// them manually. Empty list means no filtering.
fn task_has_excluded_tag(task: &crate::task::Task, excluded_tags: &[String]) -> bool {
    if excluded_tags.is_empty() {
        return false;
    }
    task.tags.iter().any(|task_tag| {
        excluded_tags
            .iter()
            .any(|excluded| excluded.eq_ignore_ascii_case(task_tag))
    })
}

fn verification_retry_required_metadata(
    task: &crate::task::Task,
) -> Option<crate::team::board::WorkflowMetadata> {
    let metadata = crate::team::board::read_workflow_metadata(&task.source_path).ok()?;
    (metadata.tests_passed == Some(false)
        && metadata.outcome.as_deref() == Some("verification_retry_required")
        && !metadata.artifacts.is_empty())
    .then_some(metadata)
}

fn verification_retry_assignment_context(task: &crate::task::Task) -> Option<String> {
    let metadata = verification_retry_required_metadata(task)?;
    let mut lines = vec![
        "Verification retry required.".to_string(),
        "Outcome: verification_retry_required.".to_string(),
    ];
    if let Some(owner) = task.claimed_by.as_deref() {
        lines.push(format!("Previous owner: {owner}."));
    }
    if let Some(artifact) = metadata.artifacts.last() {
        lines.push(format!("Latest verification artifact: {artifact}."));
    }
    Some(lines.join("\n"))
}

impl TeamDaemon {
    fn verification_retry_dispatchable_task_ids(
        &self,
        board_dir: &Path,
        allow_peer_pickup: bool,
    ) -> Result<HashSet<u32>> {
        Ok(crate::task::load_tasks_from_dir(&board_dir.join("tasks"))?
            .into_iter()
            .filter(|task| self.verification_retry_dispatchable_task(task, allow_peer_pickup))
            .map(|task| task.id)
            .collect())
    }

    fn verification_retry_dispatchable_task(
        &self,
        task: &crate::task::Task,
        allow_peer_pickup: bool,
    ) -> bool {
        if matches!(task.status.as_str(), "done" | "archived") {
            return false;
        }
        if verification_retry_required_metadata(task).is_none() {
            return false;
        }
        let Some(owner) = task.claimed_by.as_deref() else {
            return true;
        };
        if self.active_tasks.get(owner) == Some(&task.id)
            && self.states.get(owner) == Some(&MemberState::Working)
        {
            return false;
        }
        self.idle_engineer_names()
            .iter()
            .any(|engineer| engineer == owner)
            || allow_peer_pickup
    }

    fn serialize_overlapping_candidate(
        &mut self,
        board_dir: &Path,
        candidate: &crate::task::Task,
        conflicts: &[OverlapConflict],
        persist_dependency: bool,
    ) -> Result<bool> {
        if conflicts.is_empty() {
            return Ok(false);
        }

        let mut blocking_task_ids: Vec<u32> = conflicts
            .iter()
            .filter_map(|conflict| conflict.task_id.parse::<u32>().ok())
            .collect();
        blocking_task_ids.sort_unstable();
        blocking_task_ids.dedup();
        let overlap_details = conflicts
            .iter()
            .map(|conflict| {
                format!(
                    "#{} [{}]",
                    conflict.task_id,
                    conflict.conflicting_files.join(", ")
                )
            })
            .collect::<Vec<_>>();
        // #696: strip cycle-creating edges before persisting. If the
        // candidate is already (directly or transitively) a dependency
        // of a blocking task, adding `candidate depends_on blocking_id`
        // would form a cycle — auto_doctor surfaces these as WARNs but
        // does not heal them, leaving both tasks indefinitely stuck.
        // Observed in batty-marketing 2026-04-17: #553 depends_on [554]
        // was authored by maya-lead, then dispatch overlap persisted
        // #554 depends_on [553] ("prevented overlapping dispatch"),
        // producing `dependency cycle detected: #553 -> #554 -> #553`.
        let (safe_blocking_ids, rejected_blocking_ids) = if persist_dependency {
            split_acyclic_blocking_ids(board_dir, candidate.id, &blocking_task_ids)?
        } else {
            (blocking_task_ids.clone(), Vec::new())
        };
        if !rejected_blocking_ids.is_empty() {
            warn!(
                task_id = candidate.id,
                rejected = ?rejected_blocking_ids,
                "dispatch queue: skipped cycle-creating overlap dependency"
            );
        }
        let updated_dependencies = if persist_dependency && !safe_blocking_ids.is_empty() {
            Some(append_task_dependencies(
                board_dir,
                candidate.id,
                &safe_blocking_ids,
            )?)
        } else {
            None
        };
        let details = if persist_dependency {
            format!(
                "serialized task #{} behind {} due to predicted file overlap",
                candidate.id,
                overlap_details.join("; ")
            )
        } else {
            format!(
                "deferred task #{} in file_lock_wait behind {} due to predicted file overlap",
                candidate.id,
                overlap_details.join("; ")
            )
        };
        self.emit_event(TeamEvent::dispatch_overlap_prevented(
            candidate.id,
            &blocking_task_ids,
            &details,
        ));
        self.record_orchestrator_action(format!("dispatch overlap: {details}"));
        info!(
            task_id = candidate.id,
            blocking = ?updated_dependencies,
            persist_dependency,
            "dispatch queue: prevented overlapping dispatch"
        );
        Ok(true)
    }

    pub(in super::super) fn idle_engineer_names(&self) -> Vec<String> {
        self.config
            .members
            .iter()
            .filter(|member| member.role_type == RoleType::Engineer)
            .filter(|member| {
                let state = self.states.get(&member.name);
                match state {
                    Some(&MemberState::Idle) => true,
                    // Working engineers with no active task are effectively idle
                    // and should be eligible for dispatch.
                    Some(&MemberState::Working) => !self.active_tasks.contains_key(&member.name),
                    _ => false,
                }
            })
            .map(|member| member.name.clone())
            .collect()
    }

    #[cfg_attr(not(test), allow(dead_code))]
    fn next_dispatch_task(
        &self,
        board_dir: &Path,
        queued_task_ids: &HashSet<u32>,
    ) -> Result<Option<crate::task::Task>> {
        let normal_available = available_dispatch_tasks(
            board_dir,
            queued_task_ids,
            &self.config.team_config.board.dispatch_excluded_tags,
            &self.non_engineer_member_names(),
            &self.rescued_task_ids(),
            &HashSet::new(),
        )?;
        let allow_peer_pickup =
            normal_available.is_empty() && !self.idle_engineer_names().is_empty();
        Ok(available_dispatch_tasks(
            board_dir,
            queued_task_ids,
            &self.config.team_config.board.dispatch_excluded_tags,
            &self.non_engineer_member_names(),
            &self.rescued_task_ids(),
            &self.verification_retry_dispatchable_task_ids(board_dir, allow_peer_pickup)?,
        )?
        .into_iter()
        .next())
    }

    /// #684 / #686: task IDs currently within the orphan-rescue cooldown
    /// window (exponentially grown per repeated rescue). Dispatch filters
    /// these out so a task the releasing engineer parked doesn't immediately
    /// bounce to a peer, and tasks that keep getting rescued stay quiet
    /// longer instead of re-cascading every base window.
    pub(super) fn rescued_task_ids(&self) -> HashSet<u32> {
        let base = Duration::from_secs(self.config.team_config.board.orphan_rescue_cooldown_secs);
        self.recently_rescued_tasks
            .iter()
            .filter(|(_, record)| record.dispatch_blocked(base))
            .map(|(task_id, _)| *task_id)
            .collect()
    }

    /// #686 / #689: record a rescue event for `task_id`. Growth condition
    /// uses the cascade-observation window (2× effective cooldown), not
    /// the dispatch-gate window — rescues can only fire *after* the
    /// dispatch gate has opened, so gating growth on `dispatch_blocked`
    /// meant the counter never climbed past 1 in production.
    pub(in super::super) fn record_task_rescue(&mut self, task_id: u32) {
        let base = Duration::from_secs(self.config.team_config.board.orphan_rescue_cooldown_secs);
        let now = Instant::now();
        self.recently_rescued_tasks
            .entry(task_id)
            .and_modify(|record| {
                if record.in_cascade_window(base) {
                    record.count = record.count.saturating_add(1);
                } else {
                    record.count = 1;
                }
                record.last_rescued_at = now;
            })
            .or_insert(crate::team::daemon::RescueRecord {
                last_rescued_at: now,
                count: 1,
            });
    }

    /// #697: window within which an engineer who just released a task's
    /// claim is excluded from re-dispatch of that same task.
    pub(in super::super) fn release_exclusion_window(&self) -> Duration {
        Duration::from_secs(
            self.config
                .team_config
                .board
                .dispatch_release_exclusion_secs,
        )
    }

    /// #697 / #698: record that `engineer` just released task `task_id`
    /// (state reconciliation observed `claimed_by` cleared). Subsequent
    /// dispatch cycles skip this pair until the exclusion window
    /// elapses. #698: if the previous release for this pair is still
    /// inside the cascade-observation window (2× effective window), the
    /// counter grows — widening the next exclusion window exponentially
    /// up to 16× base. This prevents a human-parked task (owner
    /// awaiting a Saturday ping, for instance) from cycling through
    /// dispatch→release every base window for ~14 hours.
    pub(in super::super) fn record_task_release_by(&mut self, task_id: u32, engineer: &str) {
        let base = self.release_exclusion_window();
        let now = Instant::now();
        self.recently_released_by
            .entry((task_id, engineer.to_string()))
            .and_modify(|record| {
                if record.in_cascade_window(base) {
                    record.count = record.count.saturating_add(1);
                } else {
                    record.count = 1;
                }
                record.last_released_at = now;
            })
            .or_insert(crate::team::daemon::ReleaseRecord {
                last_released_at: now,
                count: 1,
            });
    }

    /// #697 / #698: true if `engineer` is still within the current
    /// (exponentially-grown) release-exclusion window for `task_id`.
    pub(in super::super) fn is_release_excluded(&self, task_id: u32, engineer: &str) -> bool {
        let base = self.release_exclusion_window();
        self.recently_released_by
            .get(&(task_id, engineer.to_string()))
            .map(|record| record.dispatch_excluded(base))
            .unwrap_or(false)
    }

    /// Returns names of configured members whose role is NOT `Engineer`.
    /// Tasks whose `assignee:` frontmatter points at one of these names
    /// are excluded from dispatch — they belong in that member's inbox.
    fn non_engineer_member_names(&self) -> HashSet<String> {
        self.config
            .members
            .iter()
            .filter(|member| member.role_type != RoleType::Engineer)
            .map(|member| member.name.clone())
            .collect()
    }

    #[cfg(test)]
    pub(super) fn test_next_dispatch_task(
        &self,
        board_dir: &std::path::Path,
        queued: &HashSet<u32>,
    ) -> Result<Option<crate::task::Task>> {
        self.next_dispatch_task(board_dir, queued)
    }

    pub(in super::super) fn enqueue_dispatch_candidates(&mut self) -> Result<()> {
        let board_dir = self.board_dir();
        let board_tasks = crate::task::load_tasks_from_dir(&board_dir.join("tasks"))?;
        let benched_engineers = crate::team::bench::benched_engineer_names(self.project_root())?;
        let dedup_window =
            Duration::from_secs(self.config.team_config.board.dispatch_dedup_window_secs);

        // Expire stale dedup entries.
        self.recent_dispatches
            .retain(|_, dispatched_at| dispatched_at.elapsed() < dedup_window);
        // #697 / #698: retain release-exclusion records through the
        // full cascade-observation window (2× effective window). Dropping
        // the record the moment the gate opens would reset `count` to 1
        // on every release, killing the exponential backoff the same way
        // the pre-#689 rescue map did.
        let release_base_window = self.release_exclusion_window();
        self.recently_released_by
            .retain(|_, record| record.in_cascade_window(release_base_window));

        // #684 / #686 / #689: retain rescue records through the full
        // cascade-observation window (2× effective cooldown), not just
        // the dispatch gate. Dropping the record the moment the gate
        // opens is what caused the counter to reset to 1 on every
        // rescue in production — killing the exponential backoff.
        let rescue_base_cooldown =
            Duration::from_secs(self.config.team_config.board.orphan_rescue_cooldown_secs);
        self.recently_rescued_tasks
            .retain(|_, record| record.in_cascade_window(rescue_base_cooldown));
        // Only task IDs still behind the dispatch gate should block new
        // dispatch; past-gate-but-in-window entries live on only so the
        // next rescue can see them and grow the counter.
        let rescued_task_ids: HashSet<u32> = self
            .recently_rescued_tasks
            .iter()
            .filter(|(_, record)| record.dispatch_blocked(rescue_base_cooldown))
            .map(|(task_id, _)| *task_id)
            .collect();
        let mut queued_task_ids: HashSet<u32> = self
            .dispatch_queue
            .iter()
            .map(|entry| entry.task_id)
            .collect();
        let mut queued_engineers: HashSet<String> = self
            .dispatch_queue
            .iter()
            .map(|entry| entry.engineer.clone())
            .collect();
        let mut file_locked_task_ids = HashSet::new();

        let manual_cooldown =
            Duration::from_secs(self.config.team_config.board.dispatch_manual_cooldown_secs);

        let all_engineers: Vec<String> = self
            .config
            .members
            .iter()
            .filter(|member| member.role_type == RoleType::Engineer)
            .map(|member| member.name.clone())
            .collect();
        let non_engineer_names = self.non_engineer_member_names();
        let mut profiles =
            load_engineer_profiles(self.project_root(), &all_engineers, &board_tasks)?;

        // #691: seed domain_tags with each engineer's role_name so tasks
        // tagged with the role (e.g. "kai-devrel") preferentially route to
        // engineers of that role before any completion history exists.
        // Without this, fresh engineer profiles have empty domain_tags and
        // tag_overlap contributes 0 to routing scores — causing role-tagged
        // tasks to be dispatched by alphabetical fallback (observed:
        // task #550 tagged "kai-devrel" was dispatched to sam-designer,
        // who immediately released it).
        for member in &self.config.members {
            if member.role_type != RoleType::Engineer {
                continue;
            }
            if let Some(profile) = profiles.get_mut(&member.name) {
                for seed in role_name_seed_tags(&member.role_name) {
                    profile.domain_tags.insert(seed);
                }
            }
        }

        let allow_peer_retry_pickup = available_dispatch_tasks(
            &board_dir,
            &queued_task_ids,
            &self.config.team_config.board.dispatch_excluded_tags,
            &non_engineer_names,
            &rescued_task_ids,
            &HashSet::new(),
        )?
        .is_empty()
            && !self.idle_engineer_names().is_empty();

        // Tasks whose only eligible engineer(s) are currently blocked (already
        // in `recent_dispatches` or #697 release-excluded). Treat them as
        // unavailable for the remainder of this enqueue pass so the outer
        // loop can advance to lower-priority tasks for other idle engineers
        // instead of stalling the whole queue. Observed 2026-04-17 on
        // batty_marketing: top-priority #597 was body-owner-restricted to
        // alex-dev-1-1 who sat inside the 1h release-exclusion window, which
        // starved dispatches for priya/sam/kai on their own tasks.
        let mut eligibility_excluded_task_ids: HashSet<u32> = HashSet::new();
        loop {
            let mut unavailable_task_ids = queued_task_ids.clone();
            unavailable_task_ids.extend(file_locked_task_ids.iter().copied());
            unavailable_task_ids.extend(eligibility_excluded_task_ids.iter().copied());
            let verification_retry_task_ids =
                self.verification_retry_dispatchable_task_ids(&board_dir, allow_peer_retry_pickup)?;
            let available_tasks = available_dispatch_tasks(
                &board_dir,
                &unavailable_task_ids,
                &self.config.team_config.board.dispatch_excluded_tags,
                &non_engineer_names,
                &rescued_task_ids,
                &verification_retry_task_ids,
            )?;
            if available_tasks.is_empty() {
                break;
            }

            let in_progress_tasks: Vec<crate::task::Task> =
                crate::task::load_tasks_from_dir(&board_dir.join("tasks"))?
                    .into_iter()
                    .filter(|task| task.status == "in-progress")
                    .collect();
            let mut selected_task = None;
            let mut least_conflicted: Option<(crate::task::Task, Vec<OverlapConflict>)> = None;
            let file_level_locks_enabled = self.config.team_config.workflow_policy.file_level_locks;

            // Skip overlap check when all engineers use worktrees — conflicts
            // are handled at merge time (cherry-pick), not dispatch time.
            let all_engineers_use_worktrees = self
                .config
                .team_config
                .roles
                .iter()
                .filter(|r| r.role_type == crate::team::config::RoleType::Engineer)
                .all(|r| r.use_worktrees);
            let skip_overlap_checks = all_engineers_use_worktrees && !file_level_locks_enabled;

            for task in available_tasks {
                if skip_overlap_checks {
                    selected_task = Some(task);
                    break;
                }

                let conflicts =
                    find_overlapping_tasks(&task, &in_progress_tasks, self.project_root());
                if conflicts.is_empty() {
                    selected_task = Some(task);
                    break;
                }

                for conflict in &conflicts {
                    self.emit_event(TeamEvent::dispatch_overlap_skipped(
                        task.id,
                        &conflict.task_id,
                        &conflict.conflicting_files,
                    ));
                }

                if file_level_locks_enabled {
                    self.serialize_overlapping_candidate(&board_dir, &task, &conflicts, false)?;
                    file_locked_task_ids.insert(task.id);
                    continue;
                }

                let replace = least_conflicted
                    .as_ref()
                    .is_none_or(|(_, existing)| conflicts.len() < existing.len());
                if replace {
                    least_conflicted = Some((task, conflicts));
                }
            }

            let task = if let Some(task) = selected_task {
                task
            } else if let Some((task, conflicts)) = least_conflicted {
                self.serialize_overlapping_candidate(&board_dir, &task, &conflicts, true)?;
                continue;
            } else {
                break;
            };
            let ranked_engineers = self.rank_dispatch_engineers(
                &task,
                &queued_engineers,
                &benched_engineers,
                manual_cooldown,
                &profiles,
            );
            let retry_previous_owner = self
                .verification_retry_dispatchable_task(&task, allow_peer_retry_pickup)
                .then(|| task.claimed_by.clone())
                .flatten();
            let mut ranked_engineers = ranked_engineers;
            if let Some(owner) = retry_previous_owner.as_deref() {
                ranked_engineers
                    .retain(|engineer_name| engineer_name == owner || allow_peer_retry_pickup);
                if let Some(index) = ranked_engineers
                    .iter()
                    .position(|engineer_name| engineer_name == owner)
                {
                    let owner = ranked_engineers.remove(index);
                    ranked_engineers.insert(0, owner);
                }
            }
            let Some(engineer_name) = ranked_engineers.into_iter().find(|engineer_name| {
                !self
                    .recent_dispatches
                    .contains_key(&(task.id, engineer_name.clone()))
                    // #697: skip engineers who recently released this task.
                    && !self.is_release_excluded(task.id, engineer_name)
            }) else {
                // No eligible engineer for THIS task right now — defer it and
                // let the loop consider lower-priority tasks. Without this,
                // a body-owner-restricted high-priority task whose owner is
                // inside the release-exclusion window blocks every subsequent
                // idle engineer from getting work.
                eligibility_excluded_task_ids.insert(task.id);
                continue;
            };

            queued_task_ids.insert(task.id);
            queued_engineers.insert(engineer_name.clone());
            self.dispatch_queue.push(DispatchQueueEntry {
                engineer: engineer_name,
                task_id: task.id,
                task_title: task.title,
                queued_at: now_unix(),
                validation_failures: 0,
                last_failure: None,
            });
        }
        Ok(())
    }

    fn task_for_dispatch_entry(
        &self,
        board_dir: &Path,
        entry: &DispatchQueueEntry,
    ) -> Result<Option<crate::task::Task>> {
        let tasks = crate::task::load_tasks_from_dir(&board_dir.join("tasks"))?;
        let task_status_by_id: HashMap<u32, String> = tasks
            .iter()
            .map(|task| (task.id, task.status.clone()))
            .collect();
        Ok(tasks.into_iter().find(|task| {
            let retry_dispatchable = self.verification_retry_dispatchable_task(task, true);
            task.id == entry.task_id
                && (matches!(task.status.as_str(), "backlog" | "todo") || retry_dispatchable)
                && (task.claimed_by.is_none() || retry_dispatchable)
                && task.blocked.is_none()
                && task.blocked_on.is_none()
                && !task.is_schedule_blocked()
                && task.depends_on.iter().all(|dep_id| {
                    task_status_by_id
                        .get(dep_id)
                        .is_none_or(|status| dep_status_satisfied(status))
                })
                && body_dependencies_satisfied(task, &task_status_by_id)
        }))
    }

    pub(in super::super) fn process_dispatch_queue(&mut self) -> Result<()> {
        self.reconcile_active_tasks()?;
        let board_dir = self.board_dir();
        let benched_engineers = crate::team::bench::benched_engineer_names(self.project_root())?;
        // #689: re-check the rescue cooldown at drain time. An entry can
        // be queued at `enqueue_dispatch_candidates` time, then the task
        // enters the rescue cooldown later in the same tick (when the
        // orphan-rescue runs after the queue was populated). Without
        // this re-check, the stale entry consumes the new cooldown by
        // dispatching on the very next drain.
        let rescued_task_ids = self.rescued_task_ids();
        let mut pending: Vec<DispatchQueueEntry> = std::mem::take(&mut self.dispatch_queue);
        let mut retained = Vec::new();

        for mut entry in pending.drain(..) {
            // Prune stale entries first: if the task is done, claimed by someone
            // else, or no longer exists, drop the entry regardless of engineer
            // state. Without this, entries for non-idle engineers persist forever.
            let task_still_dispatchable =
                self.task_for_dispatch_entry(&board_dir, &entry)?.is_some();
            if !task_still_dispatchable {
                debug!(
                    engineer = %entry.engineer,
                    task_id = entry.task_id,
                    "dispatch queue: pruning stale entry (task done/claimed/missing)"
                );
                continue;
            }
            if rescued_task_ids.contains(&entry.task_id) {
                info!(
                    engineer = %entry.engineer,
                    task_id = entry.task_id,
                    "dispatch queue: pruning entry — task re-entered orphan-rescue cooldown"
                );
                continue;
            }
            // #697: drop entries where the engineer recently released
            // this task. `enqueue_dispatch_candidates` filters at queue
            // time; this catches the race where the entry was queued
            // before the release was recorded in the same tick.
            if self.is_release_excluded(entry.task_id, &entry.engineer) {
                info!(
                    engineer = %entry.engineer,
                    task_id = entry.task_id,
                    "dispatch queue: pruning entry — engineer recently released this task"
                );
                continue;
            }
            if benched_engineers.contains(&entry.engineer) {
                debug!(
                    engineer = %entry.engineer,
                    task_id = entry.task_id,
                    "dispatch queue: pruning benched engineer entry"
                );
                continue;
            }

            // Recover engineers stuck in Working with no active task.
            // This happens when mark_member_working() fires but task
            // delivery fails, leaving the state map inconsistent.
            if self.states.get(&entry.engineer) == Some(&MemberState::Working)
                && !self.active_tasks.contains_key(&entry.engineer)
            {
                info!(
                    engineer = %entry.engineer,
                    task_id = entry.task_id,
                    "dispatch queue: recovering engineer stuck in Working with no active task"
                );
                self.states
                    .insert(entry.engineer.clone(), MemberState::Idle);
                self.update_automation_timers_for_state(&entry.engineer, MemberState::Idle);
            }

            if self.states.get(&entry.engineer) != Some(&MemberState::Idle) {
                retained.push(entry);
                continue;
            }
            if self.should_hold_dispatch_for_stabilization(&entry.engineer) {
                retained.push(entry);
                continue;
            }

            let Some(task) = self.task_for_dispatch_entry(&board_dir, &entry)? else {
                continue;
            };

            let retry_dispatchable = self.verification_retry_dispatchable_task(&task, true);
            // Skip if the task is already in-progress, except retry-required
            // rework that was intentionally left in-progress to preserve its
            // failed verification metadata.
            if task.status == "in-progress" && !retry_dispatchable {
                info!(
                    engineer = %entry.engineer,
                    task_id = task.id,
                    "dispatch queue: task already in-progress, skipping"
                );
                continue;
            }

            // Skip if the task body has unmet text dependencies
            // (e.g. "Blocked on: #65, #66" where those tasks aren't done)
            if let Some(blocked_ids) = parse_body_dependency_ids(&task.description) {
                let all_tasks =
                    crate::task::load_tasks_from_dir(&board_dir.join("tasks")).unwrap_or_default();
                let unmet: Vec<u32> = blocked_ids
                    .iter()
                    .filter(|id| {
                        !all_tasks
                            .iter()
                            .any(|t| t.id == **id && dep_status_satisfied(&t.status))
                    })
                    .copied()
                    .collect();
                if blocked_ids.is_empty() || !unmet.is_empty() {
                    warn!(
                        engineer = %entry.engineer,
                        task_id = task.id,
                        ?unmet,
                        "dispatch queue: task has unmet body dependencies, skipping"
                    );
                    // Move to blocked status
                    let _ = crate::team::task_cmd::transition_task_with_attribution(
                        &board_dir,
                        task.id,
                        "blocked",
                        StatusTransitionAttribution::daemon("daemon.dispatch.queue.dependencies"),
                    );
                    continue;
                }
            }

            let active_count =
                self.engineer_active_board_item_count(&board_dir, &entry.engineer)?;
            let retry_same_owner =
                retry_dispatchable && task.claimed_by.as_deref() == Some(entry.engineer.as_str());
            let effective_active_count = if retry_same_owner {
                active_count.saturating_sub(1)
            } else {
                active_count
            };
            if effective_active_count > 0 {
                // Try to reassign to an idle engineer with no active items
                let retained_engineers: HashSet<&str> =
                    retained.iter().map(|e| e.engineer.as_str()).collect();
                let alt = self.idle_engineer_names().into_iter().find(|name| {
                    name != &entry.engineer
                        && !retained_engineers.contains(name.as_str())
                        && self
                            .engineer_active_board_item_count(&board_dir, name)
                            .unwrap_or(1)
                            == 0
                });
                if let Some(alt_engineer) = alt {
                    debug!(
                        from = %entry.engineer,
                        to = %alt_engineer,
                        task_id = entry.task_id,
                        "dispatch queue: reassigning to idle engineer"
                    );
                    entry.engineer = alt_engineer;
                    entry.validation_failures = 0;
                    entry.last_failure = None;
                    retained.push(entry);
                    continue;
                }

                // No alternative — increment failure count
                entry.validation_failures += 1;
                entry.last_failure = Some(format!(
                    "Dispatch guard blocked assignment for '{}' with {} active board item(s); no idle alternative",
                    entry.engineer, effective_active_count
                ));
                if entry.validation_failures >= DISPATCH_QUEUE_FAILURE_LIMIT {
                    // Drop silently — will be re-queued by auto-dispatch when
                    // an engineer frees up. No need to escalate what is just
                    // a "everyone is busy" situation.
                    debug!(
                        engineer = %entry.engineer,
                        task_id = entry.task_id,
                        "dispatch queue: all engineers busy, dropping entry (will re-queue)"
                    );
                } else {
                    retained.push(entry);
                }
                continue;
            }

            if !check_wip_limit(
                &self.config.team_config.workflow_policy,
                RoleType::Engineer,
                effective_active_count,
            ) {
                entry.validation_failures += 1;
                entry.last_failure = Some(format!(
                    "WIP gate blocked dispatch for '{}' with {} active board task(s)",
                    entry.engineer, effective_active_count
                ));
                warn!(
                    engineer = %entry.engineer,
                    task_id = entry.task_id,
                    failures = entry.validation_failures,
                    "dispatch queue: WIP limit blocked dispatch"
                );
                if entry.validation_failures >= DISPATCH_QUEUE_FAILURE_LIMIT {
                    self.escalate_dispatch_queue_entry(
                        &entry,
                        entry
                            .last_failure
                            .as_deref()
                            .unwrap_or("wip gate blocked dispatch"),
                    )?;
                } else {
                    retained.push(entry);
                }
                continue;
            }

            let member_uses_worktrees = self.member_uses_worktrees(&entry.engineer);
            if member_uses_worktrees {
                let worktree_dir = self.worktree_dir(&entry.engineer);
                if let Err(error) = engineer_worktree_ready_for_dispatch_from_trunk(
                    &self.config.project_root,
                    &worktree_dir,
                    &entry.engineer,
                    self.config.team_config.trunk_branch(),
                ) {
                    entry.validation_failures += 1;
                    entry.last_failure = Some(error.to_string());
                    warn!(
                        engineer = %entry.engineer,
                        task_id = entry.task_id,
                        failures = entry.validation_failures,
                        error = %error,
                        "dispatch queue: worktree not ready for dispatch"
                    );

                    // Auto-recover: try rebase first, only reset as last resort.
                    let base_branch = format!("eng-main/{}", entry.engineer);

                    // SAFETY: if worktree has commits ahead of trunk, try rebase not reset.
                    let has_work = crate::worktree::commits_ahead(
                        &worktree_dir,
                        self.config.team_config.trunk_branch(),
                    )
                    .map(|n| n > 0)
                    .unwrap_or(false)
                        || crate::worktree::has_uncommitted_changes(&worktree_dir).unwrap_or(false);

                    if has_work {
                        info!(
                            engineer = %entry.engineer,
                            "dispatch queue: worktree has work; trying rebase instead of reset"
                        );
                        // Try to rebase onto trunk to preserve work.
                        let rebase_result = std::process::Command::new("git")
                            .args(["rebase", self.config.team_config.trunk_branch()])
                            .current_dir(&worktree_dir)
                            .output();
                        if rebase_result.map(|o| o.status.success()).unwrap_or(false) {
                            match crate::team::task_loop::engineer_worktree_ready_for_dispatch_from_trunk(
                                &self.config.project_root,
                                &worktree_dir,
                                &entry.engineer,
                                self.config.team_config.trunk_branch(),
                            ) {
                                Ok(()) => {
                                    info!(
                                        engineer = %entry.engineer,
                                        "dispatch queue: rebase succeeded; retrying dispatch"
                                    );
                                    entry.validation_failures = 0;
                                    entry.last_failure = None;
                                    retained.push(entry);
                                    continue;
                                }
                                Err(error) => {
                                    warn!(
                                        engineer = %entry.engineer,
                                        error = %error,
                                        "dispatch queue: rebase succeeded but worktree is still not ready; falling through to reset"
                                    );
                                }
                            }
                        }
                        // Rebase failed — abort and fall through to reset
                        let _ = std::process::Command::new("git")
                            .args(["rebase", "--abort"])
                            .current_dir(&worktree_dir)
                            .output();
                        warn!(
                            engineer = %entry.engineer,
                            "dispatch queue: rebase failed; falling through to reset (work may be lost)"
                        );
                    }

                    info!(
                        engineer = %entry.engineer,
                        base_branch = %base_branch,
                        "dispatch queue: auto-resetting worktree to base branch"
                    );
                    match crate::worktree::reset_worktree_to_base_if_clean_from_trunk(
                        &worktree_dir,
                        &base_branch,
                        "dispatch/reset recovery",
                        self.config.team_config.trunk_branch(),
                    ) {
                        Err(reset_err) => {
                            warn!(
                                engineer = %entry.engineer,
                                error = %reset_err,
                                "dispatch queue: worktree auto-reset failed; escalating"
                            );
                            entry.validation_failures += 1;
                            entry.last_failure = Some(reset_err.to_string());
                            self.report_preserve_failure(
                                &entry.engineer,
                                None,
                                "dispatch/reset recovery",
                                &reset_err.to_string(),
                            );
                            if entry.validation_failures >= DISPATCH_QUEUE_FAILURE_LIMIT {
                                self.escalate_dispatch_queue_entry(
                                    &entry,
                                    entry
                                        .last_failure
                                        .as_deref()
                                        .unwrap_or("worktree readiness validation failed"),
                                )?;
                            } else {
                                retained.push(entry);
                            }
                        }
                        Ok(reason) if reason.reset_performed() => {
                            info!(
                                engineer = %entry.engineer,
                                reset_reason = reason.as_str(),
                                "dispatch queue: worktree auto-reset succeeded; retrying dispatch"
                            );
                            entry.validation_failures = 0;
                            entry.last_failure = None;
                            retained.push(entry);
                        }
                        Ok(reason) => {
                            warn!(
                                engineer = %entry.engineer,
                                reset_reason = reason.as_str(),
                                "dispatch queue: worktree auto-reset skipped"
                            );
                            entry.validation_failures += 1;
                            entry.last_failure = Some(
                                crate::team::task_loop::dirty_worktree_preservation_blocked_reason(
                                    &worktree_dir,
                                    "dispatch/reset recovery",
                                ),
                            );
                            self.report_preserve_failure(
                                &entry.engineer,
                                None,
                                "dispatch/reset recovery",
                                reason.as_str(),
                            );
                            retained.push(entry);
                        }
                    }
                    continue;
                }
            }

            // Transition to in-progress BEFORE assigning. If this fails,
            // keep the task in the queue — don't send work that the board
            // doesn't reflect, or reconciliation will undo it in a loop.
            if task.status == "backlog" {
                let _ = transition_task_with_attribution(
                    &board_dir,
                    task.id,
                    "todo",
                    StatusTransitionAttribution::daemon("daemon.dispatch.queue"),
                );
            }
            if let Err(e) = transition_task_with_attribution(
                &board_dir,
                task.id,
                "in-progress",
                StatusTransitionAttribution::daemon("daemon.dispatch.queue"),
            ) {
                entry.validation_failures += 1;
                entry.last_failure = Some(format!("board transition failed: {e}"));
                warn!(
                    engineer = %entry.engineer,
                    task_id = task.id,
                    error = %e,
                    "dispatch queue: cannot transition task to in-progress, deferring"
                );
                if entry.validation_failures >= DISPATCH_QUEUE_FAILURE_LIMIT {
                    self.escalate_dispatch_queue_entry(
                        &entry,
                        entry
                            .last_failure
                            .as_deref()
                            .unwrap_or("board transition failed"),
                    )?;
                } else {
                    retained.push(entry);
                }
                continue;
            }
            assign_task_owners(&board_dir, task.id, Some(&entry.engineer), None)?;

            let assignment_message =
                format!("Task #{}: {}\n\n{}", task.id, task.title, task.description);
            let assignment_message =
                if let Some(context) = verification_retry_assignment_context(&task) {
                    format!("{assignment_message}\n\n{context}")
                } else {
                    assignment_message
                };
            match self.assign_task_with_task_id(&entry.engineer, &assignment_message, Some(task.id))
            {
                Ok(_) => {
                    self.active_tasks.insert(entry.engineer.clone(), task.id);
                    self.retry_counts.remove(&entry.engineer);
                    self.recent_dispatches
                        .insert((task.id, entry.engineer.clone()), Instant::now());
                    self.record_orchestrator_action(format!(
                        "dispatch queue: selected runnable task #{} ({}) and dispatched it to {}",
                        task.id, task.title, entry.engineer
                    ));
                    info!(
                        engineer = %entry.engineer,
                        task_id = task.id,
                        task_title = %task.title,
                        "queued task dispatched"
                    );
                }
                Err(error) => {
                    entry.validation_failures += 1;
                    entry.last_failure = Some(error.to_string());
                    warn!(
                        engineer = %entry.engineer,
                        task_id = entry.task_id,
                        failures = entry.validation_failures,
                        error = %error,
                        "dispatch queue: assignment launch failed"
                    );
                    if entry.validation_failures >= DISPATCH_QUEUE_FAILURE_LIMIT {
                        self.escalate_dispatch_queue_entry(
                            &entry,
                            entry
                                .last_failure
                                .as_deref()
                                .unwrap_or("assignment launch failed"),
                        )?;
                    } else {
                        retained.push(entry);
                    }
                }
            }
        }

        self.dispatch_queue = retained;
        Ok(())
    }

    fn rank_dispatch_engineers(
        &self,
        task: &crate::task::Task,
        queued_engineers: &HashSet<String>,
        benched_engineers: &std::collections::BTreeSet<String>,
        manual_cooldown: Duration,
        profiles: &HashMap<String, EngineerProfile>,
    ) -> Vec<String> {
        let mut eligible: Vec<String> = self
            .idle_engineer_names()
            .into_iter()
            .filter(|engineer_name| !queued_engineers.contains(engineer_name))
            .filter(|engineer_name| !benched_engineers.contains(engineer_name))
            // #682: honor `assignee:` frontmatter when it names an engineer.
            // Non-engineer assignees are filtered earlier in
            // `available_dispatch_tasks`; by the time we get here, an
            // assignee must be an engineer who wants this specific task.
            .filter(|engineer_name| {
                task.assignee
                    .as_deref()
                    .is_none_or(|preferred| preferred == engineer_name)
            })
            .filter(|engineer_name| {
                // #674 defect 2: skip engineers whose backend is parked
                // (quota_exhausted with future retry_at). Without this gate,
                // a stale cached `Healthy` state or the 15-minute stall-timer
                // reclaim would rotate tasks through every quota-blocked
                // engineer on every dispatch tick.
                if self.member_backend_parked(engineer_name) {
                    debug!(
                        engineer = %engineer_name,
                        "skipping dispatch — backend quota parked"
                    );
                    return false;
                }
                let Some(assigned_at) = self.manual_assign_cooldowns.get(engineer_name) else {
                    return true;
                };
                if assigned_at.elapsed() < manual_cooldown {
                    debug!(
                        engineer = %engineer_name,
                        "skipping dispatch — within manual assignment cooldown"
                    );
                    false
                } else {
                    true
                }
            })
            .collect();
        eligible.sort();

        // #705: when the task body explicitly names an engineer role
        // (e.g. `- Route: dispatch to priya-writer.`), restrict
        // eligibility to engineers carrying that role_name. Mirrors
        // #682's "wait when assignee busy" behavior for the body-owner
        // routing case: if the named engineer is not idle, leave the
        // task undispatched rather than cascade-dispatch to a peer who
        // will refuse. Only applies when at least one engineer actually
        // carries the role — a body naming a non-engineer falls through
        // to #703's filter in `available_dispatch_tasks`; a body naming
        // an unknown/unconfigured role falls through to scoring.
        //
        // Observed 2026-04-17 11:04:36 UTC in batty-marketing: task
        // #549 (body: `- Route: dispatch to priya-writer.`) dispatched
        // to kai-devrel-1-1 because priya-writer-1-1 was `working`
        // at the tick. kai released (third cascade attempt — prior:
        // kai at 09:13, alex at 10:18). Before this gate the dispatcher
        // bounced the task between whichever engineer happened to be
        // idle each tick, burning claim+refuse turns.
        let body_owner_role = parse_body_owner_role(&task.description);
        if let Some(ref owner_role) = body_owner_role {
            let engineers_with_role: HashSet<String> = self
                .config
                .members
                .iter()
                .filter(|m| m.role_type == RoleType::Engineer && &m.role_name == owner_role)
                .map(|m| m.name.clone())
                .collect();
            if !engineers_with_role.is_empty() {
                eligible.retain(|name| engineers_with_role.contains(name));
            }
        }

        if self.config.team_config.workflow_policy.allocation.strategy
            == AllocationStrategy::RoundRobin
        {
            return eligible;
        }

        // #695: if the task body explicitly names an owner role
        // (`Owner: priya-writer …`), splice that role into the task's tag
        // set before scoring. Combined with #691's role_name seeding of
        // each engineer's `domain_tags`, this produces a non-zero
        // `tag_overlap` for the matching engineer and triggers the #692
        // tag-match bypass — so the explicit body owner wins over
        // scoring-tiebreaker alphabetical fallback.
        let task_for_ranking = match body_owner_role {
            Some(owner_role) if !task.tags.iter().any(|tag| tag == &owner_role) => {
                let mut synth = task.clone();
                synth.tags.push(owner_role);
                std::borrow::Cow::Owned(synth)
            }
            _ => std::borrow::Cow::Borrowed(task),
        };

        rank_engineers_for_task(
            &eligible,
            profiles,
            &task_for_ranking,
            &self.config.team_config.workflow_policy.allocation,
        )
    }
}

#[cfg(test)]
mod tests {
    use std::collections::{HashMap, HashSet};
    use std::path::Path;

    use super::{
        OverlapConflict, find_overlapping_tasks, parse_body_owner_role, predicted_files,
        role_name_seed_tags, split_acyclic_blocking_ids,
    };
    use crate::team::config::RoleType;
    use crate::team::hierarchy::MemberInstance;
    use crate::team::standup::MemberState;
    use crate::team::task_loop::{
        current_worktree_branch, engineer_base_branch_name, setup_engineer_worktree,
    };
    use crate::team::test_support::{
        TestDaemonBuilder, architect_member, engineer_member, git_ok, git_stdout, init_git_repo,
        manager_member, write_open_task_file, write_owned_task_file,
    };

    fn write_task_with_priority(project_root: &Path, id: u32, title: &str, priority: &str) {
        let tasks_dir = project_root
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        std::fs::write(
            tasks_dir.join(format!("{id:03}-{title}.md")),
            format!(
                "---\nid: {id}\ntitle: {title}\nstatus: todo\npriority: {priority}\nclass: standard\n---\n\nTask.\n"
            ),
        )
        .unwrap();
    }

    fn write_task_with_deps(project_root: &Path, id: u32, title: &str, depends_on: &[u32]) {
        let tasks_dir = project_root
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        let mut content = format!("---\nid: {id}\ntitle: {title}\nstatus: todo\npriority: high\n");
        if !depends_on.is_empty() {
            content.push_str("depends_on:\n");
            for dep in depends_on {
                content.push_str(&format!("  - {dep}\n"));
            }
        }
        content.push_str("class: standard\n---\n\nTask.\n");
        std::fs::write(tasks_dir.join(format!("{id:03}-{title}.md")), content).unwrap();
    }

    fn write_task_with_body(
        project_root: &Path,
        id: u32,
        title: &str,
        status: &str,
        claimed_by: Option<&str>,
        body: &str,
    ) {
        let tasks_dir = project_root
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        let mut content =
            format!("---\nid: {id}\ntitle: {title}\nstatus: {status}\npriority: high\n");
        if let Some(claimed_by) = claimed_by {
            content.push_str(&format!("claimed_by: {claimed_by}\n"));
        }
        content.push_str("class: standard\n---\n\n");
        content.push_str(body);
        content.push('\n');
        std::fs::write(tasks_dir.join(format!("{id:03}-{title}.md")), content).unwrap();
    }

    fn write_task_with_files(
        project_root: &Path,
        id: u32,
        title: &str,
        status: &str,
        claimed_by: Option<&str>,
        files: &[&str],
        body: &str,
    ) {
        let tasks_dir = project_root
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        let mut content =
            format!("---\nid: {id}\ntitle: {title}\nstatus: {status}\npriority: high\n");
        if let Some(claimed_by) = claimed_by {
            content.push_str(&format!("claimed_by: {claimed_by}\n"));
        }
        if !files.is_empty() {
            content.push_str("files:\n");
            for file in files {
                content.push_str(&format!("  - {file}\n"));
            }
        }
        content.push_str("class: standard\n---\n\n");
        content.push_str(body);
        content.push('\n');
        std::fs::write(tasks_dir.join(format!("{id:03}-{title}.md")), content).unwrap();
    }

    fn write_task_with_assignee(project_root: &Path, id: u32, title: &str, assignee: &str) {
        let tasks_dir = project_root
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        std::fs::write(
            tasks_dir.join(format!("{id:03}-{title}.md")),
            format!(
                "---\nid: {id}\ntitle: {title}\nstatus: todo\npriority: high\nassignee: {assignee}\nclass: standard\n---\n\nTask.\n"
            ),
        )
        .unwrap();
    }

    fn write_task_with_tags(project_root: &Path, id: u32, title: &str, tags: &[&str]) {
        let tasks_dir = project_root
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        let tags_block = tags
            .iter()
            .map(|tag| format!("  - {tag}"))
            .collect::<Vec<_>>()
            .join("\n");
        std::fs::write(
            tasks_dir.join(format!("{id:03}-{title}.md")),
            format!(
                "---\nid: {id}\ntitle: {title}\nstatus: todo\npriority: high\ntags:\n{tags_block}\nclass: standard\n---\n\nTask.\n"
            ),
        )
        .unwrap();
    }

    fn write_task_with_tags_and_body(
        project_root: &Path,
        id: u32,
        title: &str,
        tags: &[&str],
        body: &str,
    ) {
        let tasks_dir = project_root
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        let tags_block = tags
            .iter()
            .map(|tag| format!("  - {tag}"))
            .collect::<Vec<_>>()
            .join("\n");
        std::fs::write(
            tasks_dir.join(format!("{id:03}-{title}.md")),
            format!(
                "---\nid: {id}\ntitle: {title}\nstatus: todo\npriority: high\ntags:\n{tags_block}\nclass: standard\n---\n\n{body}\n"
            ),
        )
        .unwrap();
    }

    fn write_bench_test_team_config(project_root: &Path, engineer_instances: u32) {
        let team_dir = project_root.join(".batty").join("team_config");
        std::fs::create_dir_all(&team_dir).unwrap();
        std::fs::write(
            team_dir.join("team.yaml"),
            format!(
                "name: test\nagent: codex\nroles:\n  - name: eng\n    role_type: engineer\n    instances: {engineer_instances}\n"
            ),
        )
        .unwrap();
    }

    // -- idle_engineer_names tests --

    #[test]
    fn idle_engineers_returns_only_idle() {
        let tmp = tempfile::tempdir().unwrap();
        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
                engineer_member("eng-2", Some("mgr"), false),
                engineer_member("eng-3", Some("mgr"), false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Idle),
                ("eng-2".to_string(), MemberState::Working),
                ("eng-3".to_string(), MemberState::Idle),
            ]))
            .build();
        // eng-2 is Working WITH an active task — should be excluded
        daemon.active_tasks.insert("eng-2".to_string(), 42);

        let idle = daemon.idle_engineer_names();
        assert_eq!(idle, vec!["eng-1", "eng-3"]);
    }

    #[test]
    fn idle_engineers_empty_when_all_working_with_tasks() {
        let tmp = tempfile::tempdir().unwrap();
        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .states(HashMap::from([("eng-1".to_string(), MemberState::Working)]))
            .build();
        daemon.active_tasks.insert("eng-1".to_string(), 10);

        assert!(daemon.idle_engineer_names().is_empty());
    }

    #[test]
    fn idle_engineers_includes_working_without_active_task() {
        let tmp = tempfile::tempdir().unwrap();
        let daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
                engineer_member("eng-2", Some("mgr"), false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Working),
                ("eng-2".to_string(), MemberState::Idle),
            ]))
            .build();
        // eng-1 is Working but has NO active task — should be dispatchable
        let idle = daemon.idle_engineer_names();
        assert_eq!(idle, vec!["eng-1", "eng-2"]);
    }

    #[test]
    fn idle_engineers_working_no_task_mixed_with_working_with_task() {
        let tmp = tempfile::tempdir().unwrap();
        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
                engineer_member("eng-2", Some("mgr"), false),
                engineer_member("eng-3", Some("mgr"), false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Working),
                ("eng-2".to_string(), MemberState::Working),
                ("eng-3".to_string(), MemberState::Idle),
            ]))
            .build();
        // eng-1 has an active task, eng-2 does not
        daemon.active_tasks.insert("eng-1".to_string(), 50);

        let idle = daemon.idle_engineer_names();
        assert_eq!(idle, vec!["eng-2", "eng-3"]);
    }

    #[test]
    fn idle_engineers_excludes_managers() {
        let tmp = tempfile::tempdir().unwrap();
        let daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .states(HashMap::from([
                ("mgr".to_string(), MemberState::Idle),
                ("eng-1".to_string(), MemberState::Idle),
            ]))
            .build();

        let idle = daemon.idle_engineer_names();
        assert_eq!(idle, vec!["eng-1"]);
    }

    // -- next_dispatch_task tests --

    #[test]
    fn next_task_picks_highest_priority() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_priority(tmp.path(), 10, "low-pri", "low");
        write_task_with_priority(tmp.path(), 11, "critical-pri", "critical");
        write_task_with_priority(tmp.path(), 12, "medium-pri", "medium");

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 11, "should pick the critical-priority task");
    }

    #[test]
    fn next_task_breaks_ties_by_id() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_priority(tmp.path(), 20, "second", "high");
        write_task_with_priority(tmp.path(), 10, "first", "high");

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 10, "should pick lower id when priority is equal");
    }

    #[test]
    fn next_task_skips_claimed_tasks() {
        let tmp = tempfile::tempdir().unwrap();
        write_owned_task_file(tmp.path(), 10, "claimed-task", "todo", "eng-2");
        write_open_task_file(tmp.path(), 11, "open-task", "todo");

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 11, "should skip claimed task");
    }

    #[test]
    fn next_task_skips_done_tasks() {
        let tmp = tempfile::tempdir().unwrap();
        write_open_task_file(tmp.path(), 10, "done-task", "done");
        write_open_task_file(tmp.path(), 11, "open-task", "todo");

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 11);
    }

    #[test]
    fn next_task_skips_already_queued() {
        let tmp = tempfile::tempdir().unwrap();
        write_open_task_file(tmp.path(), 10, "queued", "todo");
        write_open_task_file(tmp.path(), 11, "available", "todo");

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let queued: HashSet<u32> = [10].into();
        let task = daemon
            .test_next_dispatch_task(&board_dir, &queued)
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 11, "should skip task already in queue set");
    }

    #[test]
    fn next_task_skips_blocked_dependencies() {
        let tmp = tempfile::tempdir().unwrap();
        // Task 10 depends on task 9, which is in-progress (not done)
        write_open_task_file(tmp.path(), 9, "dep-task", "in-progress");
        write_task_with_deps(tmp.path(), 10, "blocked-task", &[9]);
        write_open_task_file(tmp.path(), 11, "free-task", "todo");

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 11, "should skip task with unmet dependency");
    }

    #[test]
    fn next_task_skips_unmet_body_dependency() {
        let tmp = tempfile::tempdir().unwrap();
        write_open_task_file(tmp.path(), 9, "dep-task", "in-progress");
        write_task_with_body(
            tmp.path(),
            10,
            "body-blocked",
            "todo",
            None,
            "Blocked on: #9",
        );
        write_open_task_file(tmp.path(), 11, "free-task", "todo");

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 11, "should skip task with unmet body dependency");
    }

    #[test]
    fn next_task_allows_met_body_dependency() {
        let tmp = tempfile::tempdir().unwrap();
        write_open_task_file(tmp.path(), 9, "dep-done", "done");
        write_task_with_body(
            tmp.path(),
            10,
            "body-unblocked",
            "todo",
            None,
            "Blocked on: #9",
        );

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 10, "should allow satisfied body dependency");
    }

    #[test]
    fn next_task_skips_body_blocker_without_task_id() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            10,
            "body-blocked",
            "todo",
            None,
            "Blocked on: provider-console token",
        );
        write_open_task_file(tmp.path(), 11, "free-task", "todo");

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 11, "should skip non-task-id body blocker");
    }

    #[test]
    fn next_task_skips_blocked_or_reworked_parent_dependencies() {
        let tmp = tempfile::tempdir().unwrap();
        write_open_task_file(tmp.path(), 8, "blocked-parent", "blocked");
        write_open_task_file(tmp.path(), 9, "rework-parent", "rework");
        write_task_with_deps(tmp.path(), 10, "blocked-child", &[8]);
        write_task_with_deps(tmp.path(), 11, "rework-child", &[9]);
        write_open_task_file(tmp.path(), 12, "free-task", "todo");

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(
            task.id, 12,
            "should only dispatch work whose parents are done or archived"
        );
    }

    #[test]
    fn next_task_allows_met_dependencies() {
        let tmp = tempfile::tempdir().unwrap();
        write_open_task_file(tmp.path(), 9, "dep-done", "done");
        write_task_with_deps(tmp.path(), 10, "unblocked", &[9]);

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 10, "should pick task with satisfied dependency");
    }

    #[test]
    fn next_task_returns_none_when_empty() {
        let tmp = tempfile::tempdir().unwrap();
        let tasks_dir = tmp
            .path()
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        assert!(
            daemon
                .test_next_dispatch_task(&board_dir, &HashSet::new())
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn next_task_accepts_backlog_status() {
        let tmp = tempfile::tempdir().unwrap();
        write_open_task_file(tmp.path(), 10, "backlog-task", "backlog");

        let daemon = TestDaemonBuilder::new(tmp.path()).build();
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let task = daemon
            .test_next_dispatch_task(&board_dir, &HashSet::new())
            .unwrap()
            .unwrap();
        assert_eq!(task.id, 10, "backlog status should be dispatchable");
    }

    // -- process_dispatch_queue pruning tests --

    #[test]
    fn process_queue_prunes_entry_for_done_task_even_when_engineer_not_idle() {
        use super::DispatchQueueEntry;
        let tmp = tempfile::tempdir().unwrap();
        // Task is done and claimed by someone else.
        write_owned_task_file(tmp.path(), 10, "finished", "done", "other-eng");

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .states(HashMap::from([("eng-1".to_string(), MemberState::Working)]))
            .build();

        daemon.dispatch_queue.push(DispatchQueueEntry {
            engineer: "eng-1".to_string(),
            task_id: 10,
            task_title: "finished".to_string(),
            queued_at: 0,
            validation_failures: 0,
            last_failure: None,
        });

        daemon.process_dispatch_queue().unwrap();
        assert!(
            daemon.dispatch_queue.is_empty(),
            "entry for done task should be pruned even when engineer is Working"
        );
    }

    #[test]
    fn process_queue_retains_valid_entry_for_non_idle_engineer() {
        use super::DispatchQueueEntry;
        let tmp = tempfile::tempdir().unwrap();
        // Task is still todo and unclaimed — valid for dispatch.
        write_open_task_file(tmp.path(), 10, "pending-work", "todo");

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .states(HashMap::from([("eng-1".to_string(), MemberState::Working)]))
            .build();

        daemon.dispatch_queue.push(DispatchQueueEntry {
            engineer: "eng-1".to_string(),
            task_id: 10,
            task_title: "pending-work".to_string(),
            queued_at: 0,
            validation_failures: 0,
            last_failure: None,
        });

        daemon.process_dispatch_queue().unwrap();
        assert_eq!(
            daemon.dispatch_queue.len(),
            1,
            "entry for valid todo task should be retained while engineer is Working"
        );
    }

    #[test]
    fn process_queue_blocks_dirty_worktree_instead_of_auto_preserving() {
        use super::DispatchQueueEntry;

        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp, "dispatch-preserve-reset");
        write_open_task_file(&repo, 42, "dispatch-reset", "todo");

        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-1");
        let team_config_dir = repo.join(".batty").join("team_config");
        let base_branch = engineer_base_branch_name("eng-1");
        setup_engineer_worktree(&repo, &worktree_dir, &base_branch, &team_config_dir).unwrap();
        git_ok(&worktree_dir, &["checkout", "-b", "eng-1/41"]);
        std::fs::write(worktree_dir.join("tracked.txt"), "tracked dispatch work\n").unwrap();
        git_ok(&worktree_dir, &["add", "tracked.txt"]);
        std::fs::write(
            worktree_dir.join("untracked.txt"),
            "untracked dispatch work\n",
        )
        .unwrap();

        let mut daemon = TestDaemonBuilder::new(repo.as_path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), true),
            ])
            .board(crate::team::config::BoardConfig {
                dispatch_stabilization_delay_secs: 0,
                ..crate::team::config::BoardConfig::default()
            })
            .states(HashMap::from([("eng-1".to_string(), MemberState::Idle)]))
            .build();
        daemon.idle_started_at.insert(
            "eng-1".to_string(),
            std::time::Instant::now() - std::time::Duration::from_secs(1),
        );
        daemon.dispatch_queue.push(DispatchQueueEntry {
            engineer: "eng-1".to_string(),
            task_id: 42,
            task_title: "dispatch-reset".to_string(),
            queued_at: 0,
            validation_failures: 0,
            last_failure: None,
        });

        daemon.process_dispatch_queue().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].validation_failures, 2);
        assert!(
            daemon.dispatch_queue[0]
                .last_failure
                .as_deref()
                .unwrap_or("")
                .contains("could not safely auto-save dirty worktree")
        );
        assert_eq!(current_worktree_branch(&worktree_dir).unwrap(), "eng-1/41");
        let status = git_stdout(&worktree_dir, &["status", "--short"]);
        assert!(
            status.contains("A  tracked.txt"),
            "tracked work should remain staged instead of being auto-preserved: {status}"
        );
        assert!(
            status.contains("?? untracked.txt"),
            "untracked work should remain untouched instead of being auto-preserved: {status}"
        );
        assert!(
            git_stdout(&repo, &["branch", "--list", "eng-1/41"]).contains("eng-1/41"),
            "dirty task branch should remain in place for manual recovery"
        );
    }

    #[test]
    fn process_queue_blocks_dirty_worktree_when_preserve_fails() {
        use super::DispatchQueueEntry;

        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp, "dispatch-preserve-blocked");
        write_open_task_file(&repo, 42, "dispatch-reset", "todo");

        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-1");
        let team_config_dir = repo.join(".batty").join("team_config");
        let base_branch = engineer_base_branch_name("eng-1");
        setup_engineer_worktree(&repo, &worktree_dir, &base_branch, &team_config_dir).unwrap();
        git_ok(&worktree_dir, &["checkout", "-b", "eng-1/41"]);
        std::fs::write(worktree_dir.join("tracked.txt"), "tracked dispatch work\n").unwrap();
        git_ok(&worktree_dir, &["add", "tracked.txt"]);
        std::fs::write(worktree_dir.join("unstaged.txt"), "leave unstaged\n").unwrap();
        let git_dir =
            std::path::PathBuf::from(git_stdout(&worktree_dir, &["rev-parse", "--git-dir"]));
        let git_dir = if git_dir.is_absolute() {
            git_dir
        } else {
            worktree_dir.join(git_dir)
        };
        std::fs::write(git_dir.join("index.lock"), "locked\n").unwrap();

        let mut daemon = TestDaemonBuilder::new(repo.as_path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), true),
            ])
            .board(crate::team::config::BoardConfig {
                dispatch_stabilization_delay_secs: 0,
                ..crate::team::config::BoardConfig::default()
            })
            .states(HashMap::from([("eng-1".to_string(), MemberState::Idle)]))
            .build();
        daemon.idle_started_at.insert(
            "eng-1".to_string(),
            std::time::Instant::now() - std::time::Duration::from_secs(1),
        );
        daemon.dispatch_queue.push(DispatchQueueEntry {
            engineer: "eng-1".to_string(),
            task_id: 42,
            task_title: "dispatch-reset".to_string(),
            queued_at: 0,
            validation_failures: 0,
            last_failure: None,
        });

        daemon.process_dispatch_queue().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].validation_failures, 2);
        assert!(
            daemon.dispatch_queue[0]
                .last_failure
                .as_deref()
                .unwrap_or("")
                .contains("could not safely auto-save dirty worktree")
        );
        assert_eq!(current_worktree_branch(&worktree_dir).unwrap(), "eng-1/41");
        let status = git_stdout(&worktree_dir, &["status", "--short"]);
        assert!(
            status.contains("A  tracked.txt"),
            "pre-existing staged work should remain staged: {status}"
        );
        assert!(
            status.contains("?? unstaged.txt"),
            "idle dispatch recovery must not stage new files: {status}"
        );
    }

    fn write_blocked_task(project_root: &Path, id: u32, title: &str, block_reason: &str) {
        let tasks_dir = project_root
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        // kanban-md --block writes `blocked: true` + `block_reason: "..."`.
        // Regression guard against the old Option<String> deserializer which
        // silently dropped the boolean shape and let dispatch see the task
        // as runnable.
        let content = format!(
            "---\nid: {id}\ntitle: {title}\nstatus: todo\npriority: high\nblocked: true\nblock_reason: \"{block_reason}\"\nclass: standard\n---\n\nBody.\n"
        );
        std::fs::write(tasks_dir.join(format!("{id:03}-{title}.md")), content).unwrap();
    }

    #[test]
    fn enqueue_dispatch_candidates_skips_kanban_md_blocked_tasks() {
        // Regression for #589: kanban-md --block writes `blocked: true` +
        // `block_reason: "..."`, which used to deserialize to None because
        // the Task struct's blocked field was Option<String>. Dispatch then
        // treated the task as runnable and auto-assigned it to benched
        // engineers. The fix is an untagged deserializer that accepts both
        // boolean and string shapes and routes `block_reason` into `blocked`.
        let tmp = tempfile::tempdir().unwrap();
        write_blocked_task(
            tmp.path(),
            30,
            "kanban-md-blocked",
            "Deferred per architect",
        );
        write_task_with_body(
            tmp.path(),
            31,
            "runnable-candidate",
            "todo",
            None,
            "Touch src/team/telemetry_db.rs only.",
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .states(HashMap::from([("eng-1".to_string(), MemberState::Idle)]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(
            daemon.dispatch_queue[0].task_id, 31,
            "blocked task #30 must be filtered out; only the runnable #31 should be queued"
        );
    }

    #[test]
    fn enqueue_dispatch_candidates_skips_tasks_assigned_to_non_engineer() {
        // #682: a task whose `assignee:` frontmatter points at a manager/
        // architect is a message for that member's inbox, not a dispatch
        // candidate. Previously these tasks were repeatedly handed to
        // engineers who immediately rejected them — burning engineer
        // context re-reading huge bodies on every dispatch tick.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_assignee(tmp.path(), 40, "pm-intake", "mgr");
        write_task_with_body(
            tmp.path(),
            41,
            "engineer-candidate",
            "todo",
            None,
            "Touch src/team/telemetry_db.rs only.",
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .states(HashMap::from([("eng-1".to_string(), MemberState::Idle)]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(
            daemon.dispatch_queue[0].task_id, 41,
            "non-engineer-assigned task #40 must be filtered out; only #41 should dispatch"
        );
    }

    #[test]
    fn enqueue_dispatch_candidates_routes_engineer_assigned_task_to_named_engineer() {
        // #682: when `assignee:` names an engineer, dispatch must route the
        // task only to that engineer — even when other idle engineers could
        // otherwise take it. Previously the dispatcher ignored the field
        // and the task went to whichever idle engineer won the ranking.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_assignee(tmp.path(), 50, "for-eng-2", "eng-2");

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
                engineer_member("eng-2", Some("mgr"), false),
                engineer_member("eng-3", Some("mgr"), false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Idle),
                ("eng-2".to_string(), MemberState::Idle),
                ("eng-3".to_string(), MemberState::Idle),
            ]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].task_id, 50);
        assert_eq!(
            daemon.dispatch_queue[0].engineer, "eng-2",
            "task with `assignee: eng-2` must dispatch to eng-2, not a peer"
        );
    }

    #[test]
    fn enqueue_dispatch_candidates_waits_when_assigned_engineer_busy() {
        // #682: if the named engineer is not idle, leave the task in the
        // pool rather than re-routing to a peer. Reassigning defeats the
        // purpose of the `assignee:` hint.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_assignee(tmp.path(), 60, "for-eng-2", "eng-2");

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
                engineer_member("eng-2", Some("mgr"), false),
            ])
            .states(HashMap::from([("eng-1".to_string(), MemberState::Idle)]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert!(
            daemon.dispatch_queue.is_empty(),
            "task must remain undispatched while named engineer is unavailable"
        );
    }

    #[test]
    fn enqueue_dispatch_candidates_skips_tasks_whose_body_owner_names_non_engineer() {
        // #703: a task whose body reads `**Owner:** maya-lead` names the
        // architect as the owner — it belongs on Maya's plate, not an
        // engineer's dispatch queue. `assignee:` frontmatter is unset
        // (#682 filter passes it through), but under v0.11.41
        // `rank_dispatch_engineers` splices "maya-lead" into task tags
        // for scoring, no engineer has that role → tag_overlap scores 0
        // for all and the task lands on whichever engineer wins
        // tiebreakers, who immediately refuses. Observed batty-marketing
        // 2026-04-17 10:18:42 UTC: task #542 (STRATEGY — Star-velocity
        // Tue 04-21 mid-window gate decision, `**Owner:** maya-lead
        // (this task)`) dispatched to sam-designer-1-1, burning a claim
        // + refuse turn on a strategy task sam had no context for.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            70,
            "strategy-star-velocity-gate",
            "todo",
            None,
            "**Owner:** maya-lead (this task), with input from jordan-pm \
             and kai-devrel. Mid-window gate decision for launch.\n",
        );
        // Control task so the test also proves the filter is surgical —
        // body-owner filter must not drop unrelated dispatchable work.
        write_task_with_body(
            tmp.path(),
            71,
            "engineer-candidate",
            "todo",
            None,
            "Touch src/team/telemetry_db.rs only.\n",
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                architect_member("maya-lead"),
                manager_member("jordan-pm", Some("maya-lead")),
                engineer_member("eng-1", Some("jordan-pm"), false),
            ])
            .states(HashMap::from([("eng-1".to_string(), MemberState::Idle)]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(
            daemon.dispatch_queue[0].task_id, 71,
            "task with `**Owner:** maya-lead` body must be filtered out \
             because maya-lead is a non-engineer member; only #71 should dispatch"
        );
    }

    #[test]
    fn enqueue_dispatch_candidates_allows_body_owner_when_it_names_an_engineer() {
        // #703 surgical check: filter must only drop tasks whose body-owner
        // names a non-engineer. A task explicitly routed to an engineer via
        // `Owner: <engineer-role>` must still reach the dispatch queue — if
        // the filter over-applies, all routing-cued tasks disappear.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            80,
            "engineer-owned",
            "todo",
            None,
            "- Owner: priya-writer drafts; review by peer.\n",
        );

        let priya = MemberInstance {
            name: "priya-writer-1-1".to_string(),
            role_name: "priya-writer".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            reports_to: Some("jordan-pm".to_string()),
            use_worktrees: false,
            ..MemberInstance::default()
        };

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                architect_member("maya-lead"),
                manager_member("jordan-pm", Some("maya-lead")),
                priya,
            ])
            .states(HashMap::from([(
                "priya-writer-1-1".to_string(),
                MemberState::Idle,
            )]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].task_id, 80);
        assert_eq!(daemon.dispatch_queue[0].engineer, "priya-writer-1-1");
    }

    #[test]
    fn enqueue_dispatch_candidates_waits_when_body_owner_engineer_busy() {
        // #705: a task whose body names a specific engineer role must
        // wait for that engineer to become idle rather than cascading to
        // a peer who will refuse. Mirrors #682's assignee-busy behavior
        // for body-owner routing.
        //
        // Observed batty-marketing 2026-04-17 11:04:36 UTC: task #549
        // (body `- Route: dispatch to priya-writer.`) dispatched to
        // kai-devrel-1-1 while priya-writer-1-1 was working on another
        // task; kai released it (third cascade bounce after kai at
        // 09:13 and alex at 10:18). Before this gate the task pinged
        // between idle peers, each burning a claim+refuse turn on work
        // that was not theirs to do.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            90,
            "twir-submission",
            "todo",
            None,
            "- Route: dispatch to priya-writer.\n",
        );

        let priya = MemberInstance {
            name: "priya-writer-1-1".to_string(),
            role_name: "priya-writer".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            reports_to: Some("jordan-pm".to_string()),
            use_worktrees: false,
            ..MemberInstance::default()
        };
        let kai = MemberInstance {
            name: "kai-devrel-1-1".to_string(),
            role_name: "kai-devrel".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            reports_to: Some("jordan-pm".to_string()),
            use_worktrees: false,
            ..MemberInstance::default()
        };

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                architect_member("maya-lead"),
                manager_member("jordan-pm", Some("maya-lead")),
                priya,
                kai,
            ])
            // priya (named body owner) is not idle — only kai is. The
            // dispatcher must NOT fall back to kai; it must wait for
            // priya. Omitting priya from `states` makes her ineligible
            // via `idle_engineer_names`, matching the field observation
            // where priya-writer-1-1 was `working` on another task.
            .states(HashMap::from([(
                "kai-devrel-1-1".to_string(),
                MemberState::Idle,
            )]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert!(
            daemon.dispatch_queue.is_empty(),
            "task must remain undispatched while named body-owner engineer is busy; \
             got {:?}",
            daemon.dispatch_queue
        );
    }

    #[test]
    fn enqueue_dispatch_candidates_dispatches_to_body_owner_when_idle_even_with_other_idle_peers() {
        // #705 surgical check: the body-owner gate must only restrict
        // eligibility to engineers carrying the named role; if that
        // engineer IS idle, the task must dispatch to them — not to
        // some other idle peer.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            91,
            "twir-submission",
            "todo",
            None,
            "- Route: dispatch to priya-writer.\n",
        );

        let priya = MemberInstance {
            name: "priya-writer-1-1".to_string(),
            role_name: "priya-writer".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            reports_to: Some("jordan-pm".to_string()),
            use_worktrees: false,
            ..MemberInstance::default()
        };
        let kai = MemberInstance {
            name: "kai-devrel-1-1".to_string(),
            role_name: "kai-devrel".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            reports_to: Some("jordan-pm".to_string()),
            use_worktrees: false,
            ..MemberInstance::default()
        };

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                architect_member("maya-lead"),
                manager_member("jordan-pm", Some("maya-lead")),
                priya,
                kai,
            ])
            .states(HashMap::from([
                ("priya-writer-1-1".to_string(), MemberState::Idle),
                ("kai-devrel-1-1".to_string(), MemberState::Idle),
            ]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].task_id, 91);
        assert_eq!(
            daemon.dispatch_queue[0].engineer, "priya-writer-1-1",
            "body-owner `priya-writer` must win over idle peer kai-devrel-1-1"
        );
    }

    #[test]
    fn dispatch_queue_seeds_role_name_into_domain_tags_for_tag_routing() {
        // #691: fresh engineer profiles have empty domain_tags until the
        // engineer completes tagged tasks. Without seeding, a task tagged
        // with a role_name (e.g. `kai-devrel`) scores 0 tag-overlap for
        // every idle engineer and the dispatcher falls back to alphabetical
        // order. Observed in batty-marketing: task #550 tagged `kai-devrel`
        // was dispatched to sam-designer, who immediately released it.
        //
        // After seeding, kai-devrel-1-1's profile has the `kai-devrel` tag,
        // matching the task's tag for a non-zero score that beats peers
        // whose role_name does not match.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_tags(tmp.path(), 90, "role-tagged", &["kai-devrel", "engagement"]);

        let member_with_role = |name: &str, role_name: &str| MemberInstance {
            name: name.to_string(),
            role_name: role_name.to_string(),
            role_type: RoleType::Engineer,
            agent: Some("codex".to_string()),
            reports_to: Some("mgr".to_string()),
            use_worktrees: false,
            ..MemberInstance::default()
        };

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                member_with_role("alex-dev-1-1", "alex-dev"),
                member_with_role("kai-devrel-1-1", "kai-devrel"),
                member_with_role("sam-designer-1-1", "sam-designer"),
            ])
            .states(HashMap::from([
                ("alex-dev-1-1".to_string(), MemberState::Idle),
                ("kai-devrel-1-1".to_string(), MemberState::Idle),
                ("sam-designer-1-1".to_string(), MemberState::Idle),
            ]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].task_id, 90);
        assert_eq!(
            daemon.dispatch_queue[0].engineer, "kai-devrel-1-1",
            "task tagged with a role_name must prefer the engineer whose role_name matches, \
             not fall back to the first alphabetical peer"
        );
    }

    #[test]
    fn dispatch_queue_seeds_role_name_word_family_variants() {
        // #708: #691 seeded the full role_name (`sam-designer`) but tasks
        // tagged with natural-language tokens (`design`, `writing`, `designer`)
        // still scored 0 tag-overlap because exact-string match rejects them.
        // Observed 2026-04-17 12:27:30 UTC in batty-marketing: task #572
        // (tagged `[pillar-a, design, thread-a, hero, card-1]`) was dispatched
        // to alex-dev-1-1 instead of sam-designer-1-1; alex released within
        // 38 s. Fix: also seed the hyphen-suffix token and `-er` stem/gerund
        // variants so `design` matches the engineer whose role_name is
        // `sam-designer`.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_tags(
            tmp.path(),
            572,
            "Card-1 peak-day hero",
            &["pillar-a", "design", "thread-a", "hero", "card-1"],
        );

        let member_with_role = |name: &str, role_name: &str| MemberInstance {
            name: name.to_string(),
            role_name: role_name.to_string(),
            role_type: RoleType::Engineer,
            agent: Some("codex".to_string()),
            reports_to: Some("mgr".to_string()),
            use_worktrees: false,
            ..MemberInstance::default()
        };

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                member_with_role("alex-dev-1-1", "alex-dev"),
                member_with_role("kai-devrel-1-1", "kai-devrel"),
                member_with_role("sam-designer-1-1", "sam-designer"),
                member_with_role("priya-writer-1-1", "priya-writer"),
            ])
            .states(HashMap::from([
                ("alex-dev-1-1".to_string(), MemberState::Idle),
                ("kai-devrel-1-1".to_string(), MemberState::Idle),
                ("sam-designer-1-1".to_string(), MemberState::Idle),
                ("priya-writer-1-1".to_string(), MemberState::Idle),
            ]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].task_id, 572);
        assert_eq!(
            daemon.dispatch_queue[0].engineer, "sam-designer-1-1",
            "task tagged `design` must prefer sam-designer over alphabetical \
             alex-dev; role_name `sam-designer` seeds `designer` + `design` + \
             `designing` into domain_tags"
        );
    }

    #[test]
    fn role_name_seed_tags_covers_hyphen_suffix_and_er_variants() {
        assert_eq!(
            role_name_seed_tags("sam-designer"),
            vec![
                "sam-designer".to_string(),
                "designer".to_string(),
                "design".to_string(),
                "designing".to_string(),
            ]
        );
        assert_eq!(
            role_name_seed_tags("priya-writer"),
            vec![
                "priya-writer".to_string(),
                "writer".to_string(),
                "writ".to_string(),
                "writing".to_string(),
            ]
        );
        assert_eq!(
            role_name_seed_tags("alex-dev"),
            vec!["alex-dev".to_string(), "dev".to_string()]
        );
        assert_eq!(
            role_name_seed_tags("kai-devrel"),
            vec!["kai-devrel".to_string(), "devrel".to_string()]
        );
        // No hyphen → no suffix token; only self-seed.
        assert_eq!(
            role_name_seed_tags("architect"),
            vec!["architect".to_string()]
        );
    }

    #[test]
    fn dispatch_honors_explicit_body_owner_when_tags_do_not_match_role() {
        // #695: architects author tasks with thematic frontmatter tags
        // (`content`, `writing`, `x`, `pillar-b`) but name the owner role
        // in prose ("Owner: priya-writer drafts; kai-devrel schedules").
        // Under #691 role-name seeding alone, no tag overlaps any
        // role_name, so `tag_overlap` is zero for every engineer and
        // dispatch falls through to scoring tiebreakers — observed in
        // batty-marketing: task #553 (body "Owner: priya-writer drafts…")
        // was dispatched to sam-designer-1-1.
        //
        // `parse_body_owner_role` + tag-splice in `rank_dispatch_engineers`
        // synthesizes a role_name tag from the body so the matching
        // engineer wins over peers whose role_name does not match.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_tags_and_body(
            tmp.path(),
            91,
            "body-owner-routing",
            &["content", "pillar-b", "x", "writing"],
            "- Owner: priya-writer drafts; kai-devrel schedules\n\
             - Acceptance: ...\n",
        );

        let member_with_role = |name: &str, role_name: &str| MemberInstance {
            name: name.to_string(),
            role_name: role_name.to_string(),
            role_type: RoleType::Engineer,
            agent: Some("codex".to_string()),
            reports_to: Some("mgr".to_string()),
            use_worktrees: false,
            ..MemberInstance::default()
        };

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                member_with_role("kai-devrel-1-1", "kai-devrel"),
                member_with_role("priya-writer-1-1", "priya-writer"),
                member_with_role("sam-designer-1-1", "sam-designer"),
            ])
            .states(HashMap::from([
                ("kai-devrel-1-1".to_string(), MemberState::Idle),
                ("priya-writer-1-1".to_string(), MemberState::Idle),
                ("sam-designer-1-1".to_string(), MemberState::Idle),
            ]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].task_id, 91);
        assert_eq!(
            daemon.dispatch_queue[0].engineer, "priya-writer-1-1",
            "task whose body says `Owner: priya-writer` must route to \
             priya-writer-1-1 even when frontmatter tags are thematic \
             (content/pillar-b/x/writing) and match no role_name"
        );
    }

    #[test]
    fn split_acyclic_blocking_ids_rejects_reverse_edge() {
        // #696: #553 already depends_on [#554]. If dispatch overlap wants
        // to persist #554 depends_on [#553], that edge closes a cycle
        // and auto_doctor will WARN on every subsequent tick without
        // healing — leaving both tasks stuck. The splitter must
        // reject the cycle-forming edge and keep the rest.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_deps(tmp.path(), 553, "pillar-b-thread", &[554]);
        write_task_with_deps(tmp.path(), 554, "dev-to-article", &[]);
        write_task_with_deps(tmp.path(), 560, "unrelated", &[]);
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let (safe, rejected) = split_acyclic_blocking_ids(&board_dir, 554, &[553, 560]).unwrap();

        assert_eq!(
            rejected,
            vec![553],
            "edge #554 -> #553 must be rejected — #553 already depends on #554"
        );
        assert_eq!(
            safe,
            vec![560],
            "unrelated #554 -> #560 edge stays — no cycle"
        );
    }

    #[test]
    fn split_acyclic_blocking_ids_rejects_transitive_cycle() {
        // Chain: #A depends_on #B depends_on #C. Persisting
        // #C depends_on #A would close a 3-node cycle through #B.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_deps(tmp.path(), 100, "a", &[101]);
        write_task_with_deps(tmp.path(), 101, "b", &[102]);
        write_task_with_deps(tmp.path(), 102, "c", &[]);
        let board_dir = tmp.path().join(".batty").join("team_config").join("board");

        let (safe, rejected) = split_acyclic_blocking_ids(&board_dir, 102, &[100]).unwrap();

        assert!(safe.is_empty(), "#102 -> #100 reaches #102 via #101");
        assert_eq!(rejected, vec![100]);
    }

    #[test]
    fn parse_body_owner_role_extracts_first_role_from_prose() {
        // Sanity: the parser tolerates markdown (`-`, `**`) and stops at
        // the first whitespace/punctuation after the role token.
        assert_eq!(
            parse_body_owner_role("- Owner: priya-writer drafts; kai-devrel schedules"),
            Some("priya-writer".to_string())
        );
        assert_eq!(
            parse_body_owner_role("Owner: **kai-devrel** (explicit)."),
            Some("kai-devrel".to_string())
        );
        // Require at least one hyphen to reject degenerate cases like
        // "Owner: TBD" that would otherwise extract "tbd" and either
        // match nothing (harmless) or collide with a future role.
        assert_eq!(parse_body_owner_role("Owner: TBD"), None);
        assert_eq!(parse_body_owner_role("- Owner: tbd\n"), None);
        assert_eq!(parse_body_owner_role("Body with no owner line."), None);
    }

    #[test]
    fn parse_body_owner_role_finds_owner_inside_prose_preamble() {
        // #699 regression: Maya-style round headers wrap the Owner declaration
        // inside a prose bold block, e.g. batty-marketing task #518 body
        // begins `**Round-8 task from maya-lead. Owner: alex-dev. Skeptic-…`.
        // The old parser required `Owner:` at line start (after trimming `-`
        // / `*`) and missed these, so the tasks were round-robined to the
        // wrong role. The new parser searches within the line at word
        // boundaries.
        assert_eq!(
            parse_body_owner_role(
                "**Round-8 task from maya-lead. Owner: alex-dev. Skeptic-defuser artifact for Article A.**"
            ),
            Some("alex-dev".to_string())
        );
        assert_eq!(
            parse_body_owner_role(
                "**Round-11 task from maya-lead. Owner: alex-dev. Daily metrics snapshot.**"
            ),
            Some("alex-dev".to_string())
        );
        // Guard against word-boundary bypass: `CoOwner: rogue-role` must not
        // be picked up in place of a later legitimate `Owner: real-role`.
        assert_eq!(
            parse_body_owner_role("CoOwner: rogue-role. Owner: real-role handles it."),
            Some("real-role".to_string())
        );
    }

    #[test]
    fn parse_body_owner_role_finds_routing_cues_from_jordan_style_bodies() {
        // #700 regression: jordan-pm-authored tasks use richer routing syntax
        // than literal `Owner: <role>`. Observed 2026-04-17 09:13:35 UTC in
        // batty-marketing — three-task wave misdispatched because the old
        // parser never found `Owner:` as a substring with a role right after.
        //
        // #547 body: `**Owner routing**: content/submission task — route to
        // priya-writer for draft, kai-devrel for PR submission ...`
        assert_eq!(
            parse_body_owner_role(
                "**Owner routing**: content/submission task — route to priya-writer for draft, kai-devrel for PR submission (he holds the posting/publishing lane)."
            ),
            Some("priya-writer".to_string())
        );
        // #548 body: `**Owner routing**: Research + strategic-analysis task,
        // role-flexible. Primary: priya-writer (narrative audit lens) OR
        // kai-devrel ... NOT Sam, NOT Alex.`
        //
        // This covers three guards at once: `strategic-analysis`,
        // `role-flexible`, and `narrative-audit` all live on
        // `NON_ROLE_HYPHEN_TOKENS`, so `Primary:` correctly skips them and
        // returns the real role `priya-writer`.
        assert_eq!(
            parse_body_owner_role(
                "**Owner routing**: Research + strategic-analysis task, role-flexible. Primary: priya-writer (narrative audit lens) OR kai-devrel (community/conversion lens). NOT Sam (not visual), NOT Alex."
            ),
            Some("priya-writer".to_string())
        );
        // #549 body: `- Route: dispatch to priya-writer.`
        assert_eq!(
            parse_body_owner_role("- Route: dispatch to priya-writer."),
            Some("priya-writer".to_string())
        );
        // jordan-pm's manual inbox-workaround format, used while the bug was
        // live: `OWNER: alex-dev-1-1 (explicit ...)`. The trailing `-1-1`
        // must not trip the parser — `first_role_token_after` stops at the
        // first hyphen-role token, which is `alex-dev-1-1` (all lowercase /
        // hyphen / digits? no, digits break the class → returns `alex-dev`).
        assert_eq!(
            parse_body_owner_role("OWNER: alex-dev-1-1 (explicit per Maya directive)."),
            Some("alex-dev".to_string())
        );
        // Inline `assign to <role>` prose cue.
        assert_eq!(
            parse_body_owner_role("Please assign to kai-devrel for the release post."),
            Some("kai-devrel".to_string())
        );
    }

    #[test]
    fn enqueue_dispatch_candidates_skips_recently_orphan_rescued_task() {
        // #684: after the orphan-rescue path moves an in-progress task back
        // to todo (e.g. the claimer released/parked), dispatch must wait
        // for the cooldown to elapse before re-dispatching. Previously the
        // task bounced straight to a peer within the same tick.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            70,
            "rescued-task",
            "todo",
            None,
            "Touch src/team/telemetry_db.rs only.",
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .states(HashMap::from([("eng-1".to_string(), MemberState::Idle)]))
            .build();
        daemon.record_task_rescue(70);

        daemon.enqueue_dispatch_candidates().unwrap();

        assert!(
            daemon.dispatch_queue.is_empty(),
            "task under orphan-rescue cooldown must stay off the dispatch queue"
        );
    }

    #[test]
    fn enqueue_dispatch_candidates_includes_task_after_orphan_rescue_cooldown_expires() {
        // #684: once the cooldown passes the task becomes eligible again.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            71,
            "expired-rescue",
            "todo",
            None,
            "Touch src/team/telemetry_db.rs only.",
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .states(HashMap::from([("eng-1".to_string(), MemberState::Idle)]))
            .build();
        // Force cooldown to 0 so the task is immediately eligible.
        daemon.config.team_config.board.orphan_rescue_cooldown_secs = 0;
        daemon.record_task_rescue(71);

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].task_id, 71);
    }

    #[test]
    fn record_task_rescue_grows_cooldown_exponentially_on_repeat() {
        // #686: repeated rescues of the same task should widen the
        // effective dispatch-cooldown window (1×, 2×, 4×, 8×, 16× cap)
        // so the engine doesn't cascade a task across every idle peer
        // every base window.
        let tmp = tempfile::tempdir().unwrap();
        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .build();

        daemon.record_task_rescue(99);
        let first = daemon.recently_rescued_tasks[&99];
        assert_eq!(first.count, 1);

        // Rescue again while still active — count must grow.
        daemon.record_task_rescue(99);
        let second = daemon.recently_rescued_tasks[&99];
        assert_eq!(second.count, 2);

        daemon.record_task_rescue(99);
        let third = daemon.recently_rescued_tasks[&99];
        assert_eq!(third.count, 3);

        // Effective cooldown doubles each rescue up to the 16× cap.
        let base = std::time::Duration::from_secs(100);
        assert_eq!(
            third.effective_cooldown(base),
            std::time::Duration::from_secs(400)
        );

        // Simulate many rescues — multiplier caps at 16×.
        for _ in 0..10 {
            daemon.record_task_rescue(99);
        }
        let capped = daemon.recently_rescued_tasks[&99];
        assert_eq!(
            capped.effective_cooldown(base),
            std::time::Duration::from_secs(1600)
        );
    }

    #[test]
    fn record_task_rescue_grows_count_across_dispatch_gate_openings() {
        // #689 regression: the dispatch cooldown gates dispatch, so the
        // next rescue always fires *after* the effective_cooldown has
        // elapsed. The old `is_active`-gated growth check therefore never
        // triggered in production — count reset to 1 on every rescue and
        // the exponential backoff flatlined at base. Here we simulate
        // that by backdating `last_rescued_at` past the dispatch gate
        // but still within the cascade-observation window.
        use std::time::Duration;
        let tmp = tempfile::tempdir().unwrap();
        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .build();
        // 100s base cooldown → count=1 effective_cooldown=100s, cascade_window=200s.
        daemon.config.team_config.board.orphan_rescue_cooldown_secs = 100;

        daemon.record_task_rescue(42);
        // Simulate 150s elapsed — past the 100s dispatch gate (so a
        // re-dispatch happens and the rescued engineer quickly releases)
        // but still inside the 200s cascade window.
        let record = daemon.recently_rescued_tasks.get_mut(&42).unwrap();
        record.last_rescued_at = std::time::Instant::now() - Duration::from_secs(150);

        daemon.record_task_rescue(42);
        let grown = daemon.recently_rescued_tasks[&42];
        assert_eq!(
            grown.count, 2,
            "rescue after gate-open but inside cascade window must grow the counter"
        );

        // Same scenario but past the cascade window → counter resets.
        daemon.record_task_rescue(77);
        let record = daemon.recently_rescued_tasks.get_mut(&77).unwrap();
        // cascade_window at count=1 is 2× base = 200s; go well past it.
        record.last_rescued_at = std::time::Instant::now() - Duration::from_secs(500);

        daemon.record_task_rescue(77);
        let reset = daemon.recently_rescued_tasks[&77];
        assert_eq!(
            reset.count, 1,
            "rescue past cascade window is a new cascade — counter resets"
        );
    }

    #[test]
    fn release_exclusion_blocks_redispatch_to_same_engineer_until_window_expires() {
        // #697: after an engineer releases a task (claim cleared), the
        // dispatcher must not immediately re-queue the same task back to
        // the same engineer. Observed in batty-marketing: task #555 was
        // repeatedly re-dispatched to kai-devrel-1-1 at base-cooldown
        // intervals after they parked it with an upstream-block note.
        use std::time::Duration;
        let tmp = tempfile::tempdir().unwrap();
        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .build();
        daemon
            .config
            .team_config
            .board
            .dispatch_release_exclusion_secs = 300;

        assert!(!daemon.is_release_excluded(42, "eng-1"));
        daemon.record_task_release_by(42, "eng-1");
        assert!(
            daemon.is_release_excluded(42, "eng-1"),
            "engineer who just released task must be excluded"
        );
        // A different engineer should NOT be excluded.
        assert!(
            !daemon.is_release_excluded(42, "eng-2"),
            "exclusion is per-(task, engineer), not global"
        );
        // A different task must not be excluded for the same engineer.
        assert!(
            !daemon.is_release_excluded(99, "eng-1"),
            "exclusion must not leak to other tasks"
        );

        // Backdate the entry past the configured window — exclusion expires.
        daemon.recently_released_by.insert(
            (42, "eng-1".to_string()),
            crate::team::daemon::ReleaseRecord {
                last_released_at: std::time::Instant::now() - Duration::from_secs(400),
                count: 1,
            },
        );
        assert!(
            !daemon.is_release_excluded(42, "eng-1"),
            "exclusion must expire after dispatch_release_exclusion_secs"
        );
    }

    #[test]
    fn record_task_release_by_grows_exclusion_exponentially_on_repeat() {
        // #698: a parked task (owner awaiting human coordination) re-dispatched
        // and re-released inside the cascade-observation window must climb
        // the exponential backoff so the next exclusion lasts longer than
        // the base window. Without this, the hourly dispatch→release loop
        // observed on batty_marketing with task #597 (alex-dev awaiting
        // Akim's Saturday ping) wastes ~14 engineer turns per weekend.
        use std::time::Duration;
        let tmp = tempfile::tempdir().unwrap();
        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
            ])
            .build();
        daemon
            .config
            .team_config
            .board
            .dispatch_release_exclusion_secs = 300;

        // First release — count=1, base window (300s).
        daemon.record_task_release_by(555, "eng-1");
        assert_eq!(
            daemon.recently_released_by[&(555, "eng-1".to_string())].count,
            1
        );

        // Simulate a second release after the base window expires but still
        // inside the cascade-observation window (2×300s = 600s). Count grows.
        daemon.recently_released_by.insert(
            (555, "eng-1".to_string()),
            crate::team::daemon::ReleaseRecord {
                last_released_at: std::time::Instant::now() - Duration::from_secs(310),
                count: 1,
            },
        );
        daemon.record_task_release_by(555, "eng-1");
        let after_second = daemon.recently_released_by[&(555, "eng-1".to_string())];
        assert_eq!(
            after_second.count, 2,
            "second release within cascade window must grow the counter"
        );
        // Effective window is now 2× base = 600s — exclusion still holds
        // at 0s elapsed.
        assert!(daemon.is_release_excluded(555, "eng-1"));

        // A release well past the cascade window resets the counter to 1.
        // At count=3 the effective window is 4× base (1200s) and the
        // cascade window is 2× that (2400s). 3000s elapsed is unambiguously
        // past the cascade window.
        daemon.recently_released_by.insert(
            (555, "eng-1".to_string()),
            crate::team::daemon::ReleaseRecord {
                last_released_at: std::time::Instant::now() - Duration::from_secs(3_000),
                count: 3,
            },
        );
        daemon.record_task_release_by(555, "eng-1");
        let after_reset = daemon.recently_released_by[&(555, "eng-1".to_string())];
        assert_eq!(
            after_reset.count, 1,
            "release past cascade window is a new cascade — counter resets"
        );
    }

    #[test]
    fn enqueue_dispatch_candidates_defers_release_excluded_task_and_dispatches_next_priority() {
        // Regression for dispatch-starvation observed on batty_marketing
        // 2026-04-17: top-priority task was body-owner-restricted to a
        // single engineer who was inside the 1h #697 release-exclusion
        // window. The pre-fix `enqueue_dispatch_candidates` called
        // `break` when its ranked_engineers `find` came up empty, which
        // stalled the whole queue — idle peers whose own tasks were
        // dispatchable never got them. Fix: defer the blocked task via
        // `eligibility_excluded_task_ids` and `continue` so the loop
        // advances to the next candidate.
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            101,
            "ci-badge-repair",
            "todo",
            None,
            "- Owner: alex-dev. Prefer CI job repair over badge swap.\n",
        );
        write_task_with_body(
            tmp.path(),
            102,
            "twir-submission",
            "todo",
            None,
            "- Route: dispatch to priya-writer.\n",
        );

        let alex = MemberInstance {
            name: "alex-dev-1-1".to_string(),
            role_name: "alex-dev".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            reports_to: Some("mgr".to_string()),
            use_worktrees: false,
            ..MemberInstance::default()
        };
        let priya = MemberInstance {
            name: "priya-writer-1-1".to_string(),
            role_name: "priya-writer".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            reports_to: Some("mgr".to_string()),
            use_worktrees: false,
            ..MemberInstance::default()
        };

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![manager_member("mgr", None), alex, priya])
            .states(HashMap::from([
                ("alex-dev-1-1".to_string(), MemberState::Idle),
                ("priya-writer-1-1".to_string(), MemberState::Idle),
            ]))
            .build();

        // Alex just released task #101 — still inside the exclusion window.
        daemon.record_task_release_by(101, "alex-dev-1-1");
        assert!(daemon.is_release_excluded(101, "alex-dev-1-1"));

        daemon.enqueue_dispatch_candidates().unwrap();

        // #101 must be deferred (alex is the only eligible engineer and is
        // release-excluded) and #102 must still dispatch to priya. Before
        // the fix, the outer loop `break`'d on #101 and left priya idle.
        assert_eq!(
            daemon.dispatch_queue.len(),
            1,
            "release-excluded top-priority task must not starve lower candidates"
        );
        assert_eq!(daemon.dispatch_queue[0].task_id, 102);
        assert_eq!(daemon.dispatch_queue[0].engineer, "priya-writer-1-1");
    }

    #[test]
    fn enqueue_dispatch_candidates_serializes_overlapping_task_and_enqueues_non_overlapping_task() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            10,
            "active-overlap",
            "in-progress",
            Some("eng-2"),
            "Modify src/team/dispatch/queue.rs and tests.",
        );
        write_task_with_body(
            tmp.path(),
            11,
            "candidate-overlap",
            "todo",
            None,
            "Update src/team/dispatch/queue.rs overlap logic.",
        );
        write_task_with_body(
            tmp.path(),
            12,
            "candidate-safe",
            "todo",
            None,
            "Touch src/team/telemetry_db.rs only.",
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
                engineer_member("eng-2", Some("mgr"), false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Idle),
                ("eng-2".to_string(), MemberState::Working),
            ]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].task_id, 12);

        let task = crate::task::Task::from_file(
            &tmp.path()
                .join(".batty")
                .join("team_config")
                .join("board")
                .join("tasks")
                .join("011-candidate-overlap.md"),
        )
        .unwrap();
        assert_eq!(task.depends_on, vec![10]);

        let events =
            crate::team::events::read_events(&crate::team::team_events_path(tmp.path())).unwrap();
        assert!(events.iter().any(|event| {
            event.event == "dispatch_overlap_skipped" && event.task.as_deref() == Some("11")
        }));
    }

    #[test]
    fn enqueue_dispatch_candidates_leaves_serialized_task_unqueued_when_no_safe_alternative_exists()
    {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            20,
            "active-overlap",
            "in-progress",
            Some("eng-2"),
            "Modify src/team/dispatch/mod.rs.",
        );
        write_task_with_body(
            tmp.path(),
            21,
            "candidate-overlap",
            "todo",
            None,
            "Also update src/team/dispatch/mod.rs for prevention logic.",
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
                engineer_member("eng-2", Some("mgr"), false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Idle),
                ("eng-2".to_string(), MemberState::Working),
            ]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();

        assert!(daemon.dispatch_queue.is_empty());
        let task = crate::task::Task::from_file(
            &tmp.path()
                .join(".batty")
                .join("team_config")
                .join("board")
                .join("tasks")
                .join("021-candidate-overlap.md"),
        )
        .unwrap();
        assert_eq!(task.depends_on, vec![20]);
    }

    #[test]
    fn test_predicted_files_from_body() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            30,
            "body-path",
            "todo",
            None,
            "Update src/team/daemon.rs to add the new check.",
        );
        let task = crate::task::Task::from_file(
            &tmp.path()
                .join(".batty")
                .join("team_config")
                .join("board")
                .join("tasks")
                .join("030-body-path.md"),
        )
        .unwrap();

        assert!(predicted_files(&task, tmp.path()).contains(&"src/team/daemon.rs".to_string()));
    }

    #[test]
    fn test_predicted_files_from_frontmatter_files() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_files(
            tmp.path(),
            31,
            "frontmatter-paths",
            "todo",
            None,
            &["src/app.rs", "src/**/*.rs"],
            "Use the declared file list.",
        );
        let task = crate::task::Task::from_file(
            &tmp.path()
                .join(".batty")
                .join("team_config")
                .join("board")
                .join("tasks")
                .join("031-frontmatter-paths.md"),
        )
        .unwrap();

        let predicted = predicted_files(&task, tmp.path());
        assert!(predicted.contains(&"src/**/*.rs".to_string()));
        assert!(predicted.contains(&"src/app.rs".to_string()));
    }

    #[test]
    fn test_find_overlapping_with_frontmatter_glob() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_files(
            tmp.path(),
            40,
            "active-glob",
            "in-progress",
            Some("eng-2"),
            &["src/**/*.rs"],
            "Broad source lock.",
        );
        write_task_with_body(
            tmp.path(),
            41,
            "candidate-file",
            "todo",
            None,
            "Change src/app.rs only.",
        );

        let mut active = None;
        let mut candidate = None;
        for task in crate::task::load_tasks_from_dir(
            &tmp.path()
                .join(".batty")
                .join("team_config")
                .join("board")
                .join("tasks"),
        )
        .unwrap()
        {
            match task.id {
                40 => active = Some(task),
                41 => candidate = Some(task),
                _ => {}
            }
        }

        let conflicts = find_overlapping_tasks(
            &candidate.expect("candidate task"),
            &[active.expect("active task")],
            tmp.path(),
        );
        assert_eq!(conflicts.len(), 1);
        assert_eq!(
            conflicts[0].conflicting_files,
            vec!["src/app.rs".to_string()]
        );
    }

    #[test]
    fn test_predicted_files_from_tags() {
        let tmp = tempfile::tempdir().unwrap();
        let tasks_dir = tmp
            .path()
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        std::fs::write(
            tasks_dir.join("001-prior-shim.md"),
            "---\nid: 1\ntitle: prior shim\nstatus: done\npriority: high\nclaimed_by: eng-2\ntags:\n  - shim\nchanged_paths:\n  - src/shim/runtime.rs\nclass: standard\n---\n\nEarlier shim work.\n",
        )
        .unwrap();
        std::fs::write(
            tasks_dir.join("031-new-shim.md"),
            "---\nid: 31\ntitle: new shim\nstatus: todo\npriority: high\ntags:\n  - shim\nclass: standard\n---\n\nNo explicit paths.\n",
        )
        .unwrap();
        let task = crate::task::Task::from_file(&tasks_dir.join("031-new-shim.md")).unwrap();

        assert!(predicted_files(&task, tmp.path()).contains(&"src/shim/runtime.rs".to_string()));
    }

    #[test]
    fn test_predicted_files_empty() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            32,
            "no-hints",
            "todo",
            None,
            "No file hints here.",
        );
        let task = crate::task::Task::from_file(
            &tmp.path()
                .join(".batty")
                .join("team_config")
                .join("board")
                .join("tasks")
                .join("032-no-hints.md"),
        )
        .unwrap();

        assert!(predicted_files(&task, tmp.path()).is_empty());
    }

    #[test]
    fn test_find_overlapping_no_conflict() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            40,
            "candidate",
            "todo",
            None,
            "Edit src/team/daemon.rs.",
        );
        write_task_with_body(
            tmp.path(),
            41,
            "active",
            "in-progress",
            Some("eng-2"),
            "Edit src/team/status.rs.",
        );
        let tasks_dir = tmp
            .path()
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        let candidate = crate::task::Task::from_file(&tasks_dir.join("040-candidate.md")).unwrap();
        let active = crate::task::Task::from_file(&tasks_dir.join("041-active.md")).unwrap();

        assert!(find_overlapping_tasks(&candidate, &[active], tmp.path()).is_empty());
    }

    #[test]
    fn test_find_overlapping_with_conflict() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            42,
            "candidate",
            "todo",
            None,
            "Edit src/team/daemon.rs.",
        );
        write_task_with_body(
            tmp.path(),
            43,
            "active",
            "in-progress",
            Some("eng-2"),
            "Edit src/team/daemon.rs too.",
        );
        let tasks_dir = tmp
            .path()
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        let candidate = crate::task::Task::from_file(&tasks_dir.join("042-candidate.md")).unwrap();
        let active = crate::task::Task::from_file(&tasks_dir.join("043-active.md")).unwrap();

        let conflicts = find_overlapping_tasks(&candidate, &[active], tmp.path());
        assert_eq!(conflicts.len(), 1);
        assert_eq!(conflicts[0].task_id, "43");
    }

    #[test]
    fn test_find_overlapping_multiple_conflicts() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            44,
            "candidate",
            "todo",
            None,
            "Edit src/team/daemon.rs.",
        );
        write_task_with_body(
            tmp.path(),
            45,
            "active-a",
            "in-progress",
            Some("eng-2"),
            "Edit src/team/daemon.rs too.",
        );
        write_task_with_body(
            tmp.path(),
            46,
            "active-b",
            "in-progress",
            Some("eng-3"),
            "Also touch src/team/daemon.rs.",
        );
        let tasks_dir = tmp
            .path()
            .join(".batty")
            .join("team_config")
            .join("board")
            .join("tasks");
        let candidate = crate::task::Task::from_file(&tasks_dir.join("044-candidate.md")).unwrap();
        let active_a = crate::task::Task::from_file(&tasks_dir.join("045-active-a.md")).unwrap();
        let active_b = crate::task::Task::from_file(&tasks_dir.join("046-active-b.md")).unwrap();

        let conflicts = find_overlapping_tasks(&candidate, &[active_a, active_b], tmp.path());
        assert_eq!(conflicts.len(), 2);
    }

    #[test]
    fn test_dispatch_skips_overlapping_candidate() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            50,
            "active",
            "in-progress",
            Some("eng-2"),
            "Edit src/team/daemon.rs.",
        );
        write_task_with_body(
            tmp.path(),
            51,
            "overlap",
            "todo",
            None,
            "Edit src/team/daemon.rs.",
        );
        write_task_with_body(
            tmp.path(),
            52,
            "safe",
            "todo",
            None,
            "Edit src/team/status.rs.",
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
                engineer_member("eng-2", Some("mgr"), false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Idle),
                ("eng-2".to_string(), MemberState::Working),
            ]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();
        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].task_id, 52);
    }

    #[test]
    fn enqueue_dispatch_candidates_skips_benched_engineer() {
        let tmp = tempfile::tempdir().unwrap();
        write_open_task_file(tmp.path(), 70, "dispatchable", "todo");
        write_bench_test_team_config(tmp.path(), 2);

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                engineer_member("eng-1", None, false),
                engineer_member("eng-2", None, false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Idle),
                ("eng-2".to_string(), MemberState::Idle),
            ]))
            .build();

        crate::team::bench::bench_engineer(tmp.path(), "eng-1", Some("session end")).unwrap();

        daemon.enqueue_dispatch_candidates().unwrap();
        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].engineer, "eng-2");
        assert_eq!(daemon.dispatch_queue[0].task_id, 70);
    }

    /// #674 defect 2: dispatch selection must skip engineers whose backend
    /// is parked (quota_exhausted with future retry_at), regardless of
    /// cached health state. Without this gate, the stall-timer reclaim
    /// cascade rotates tasks across every quota-blocked engineer every
    /// 15 minutes, producing board churn with zero real progress.
    #[test]
    fn enqueue_dispatch_candidates_skips_quota_parked_engineer() {
        let tmp = tempfile::tempdir().unwrap();
        write_open_task_file(tmp.path(), 674, "dispatchable", "todo");

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                engineer_member("eng-1", None, false),
                engineer_member("eng-2", None, false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Idle),
                ("eng-2".to_string(), MemberState::Idle),
            ]))
            .build();

        // eng-1 is quota-parked via future retry_at (32h out). Its cached
        // health value is intentionally left as the default (Healthy) to
        // prove the retry_at deadline alone is sufficient to park it.
        let future_deadline = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or(std::time::Duration::ZERO)
            .as_secs()
            + 32 * 3600;
        daemon
            .backend_quota_retry_at
            .insert("eng-1".to_string(), future_deadline);

        daemon.enqueue_dispatch_candidates().unwrap();
        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(
            daemon.dispatch_queue[0].engineer, "eng-2",
            "quota-parked engineer must be skipped even if cached health is Healthy"
        );
        assert_eq!(daemon.dispatch_queue[0].task_id, 674);
    }

    #[test]
    fn unbench_restores_dispatch_eligibility() {
        let tmp = tempfile::tempdir().unwrap();
        write_open_task_file(tmp.path(), 71, "dispatchable", "todo");
        write_bench_test_team_config(tmp.path(), 2);

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                engineer_member("eng-1", None, false),
                engineer_member("eng-2", None, false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Idle),
                ("eng-2".to_string(), MemberState::Idle),
            ]))
            .build();

        crate::team::bench::bench_engineer(tmp.path(), "eng-1", Some("pause")).unwrap();
        daemon.enqueue_dispatch_candidates().unwrap();
        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].engineer, "eng-2");

        crate::team::bench::unbench_engineer(tmp.path(), "eng-1").unwrap();
        daemon.dispatch_queue.clear();
        daemon.enqueue_dispatch_candidates().unwrap();
        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].engineer, "eng-1");
        assert_eq!(daemon.dispatch_queue[0].task_id, 71);
    }

    #[test]
    fn test_dispatch_all_overlap_picks_least_conflict() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            60,
            "active-daemon",
            "in-progress",
            Some("eng-2"),
            "Edit src/team/daemon.rs.",
        );
        write_task_with_body(
            tmp.path(),
            61,
            "active-status",
            "in-progress",
            Some("eng-3"),
            "Edit src/team/status.rs.",
        );
        write_task_with_body(
            tmp.path(),
            62,
            "overlap-both",
            "todo",
            None,
            "Edit src/team/daemon.rs and src/team/status.rs.",
        );
        write_task_with_body(
            tmp.path(),
            63,
            "overlap-one",
            "todo",
            None,
            "Edit src/team/daemon.rs only.",
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), false),
                engineer_member("eng-2", Some("mgr"), false),
                engineer_member("eng-3", Some("mgr"), false),
            ])
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Idle),
                ("eng-2".to_string(), MemberState::Working),
                ("eng-3".to_string(), MemberState::Working),
            ]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();
        assert!(daemon.dispatch_queue.is_empty());
        let task = crate::task::Task::from_file(
            &tmp.path()
                .join(".batty")
                .join("team_config")
                .join("board")
                .join("tasks")
                .join("063-overlap-one.md"),
        )
        .unwrap();
        assert_eq!(task.depends_on, vec![60]);
    }

    #[test]
    fn test_overlap_conflict_struct_fields() {
        let conflict = OverlapConflict {
            task_id: "42".to_string(),
            conflicting_files: vec!["src/team/daemon.rs".to_string()],
            in_progress_engineer: "eng-2".to_string(),
        };
        assert_eq!(conflict.task_id, "42");
        assert_eq!(conflict.conflicting_files, vec!["src/team/daemon.rs"]);
        assert_eq!(conflict.in_progress_engineer, "eng-2");
    }

    #[test]
    fn file_level_locks_defer_then_release_overlapping_work_for_worktree_teams() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_with_body(
            tmp.path(),
            60,
            "active-overlap",
            "in-progress",
            Some("eng-2"),
            "Modify src/app.rs only.",
        );
        write_task_with_files(
            tmp.path(),
            61,
            "waiting-overlap",
            "todo",
            None,
            &["src/*.rs"],
            "Lock should wait without rewriting dependencies.",
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member("mgr", None),
                engineer_member("eng-1", Some("mgr"), true),
                engineer_member("eng-2", Some("mgr"), true),
            ])
            .workflow_policy(crate::team::config::WorkflowPolicy {
                file_level_locks: true,
                ..crate::team::config::WorkflowPolicy::default()
            })
            .states(HashMap::from([
                ("eng-1".to_string(), MemberState::Idle),
                ("eng-2".to_string(), MemberState::Working),
            ]))
            .build();

        daemon.enqueue_dispatch_candidates().unwrap();
        assert!(daemon.dispatch_queue.is_empty());

        let waiting_task = crate::task::Task::from_file(
            &tmp.path()
                .join(".batty")
                .join("team_config")
                .join("board")
                .join("tasks")
                .join("061-waiting-overlap.md"),
        )
        .unwrap();
        assert!(
            waiting_task.depends_on.is_empty(),
            "file-level wait should not rewrite task dependencies"
        );

        write_task_with_body(
            tmp.path(),
            60,
            "active-overlap",
            "done",
            Some("eng-2"),
            "Modify src/app.rs only.",
        );

        daemon.enqueue_dispatch_candidates().unwrap();
        assert_eq!(daemon.dispatch_queue.len(), 1);
        assert_eq!(daemon.dispatch_queue[0].task_id, 61);
    }
}