codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
//! Model-facing Workflow runner over the live sub-agent runtime.
//!
//! The JS VM stays in `codewhale-workflow-js`; this module supplies the TUI
//! driver that turns each `task(...)` call into a real `SubAgentManager` spawn.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};

use async_trait::async_trait;
use codewhale_workflow::{
    AgentType, BranchResult, BranchSpec, BudgetSpec, ControlNodeKind, ControlNodeResult,
    FleetRoleMap, GateKind, GateOn, GateOutcome, GateSpec, GateState, GateStatusLine,
    HandoffArtifact, LaneGateBoard, LeafResult, LeafSpec, ReduceSpec, SequenceSpec, TaskMode,
    WorkflowExecution as IrWorkflowExecution, WorkflowMemoUsage, WorkflowNode,
    WorkflowRunStatus as IrWorkflowRunStatus, WorkflowSpec, WorkflowUsage,
    compile_javascript_workflow, compile_typescript_workflow, leaf_wants_worktree,
    resolve_workflow_agent,
};
use codewhale_workflow_js::{
    BudgetSnapshot, DriverError, ProgressEvent, SpawnedTask, TaskCompletion, TaskRequest,
    WORKFLOW_MAX_CONCURRENT, WorkflowDriver, WorkflowRunCancel, WorkflowVm,
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc, oneshot};
use uuid::Uuid;

use crate::core::events::Event;
use crate::tools::spec::{
    ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
    optional_bool, optional_str, optional_u64,
};
use crate::tools::subagent::{
    SharedSubAgentManager, SubAgentCompletion, SubAgentManager, SubAgentResult, SubAgentRuntime,
    SubAgentStatus, WorkflowTaskSpawnIdentity, WorkflowTaskSpawnMetadata, spawn_workflow_task,
};
use crate::tools::verifier::run_workflow_completion_gates;
use crate::tools::workflow_plan_approval::{
    WorkflowPlanApprovalReceipt, analyze_workflow_plan_approval_with_config, analyze_workflow_spec,
    workflow_approval_requirement_for,
};
use crate::utils::spawn_supervised;
use crate::work_graph::{
    CancelOutcome, EvidenceKind, EvidenceRef, OperationIntent, OperationObservation,
    OperationOwnerSnapshot, OwnerState, SharedWorkRuntime,
};

/// Keep promoted artifacts compact without clipping ordinary evidence reports.
/// A 900-character cap cut six-line source receipts in half during live Fleet
/// acceptance, so downstream roles could not evaluate evidence the host had
/// already approved.
const WORKFLOW_HANDOFF_MAX_CHARS: usize = 4_000;

/// Model-facing run-record payloads carry only the newest events; the full
/// stream persists per-event in `.codewhale/workflow-runs.jsonl` (#2974).
const WORKFLOW_RESULT_EVENTS_TAIL: usize = 50;
/// Bounded tail for free-form progress lines in model-facing payloads.
const WORKFLOW_RESULT_PROGRESS_TAIL: usize = 20;
/// Bounded tail for rejected child dispatches in the model-facing payload.
/// The durable run journal retains the complete failure ledger.
const WORKFLOW_RESULT_DISPATCH_FAILURES_TAIL: usize = 12;
/// Per-field cap for one model-facing dispatch-failure receipt.
const WORKFLOW_RESULT_DISPATCH_FAILURE_FIELD_MAX_CHARS: usize = 320;
/// Char cap for the VM `result` / `verification` values in model-facing
/// payloads (matches the handoff compaction budget); oversized values
/// collapse to a preview plus a journal pointer.
const WORKFLOW_RESULT_VALUE_MAX_CHARS: usize = 4_000;
/// Char cap per leaf output preview inside the model-facing execution
/// receipt; full child output stays retrievable via the worker ledger and
/// the journal.
const WORKFLOW_RESULT_LEAF_OUTPUT_MAX_CHARS: usize = 500;
/// Stated upper bound for a bounded model-facing run-record payload; the
/// payload tests assert every `start`/`run`/`status` result stays below it.
const WORKFLOW_RESULT_MAX_CHARS: usize = 24_000;
/// In-memory (and snapshot) event retention per run: only the newest events
/// are kept; older ones remain in the per-event journal lines (#2974).
const WORKFLOW_RUN_EVENTS_MAX_RETAINED: usize = 1_000;

#[derive(Clone)]
pub struct WorkflowTool {
    manager: SharedSubAgentManager,
    runtime: SubAgentRuntime,
    approval_decision: &'static str,
}

impl WorkflowTool {
    #[must_use]
    pub fn new(manager: SharedSubAgentManager, runtime: SubAgentRuntime) -> Self {
        Self {
            manager,
            runtime,
            approval_decision: "approved",
        }
    }

    /// Mark execution as approved by the user's explicit `workflow run`
    /// command rather than by an Engine tool-call approval gate.
    #[must_use]
    pub(crate) fn with_explicit_cli_approval(mut self) -> Self {
        self.approval_decision = "approved_explicit_cli_command";
        self
    }
}

type SharedWorkflowRuns = Arc<Mutex<HashMap<String, WorkflowRunRecord>>>;
type SharedWorkflowControllers = Arc<Mutex<HashMap<String, Arc<WorkflowRunController>>>>;
type SharedWorkflowLifecycles = Arc<Mutex<HashMap<String, WorkflowWorkLifecycle>>>;

#[derive(Clone)]
struct WorkflowWorkLifecycle {
    work: SharedWorkRuntime,
    session_id: String,
    external: String,
}

impl WorkflowWorkLifecycle {
    fn register(
        context: &ToolContext,
        run_id: &str,
        title: &str,
    ) -> Result<Option<Self>, ToolError> {
        let Some(work) = context.runtime.work.clone() else {
            return Ok(None);
        };
        let lifecycle = Self {
            work,
            session_id: context.state_namespace.clone(),
            external: format!("workflow:{run_id}"),
        };
        lifecycle
            .work
            .register_operation(
                &lifecycle.session_id,
                OperationIntent::new(
                    lifecycle.external.clone(),
                    title,
                    true,
                    "workflow",
                    format!("workflow:{run_id}:start"),
                ),
            )
            .map_err(ToolError::execution_failed)?;
        Ok(Some(lifecycle))
    }

    fn for_bound(context: &ToolContext, run_id: &str) -> Option<Self> {
        let work = context.runtime.work.clone()?;
        let external = format!("workflow:{run_id}");
        work.has_operation_binding(Some(&context.state_namespace), &external)
            .then(|| Self {
                work,
                session_id: context.state_namespace.clone(),
                external,
            })
    }

    fn reconcile_record(&self, record: &WorkflowRunRecord) -> Result<bool, String> {
        let output = record.result.as_ref().and_then(|result| {
            serde_json::to_vec(result).ok().and_then(|bytes| {
                EvidenceRef::new(
                    EvidenceKind::Receipt {
                        owner: "workflow".to_string(),
                    },
                    format!("workflow:{}:result", record.run_id),
                    Some(u64::try_from(bytes.len()).unwrap_or(u64::MAX)),
                    false,
                )
                .ok()
            })
        });
        let state = match record.status {
            WorkflowRunStatus::Running => OwnerState::Running,
            // Degraded still finished and produced output; the run record and
            // report carry the dropped-slot truth.
            WorkflowRunStatus::Completed | WorkflowRunStatus::Degraded => OwnerState::Completed,
            WorkflowRunStatus::Failed => OwnerState::Failed,
            WorkflowRunStatus::Cancelled => OwnerState::Cancelled,
        };
        let mut snapshot = OperationOwnerSnapshot::new(
            self.external.clone(),
            state,
            record.lifecycle_seq,
            i64::try_from(record.completed_at_ms.unwrap_or(record.started_at_ms))
                .unwrap_or(i64::MAX),
        );
        if let Some(output) = output {
            snapshot = snapshot.with_output(output);
        }
        self.work.reconcile_operation(&self.session_id, snapshot)
    }

    fn reconcile_cancel(&self, outcome: CancelOutcome) -> Result<bool, String> {
        self.work.reconcile_observation(
            &self.session_id,
            &self.external,
            OperationObservation::CancelUpdate {
                outcome,
                at: i64::try_from(now_ms()).unwrap_or(i64::MAX),
            },
        )
    }

    fn reconcile_spawn_failure(&self) {
        let _ = self.work.reconcile_operation(
            &self.session_id,
            OperationOwnerSnapshot::new(
                self.external.clone(),
                OwnerState::Failed,
                1,
                i64::try_from(now_ms()).unwrap_or(i64::MAX),
            ),
        );
    }

    fn reconcile_missing(&self) {
        let _ = self.work.reconcile_observation(
            &self.session_id,
            &self.external,
            OperationObservation::OwnerMissing {
                checked_at: i64::try_from(now_ms()).unwrap_or(i64::MAX),
            },
        );
    }
}

struct WorkflowRunController {
    driver: Arc<SubAgentWorkflowDriver>,
    vm_cancel: WorkflowRunCancel,
    run_handle: Mutex<Option<tokio::task::JoinHandle<()>>>,
}

impl WorkflowRunController {
    fn new(driver: Arc<SubAgentWorkflowDriver>, vm_cancel: WorkflowRunCancel) -> Self {
        Self {
            driver,
            vm_cancel,
            run_handle: Mutex::new(None),
        }
    }

    fn set_run_handle(&self, handle: tokio::task::JoinHandle<()>) {
        if let Ok(mut guard) = self.run_handle.lock() {
            *guard = Some(handle);
        }
    }

    fn cancel(&self) {
        self.vm_cancel.cancel();
        self.driver.finalize_running_tasks_cancelled();
        self.driver.force_cancel_all();
        if let Ok(mut guard) = self.run_handle.lock()
            && let Some(handle) = guard.take()
        {
            handle.abort();
        }
    }
}

#[derive(Debug, Clone, Serialize)]
struct WorkflowRunSummary {
    run_id: String,
    status: WorkflowRunStatus,
    lifecycle_seq: u64,
    started_at_ms: u64,
    completed_at_ms: Option<u64>,
    source_path: Option<PathBuf>,
    workflow_id: Option<String>,
    workflow_goal: Option<String>,
    token_budget: Option<u64>,
    child_count: usize,
    schema_error_count: usize,
    dispatch_failure_count: usize,
    progress_count: usize,
    last_progress: Option<String>,
    event_count: usize,
    last_event_type: Option<String>,
    leaf_count: usize,
    branch_count: usize,
    control_count: usize,
    execution_status: Option<IrWorkflowRunStatus>,
    gate_count: usize,
    blocked_gate_count: usize,
    gate_status: Vec<GateStatusLine>,
    error: Option<String>,
    /// Run-wide usage totals reconciled from per-task telemetry (#2974).
    usage: Option<WorkflowRunUsage>,
    /// Events evicted from the retained tail; full stream in the journal.
    events_dropped: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct WorkflowSchemaError {
    task_id: String,
    message: String,
}

/// One `task()` dispatch the driver rejected before any child agent existed.
/// Inside `parallel()` the JS throw collapses into a `null` slot, so without
/// this ledger a run whose fan-out never dispatched anything still reads as
/// successful orchestration (#5035).
#[derive(Debug, Clone, Serialize, Deserialize)]
struct WorkflowDispatchFailure {
    at_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    label: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    phase: Option<String>,
    message: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct WorkflowUiEvent {
    at_ms: u64,
    #[serde(flatten)]
    kind: WorkflowUiEventKind,
}

impl WorkflowUiEvent {
    fn new(kind: WorkflowUiEventKind) -> Self {
        Self {
            at_ms: now_ms(),
            kind,
        }
    }

    fn at(at_ms: u64, kind: WorkflowUiEventKind) -> Self {
        Self { at_ms, kind }
    }

    fn event_type(&self) -> &'static str {
        self.kind.event_type()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum WorkflowUiEventKind {
    RunStarted {
        workflow_id: Option<String>,
        workflow_goal: Option<String>,
        source_path: Option<PathBuf>,
        token_budget: Option<u64>,
    },
    RunCompleted {
        status: WorkflowRunStatus,
        error: Option<String>,
        /// Run-wide usage totals reconciled from per-task telemetry (#2974).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        usage: Option<WorkflowRunUsage>,
    },
    RunCancelled {
        reason: String,
    },
    PhaseStarted {
        title: String,
    },
    TaskStarted(Box<WorkflowTaskStartedEvent>),
    TaskCompleted {
        task_id: String,
        status: IrWorkflowRunStatus,
        /// Per-worker telemetry captured at terminal delivery (#2974).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        usage: Option<WorkflowTaskUsage>,
    },
    GateUpdated {
        gate_id: String,
        role: String,
        gate: String,
        state: String,
        blocked_role: Option<String>,
        blocked_reason: Option<String>,
    },
    HandoffPromoted {
        artifact_id: String,
        gate_id: String,
        kind: String,
        from_role: String,
        to_role: String,
        producer_task_id: String,
    },
    HandoffConsumed {
        artifact_id: String,
        kind: String,
        from_role: String,
        to_role: String,
        consumer_task_id: String,
    },
    TaskSchemaValidationFailed {
        task_id: String,
        message: String,
    },
    TaskDispatchFailed {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        label: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase: Option<String>,
        message: String,
    },
    BudgetUpdated {
        total: Option<u64>,
        spent: u64,
        remaining: Option<u64>,
    },
    Log {
        message: String,
    },
}

/// Per-worker usage telemetry carried on `task_completed` events (#2974).
///
/// Tokens come from the worker ledger (`AgentRunUsage`); `tool_calls` is the
/// worker's model/tool step count (`SubAgentResult::steps_taken`) and
/// `result_ref` points at the durable child artifact (transcript handle) so
/// consumers can fetch full output by reference instead of inline text.
/// Field names mirror `AgentRunUsage` so #4039 can render Tokens/Tools
/// columns without a remapping layer.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
struct WorkflowTaskUsage {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    input_tokens: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    output_tokens: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    total_tokens: Option<u64>,
    /// Priced USD subtotal carried from the worker's immutable route audits,
    /// in microdollars. Absence is unknown, never a zero-cost claim.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    cost_microusd: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    tool_calls: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    duration_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    result_ref: Option<String>,
    /// Provenance of the token counts. This producer currently emits only
    /// `provider_reported`; absent means unknown and must never render as zero
    /// (#4039).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    token_source: Option<WorkflowTokenSource>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
enum WorkflowTokenSource {
    ProviderReported,
}

/// Run-wide usage totals reconciled from per-task telemetry, carried on
/// `run_completed` events and the persisted run record (#2974).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
struct WorkflowRunUsage {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    input_tokens: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    output_tokens: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    total_tokens: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    cost_microusd: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    tool_calls: Option<u64>,
    /// Number of completed tasks that contributed telemetry.
    #[serde(default)]
    tasks_reported: u64,
}

impl WorkflowRunUsage {
    fn from_task(usage: &WorkflowTaskUsage) -> Self {
        Self {
            input_tokens: usage.input_tokens,
            output_tokens: usage.output_tokens,
            total_tokens: usage.total_tokens,
            cost_microusd: usage.cost_microusd,
            tool_calls: usage.tool_calls.map(u64::from),
            tasks_reported: 1,
        }
    }

    fn add_task(&mut self, usage: &WorkflowTaskUsage) {
        self.input_tokens = sum_optional_usage(self.input_tokens, usage.input_tokens);
        self.output_tokens = sum_optional_usage(self.output_tokens, usage.output_tokens);
        self.total_tokens = sum_optional_usage(self.total_tokens, usage.total_tokens);
        self.cost_microusd = sum_optional_usage(self.cost_microusd, usage.cost_microusd);
        self.tool_calls = sum_optional_usage(self.tool_calls, usage.tool_calls.map(u64::from));
        self.tasks_reported = self.tasks_reported.saturating_add(1);
    }
}

fn sum_optional_usage(left: Option<u64>, right: Option<u64>) -> Option<u64> {
    match (left, right) {
        (Some(left), Some(right)) => Some(left.saturating_add(right)),
        (Some(value), None) | (None, Some(value)) => Some(value),
        (None, None) => None,
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct WorkflowTaskStartedEvent {
    task_id: String,
    label: Option<String>,
    /// Fleet role declared on the step, if any (#4177).
    role: Option<String>,
    profile: Option<String>,
    model: Option<String>,
    strength: Option<String>,
    thinking: Option<String>,
    /// Reasoning the task requested, verbatim (`inherit`/`auto`/effort) (#4039).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    requested_reasoning: Option<String>,
    /// Reasoning the child runtime was actually installed with (#4039). Absent
    /// when the resolved route carries no reasoning control; consumers render
    /// that as unknown rather than inventing an effort.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    effective_reasoning: Option<String>,
    /// Resolved fleet role after roster lookup (#4177).
    resolved_role: Option<String>,
    /// Resolved AgentProfile id after fleet resolution (#4177).
    resolved_profile: Option<String>,
    resolved_provider: String,
    resolved_model: String,
    route_source: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    child_route: Option<crate::tools::subagent::ChildRouteReceipt>,
    worktree: bool,
    workspace: Option<PathBuf>,
    git_branch: Option<String>,
    parent_task_id: Option<String>,
    depth: u32,
    /// Workflow run that admitted this child (#4119).
    workflow_run_id: Option<String>,
    /// Phase title/id active (or declared on the task) at spawn (#4119).
    workflow_phase_id: Option<String>,
    /// Typed task label — UI must prefer this over prompt text (#4119).
    workflow_task_label: Option<String>,
    /// 0-based admission order among children of this run (#4119).
    workflow_child_index: Option<u32>,
    /// Durable exact-Fleet routing receipt: the fixed member identity, its
    /// exact provider/model, the requested vs. selector vs. provider-effective
    /// reasoning, where the decision came from, and the Router's exact identity
    /// when a Router made it. `default` keeps events written before this field
    /// existed — and every legacy/non-fleet task — readable unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    fleet_receipt: Option<codewhale_workflow::FleetTaskReceipt>,
}

impl WorkflowUiEventKind {
    fn event_type(&self) -> &'static str {
        match self {
            Self::RunStarted { .. } => "run_started",
            Self::RunCompleted { .. } => "run_completed",
            Self::RunCancelled { .. } => "run_cancelled",
            Self::PhaseStarted { .. } => "phase_started",
            Self::TaskStarted(_) => "task_started",
            Self::TaskCompleted { .. } => "task_completed",
            Self::GateUpdated { .. } => "gate_updated",
            Self::HandoffPromoted { .. } => "handoff_promoted",
            Self::HandoffConsumed { .. } => "handoff_consumed",
            Self::TaskSchemaValidationFailed { .. } => "task_schema_validation_failed",
            Self::TaskDispatchFailed { .. } => "task_dispatch_failed",
            Self::BudgetUpdated { .. } => "budget_updated",
            Self::Log { .. } => "log",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct WorkflowRunRecord {
    run_id: String,
    status: WorkflowRunStatus,
    #[serde(default)]
    lifecycle_seq: u64,
    started_at_ms: u64,
    completed_at_ms: Option<u64>,
    source_path: Option<PathBuf>,
    workflow_id: Option<String>,
    workflow_goal: Option<String>,
    token_budget: Option<u64>,
    child_ids: Vec<String>,
    progress: Vec<String>,
    #[serde(default)]
    events: Vec<WorkflowUiEvent>,
    schema_errors: Vec<WorkflowSchemaError>,
    /// Task dispatches the driver rejected before any child ran (#5035).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    dispatch_failures: Vec<WorkflowDispatchFailure>,
    result: Option<Value>,
    execution: Option<IrWorkflowExecution>,
    error: Option<String>,
    #[serde(default)]
    verify_on_complete: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    verification: Option<Value>,
    /// Durable elevated-plan approval receipt for audit (#4126).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    plan_approval: Option<WorkflowPlanApprovalReceipt>,
    /// Compact lane gate state for status / panel surfaces (#4179).
    #[serde(default)]
    gate_status: Vec<GateStatusLine>,
    /// Run-wide usage totals reconciled at completion (#2974).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    usage: Option<WorkflowRunUsage>,
    /// Total events recorded for this run (monotonic; survives the bounded
    /// `events` tail retention) (#2974).
    #[serde(default)]
    events_total: u64,
    /// Events evicted from the in-memory tail; available in the journal.
    #[serde(default)]
    events_dropped: u64,
}

impl WorkflowRunRecord {
    fn new(
        run_id: String,
        source_path: Option<PathBuf>,
        token_budget: Option<u64>,
        spec: Option<&WorkflowSpec>,
    ) -> Self {
        let gate_status = spec
            .map(|spec| initial_gate_status(&run_id, &spec.gates))
            .unwrap_or_default();
        Self {
            run_id,
            status: WorkflowRunStatus::Running,
            lifecycle_seq: 1,
            started_at_ms: now_ms(),
            completed_at_ms: None,
            source_path,
            workflow_id: spec.and_then(|spec| spec.id.clone()),
            workflow_goal: spec.map(|spec| spec.goal.clone()),
            token_budget,
            child_ids: Vec::new(),
            progress: Vec::new(),
            events: Vec::new(),
            schema_errors: Vec::new(),
            dispatch_failures: Vec::new(),
            result: None,
            execution: None,
            error: None,
            verify_on_complete: false,
            verification: None,
            plan_approval: None,
            gate_status,
            usage: None,
            events_total: 0,
            events_dropped: 0,
        }
    }

    /// Record one event, bounding retention to the newest
    /// `WORKFLOW_RUN_EVENTS_MAX_RETAINED` entries (#2974). Every event is
    /// journaled per-line at record time, so evicted entries remain
    /// available in `.codewhale/workflow-runs.jsonl`.
    fn push_event(&mut self, event: WorkflowUiEvent) {
        self.events_total = self.events_total.saturating_add(1);
        self.events.push(event);
        if self.events.len() > WORKFLOW_RUN_EVENTS_MAX_RETAINED {
            let overflow = self.events.len() - WORKFLOW_RUN_EVENTS_MAX_RETAINED;
            self.events.drain(..overflow);
            self.events_dropped = self
                .events_dropped
                .saturating_add(u64::try_from(overflow).unwrap_or(u64::MAX));
        }
    }

    fn summary(&self) -> WorkflowRunSummary {
        WorkflowRunSummary {
            run_id: self.run_id.clone(),
            status: self.status,
            lifecycle_seq: self.lifecycle_seq,
            started_at_ms: self.started_at_ms,
            completed_at_ms: self.completed_at_ms,
            source_path: self.source_path.clone(),
            workflow_id: self.workflow_id.clone(),
            workflow_goal: self.workflow_goal.clone(),
            token_budget: self.token_budget,
            child_count: self.child_ids.len(),
            schema_error_count: self.schema_errors.len(),
            dispatch_failure_count: self.dispatch_failures.len(),
            progress_count: self.progress.len(),
            last_progress: self.progress.last().cloned(),
            event_count: usize::try_from(self.events_total.max(self.events.len() as u64))
                .unwrap_or(usize::MAX),
            last_event_type: self
                .events
                .last()
                .map(|event| event.event_type().to_string()),
            leaf_count: self
                .execution
                .as_ref()
                .map(|execution| execution.leaf_results.len())
                .unwrap_or_default(),
            branch_count: self
                .execution
                .as_ref()
                .map(|execution| execution.branch_results.len())
                .unwrap_or_default(),
            control_count: self
                .execution
                .as_ref()
                .map(|execution| execution.control_node_results.len())
                .unwrap_or_default(),
            execution_status: self.execution.as_ref().map(|execution| execution.status),
            gate_count: self.gate_status.len(),
            blocked_gate_count: self
                .gate_status
                .iter()
                .filter(|line| line.blocked_reason.is_some())
                .count(),
            gate_status: self.gate_status.clone(),
            error: self.error.clone(),
            usage: self.usage.clone(),
            events_dropped: self.events_dropped,
        }
    }
}

fn initial_gate_status(run_id: &str, gates: &[GateSpec]) -> Vec<GateStatusLine> {
    if gates.is_empty() {
        return Vec::new();
    }
    let mut board = LaneGateBoard::new(run_id);
    board.install_gates(gates);
    board.status_summary()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum WorkflowRunStatus {
    Running,
    Completed,
    /// The script returned a value, but at least one requested task slot
    /// failed or was rejected without the script declaring a partial-failure
    /// contract. The output is preserved; the status refuses to call a run
    /// with dropped slots a plain success (receipt honesty, morning-report
    /// issue #2).
    Degraded,
    Failed,
    Cancelled,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WorkflowAction {
    Start,
    Run,
    Status,
    Cancel,
}

fn parse_workflow_action(input: &Value) -> Result<WorkflowAction, ToolError> {
    let Some(action) = optional_str(input, "action")? else {
        return Ok(WorkflowAction::Start);
    };
    match action.trim().to_ascii_lowercase().as_str() {
        "" | "start" | "spawn" => Ok(WorkflowAction::Start),
        "run" | "wait" => Ok(WorkflowAction::Run),
        "status" | "list" | "inspect" => Ok(WorkflowAction::Status),
        "cancel" | "stop" | "abort" => Ok(WorkflowAction::Cancel),
        other => Err(ToolError::invalid_input(format!(
            "Invalid workflow action '{other}'. Use start, run, status, or cancel."
        ))),
    }
}

#[async_trait]
impl ToolSpec for WorkflowTool {
    fn name(&self) -> &'static str {
        "workflow"
    }

    fn description(&self) -> &'static str {
        concat!(
            "Start, run, inspect, or cancel a Workflow. Workflows execute deterministic JS with args, phase/log progress, and task(...) calls that dispatch real sub-agents through Fleet/sub-agent scheduling. ",
            "For parallel fan-out, pass an array of zero-argument thunks exactly like `await parallel([() => task({...}), () => task({...})])`; do not pass task promises as variadic arguments. ",
            "Provide exactly one of script, source_path, or plan (structured planner JSON). ",
            "Use action=start for detached orchestration and action=status with run_id to inspect progress. Use action=run when the model needs the final result before continuing. ",
            "Start a workflow on your own only for broad or staged work (the session [workflow].automatic table, default on). An explicit /workflow invocation is authorization. Do not start a workflow for one-file edits or simple questions."
        )
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["start", "run", "status", "cancel"],
                    "description": "start (default) launches a Workflow in the background. run waits for completion. status lists runs or inspects run_id. cancel stops a run and its child agents."
                },
                "run_id": {
                    "type": "string",
                    "description": "Workflow run id for action=status or action=cancel."
                },
                "script": {
                    "type": "string",
                    "description": "Workflow JS source. The runtime provides args, task(...), parallel(thunks), pipeline(thunks), log(...), phase(...), and budget. Fan-out syntax: await parallel([() => task({...}), () => task({...})]). parallel() requires one array of zero-argument thunks, not variadic task promises."
                },
                "source_path": {
                    "type": "string",
                    "description": "Path to a .workflow.js script inside the workspace. Use instead of script for checked-in workflows."
                },
                "fleet": {
                    "type": "string",
                    "description": "Named Fleet to resolve task({ role }) declarations, loaded from $CODEWHALE_HOME/fleets/ or workspace fleets/. Accepts a qualified origin/name. A legacy roster maps roles to profiles. An exact Fleet (schema = \"exact\") is frozen at start: each member's provider, model, reasoning, and permission ceiling are fixed, and per-task model/thinking overrides are rejected."
                },
                "plan": {
                    "type": "object",
                    "description": "Structured planner plan JSON (#4124). Alternative to script/source_path. Accepts goal, risk, max_children, token_budget, phases[], and/or children[] (or IR nodes). risk must be exactly read_only, writes, or elevated. For a child, prefer role/profile without an explicit type; do not combine a role/profile with a conflicting type. Lowered to Workflow JS with parallel() partial-success semantics."
                },
                "args": {
                    "anyOf": [
                        { "type": "null" },
                        { "type": "boolean" },
                        { "type": "integer" },
                        { "type": "number" },
                        { "type": "string" },
                        { "type": "array" },
                        {
                            "type": "object",
                            "additionalProperties": {}
                        }
                    ],
                    "description": "JSON value exposed to the script as args. Defaults to null."
                },
                "token_budget": {
                    "type": "integer",
                    "minimum": 1,
                    "description": "Optional shared Workflow admission hint. Usage is reconciled when children report completion; already-running parallel children can take aggregate spent past the hint, while later and descendant spawns are rejected once exhausted."
                },
                "wait": {
                    "type": "boolean",
                    "description": "For action=start, wait for completion instead of returning immediately."
                },
                "verify": {
                    "type": "boolean",
                    "default": false,
                    "description": "After a successful workflow completion, run quick workspace verifier gates (auto/quick profile)."
                }
            },
            "required": [],
            "additionalProperties": false
        })
    }

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

    fn approval_requirement(&self) -> ApprovalRequirement {
        // Default posture: elevated starts require approval. Concrete inputs
        // refine this via `approval_requirement_for` (#4126).
        ApprovalRequirement::Required
    }

    fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement {
        // The session's `[workflow]` table decides read-only auto-start and
        // write approval; product defaults apply only when the runtime never
        // threaded a config. YOLO/bypass still short-circuit upstream.
        let config = workflow_config_for(&self.runtime);
        workflow_approval_requirement_for(input, &config)
    }

    fn starts_detached_for(&self, input: &Value) -> bool {
        // A scheduling hint, not an authority decision, and this trait method
        // cannot report an error. A malformed `wait` reads as "not detached"
        // so the call stays in the foreground; `execute` then refuses it with
        // the named-parameter error rather than running anything.
        matches!(parse_workflow_action(input), Ok(WorkflowAction::Start))
            && !optional_bool(input, "wait", false).unwrap_or(true)
    }

    fn supports_parallel_for(&self, input: &Value) -> bool {
        matches!(parse_workflow_action(input), Ok(WorkflowAction::Status))
    }

    fn is_read_only_for(&self, input: &Value) -> bool {
        matches!(parse_workflow_action(input), Ok(WorkflowAction::Status))
    }

    async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
        let state = shared_workflow_state(&context.workspace);
        attach_bound_workflow_lifecycles(context, &state)?;
        // Keyed off the parsed `WorkflowAction` discriminant, never off
        // `input["action"]`. The JSON Schema published to the model is a
        // declaration, not a guard: the real parse also accepts `spawn`,
        // `wait`, `list`, `inspect`, `stop`, and `abort`, and its reject arm
        // embeds the model's string verbatim.
        let action = parse_workflow_action(&input)?;
        codewhale_telemetry::session_counters().bump(codewhale_telemetry::Counter::WorkflowRun);
        match action {
            WorkflowAction::Start => {
                let wait = optional_bool(&input, "wait", false)?;
                start_workflow(
                    input,
                    context,
                    self.manager.clone(),
                    self.runtime.clone(),
                    state,
                    wait,
                    self.approval_decision,
                )
                .await
            }
            WorkflowAction::Run => {
                start_workflow(
                    input,
                    context,
                    self.manager.clone(),
                    self.runtime.clone(),
                    state,
                    true,
                    self.approval_decision,
                )
                .await
            }
            WorkflowAction::Status => status_workflow(input, state),
            WorkflowAction::Cancel => cancel_workflow(input, state).await,
        }
    }
}

fn attach_bound_workflow_lifecycles(
    context: &ToolContext,
    state: &Arc<WorkflowWorkspaceState>,
) -> Result<(), ToolError> {
    let records = lock_mutex(&state.runs)?
        .values()
        .cloned()
        .collect::<Vec<_>>();
    for record in records {
        if let Some(lifecycle) = WorkflowWorkLifecycle::for_bound(context, &record.run_id) {
            state.attach_lifecycle(&record.run_id, lifecycle);
            state.reconcile_snapshot(&record);
        }
    }
    Ok(())
}

fn fail_workflow_start(state: &Arc<WorkflowWorkspaceState>, run_id: &str, message: String) {
    let snapshot = state.runs.lock().ok().and_then(|mut runs| {
        let record = runs.get_mut(run_id)?;
        record.status = WorkflowRunStatus::Failed;
        record.lifecycle_seq = record.lifecycle_seq.saturating_add(1);
        record.completed_at_ms = Some(now_ms());
        record.error = Some(message);
        Some(record.clone())
    });
    let Some(snapshot) = snapshot else {
        state.mark_owner_missing(run_id);
        return;
    };
    if state.try_record_snapshot(&snapshot).is_ok() {
        state.reconcile_snapshot(&snapshot);
    } else {
        state.mark_owner_missing(run_id);
    }
}

fn fail_workflow_after_controller_registration(
    state: &Arc<WorkflowWorkspaceState>,
    run_id: &str,
    controller: &Arc<WorkflowRunController>,
    message: String,
) {
    controller.cancel();
    if let Ok(mut controllers) = state.controllers.lock() {
        controllers.remove(run_id);
    }
    fail_workflow_start(state, run_id, message);
}

#[allow(clippy::too_many_arguments)]
async fn start_workflow(
    input: Value,
    context: &ToolContext,
    manager: SharedSubAgentManager,
    runtime: SubAgentRuntime,
    state: Arc<WorkflowWorkspaceState>,
    wait: bool,
    approval_decision: &str,
) -> Result<ToolResult, ToolError> {
    let source = workflow_source(&input, context)?;
    let args = input.get("args").cloned().unwrap_or(Value::Null);
    let token_budget = optional_u64(&input, "token_budget", 0)?;
    let token_budget = (token_budget > 0).then_some(token_budget);
    let verify_on_complete = optional_bool(&input, "verify", false)?;
    let fleet = workflow_fleet_binding(&input, context, runtime.api_config.as_deref())?;
    let run_id = format!("workflow_{}", &Uuid::new_v4().to_string()[..8]);
    let gate_specs = source
        .spec
        .as_ref()
        .map(|spec| spec.gates.clone())
        .unwrap_or_default();

    // Capture the approved plan envelope for audit/receipt (#4126). Reaching
    // execute means the approval gate already passed (or YOLO/auto-start).
    let workflow_cfg = workflow_config_for(&runtime);
    let summary = source
        .spec
        .as_ref()
        .map(|spec| analyze_workflow_spec(spec, token_budget, &workflow_cfg))
        .unwrap_or_else(|| analyze_workflow_plan_approval_with_config(&input, &workflow_cfg));
    let approval_decision = if summary.is_read_only_envelope() {
        "auto_read_only"
    } else {
        approval_decision
    };
    let plan_approval = summary.to_receipt(approval_decision, now_ms());
    let workflow_title = source
        .spec
        .as_ref()
        .map(|spec| spec.goal.as_str())
        .or_else(|| {
            source
                .path
                .as_ref()
                .and_then(|path| path.file_name()?.to_str())
        })
        .unwrap_or("Workflow run");
    let lifecycle = WorkflowWorkLifecycle::register(context, &run_id, workflow_title)?;

    {
        let mut runs_guard = match lock_mutex(&state.runs) {
            Ok(guard) => guard,
            Err(err) => {
                if let Some(lifecycle) = lifecycle.as_ref() {
                    lifecycle.reconcile_spawn_failure();
                }
                return Err(err);
            }
        };
        let mut record = WorkflowRunRecord::new(
            run_id.clone(),
            source.path.clone(),
            token_budget,
            source.spec.as_ref(),
        );
        record.verify_on_complete = verify_on_complete;
        record.plan_approval = Some(plan_approval.clone());
        let started = WorkflowUiEvent::at(
            record.started_at_ms,
            WorkflowUiEventKind::RunStarted {
                workflow_id: record.workflow_id.clone(),
                workflow_goal: record.workflow_goal.clone(),
                source_path: record.source_path.clone(),
                token_budget: record.token_budget,
            },
        );
        record.push_event(started.clone());
        runs_guard.insert(run_id.clone(), record.clone());
        if let Err(err) = state.try_record_snapshot(&record) {
            runs_guard.remove(&run_id);
            if let Some(lifecycle) = lifecycle.as_ref() {
                lifecycle.reconcile_spawn_failure();
            }
            return Err(ToolError::execution_failed(format!(
                "workflow journal snapshot failed before launch: {err}"
            )));
        }
        // #4122: emit RunStarted immediately so the panel + history card open
        // before the first task/phase (including wait:false fire-and-forget).
        if let Some(tx) = runtime.event_tx.as_ref()
            && let Ok(mut value) = serde_json::to_value(&started)
        {
            if let Some(obj) = value.as_object_mut() {
                obj.insert("run_id".to_string(), json!(run_id));
            }
            let _ = tx.try_send(Event::WorkflowUi {
                run_id: run_id.clone(),
                event: value,
            });
        }
    }
    if let Some(lifecycle) = lifecycle {
        state.attach_lifecycle(&run_id, lifecycle);
    }

    // An exact Fleet runs on a run-scoped roster projected from its immutable
    // snapshot, so every child resolves its member (and that member's exact
    // provider pin) from the value frozen at start rather than from whatever
    // the session roster holds now.
    let mut runtime = runtime;
    if let Some(operation) = fleet.exact() {
        runtime.fleet_roster = operation.roster().clone();
    }

    let driver = SubAgentWorkflowDriver::new(
        run_id.clone(),
        manager,
        runtime,
        state.clone(),
        token_budget,
        fleet,
        gate_specs,
    );
    let vm_cancel = WorkflowRunCancel::new();
    let controller = Arc::new(WorkflowRunController::new(
        driver.clone(),
        vm_cancel.clone(),
    ));
    if let Err(err) = lock_mutex(&state.controllers).map(|mut controllers_guard| {
        controllers_guard.insert(run_id.clone(), controller.clone());
    }) {
        fail_workflow_start(&state, &run_id, err.to_string());
        return Err(err);
    }
    let running_snapshot = {
        let mut runs_guard = match lock_mutex(&state.runs) {
            Ok(guard) => guard,
            Err(err) => {
                fail_workflow_after_controller_registration(
                    &state,
                    &run_id,
                    &controller,
                    err.to_string(),
                );
                return Err(err);
            }
        };
        let Some(record) = runs_guard.get_mut(&run_id) else {
            drop(runs_guard);
            fail_workflow_after_controller_registration(
                &state,
                &run_id,
                &controller,
                "workflow owner record disappeared before launch".to_string(),
            );
            return Err(ToolError::execution_failed(
                "workflow owner record disappeared before launch",
            ));
        };
        record.lifecycle_seq = record.lifecycle_seq.saturating_add(1);
        record.clone()
    };
    if let Err(err) = state.try_record_snapshot(&running_snapshot) {
        fail_workflow_after_controller_registration(
            &state,
            &run_id,
            &controller,
            format!("workflow journal failed while activating owner: {err}"),
        );
        return Err(ToolError::execution_failed(format!(
            "workflow journal failed while activating owner: {err}"
        )));
    }
    state.reconcile_snapshot(&running_snapshot);

    let run = run_workflow_vm(
        run_id.clone(),
        source.source,
        source.spec,
        args,
        driver,
        state.clone(),
        context.clone(),
        vm_cancel,
    );
    if wait {
        run.await;
    } else {
        let handle = spawn_supervised("workflow-run", std::panic::Location::caller(), run);
        controller.set_run_handle(handle);
    }

    workflow_result_for(&run_id, state)
}

fn status_workflow(
    input: Value,
    state: Arc<WorkflowWorkspaceState>,
) -> Result<ToolResult, ToolError> {
    if let Some(run_id) = optional_str(&input, "run_id")? {
        return workflow_result_for(run_id, state);
    }
    let mut summaries = {
        let runs_guard = lock_mutex(&state.runs)?;
        runs_guard
            .values()
            .map(WorkflowRunRecord::summary)
            .collect::<Vec<_>>()
    };
    summaries.sort_by_key(|record| record.started_at_ms);
    ToolResult::json(&json!({
        "action": "status",
        "count": summaries.len(),
        "runs": summaries,
    }))
    .map_err(|err| ToolError::execution_failed(err.to_string()))
}

async fn cancel_workflow(
    input: Value,
    state: Arc<WorkflowWorkspaceState>,
) -> Result<ToolResult, ToolError> {
    let run_id =
        optional_str(&input, "run_id")?.ok_or_else(|| ToolError::missing_field("run_id"))?;
    cancel_workflow_run(run_id, state)
}

/// Synchronous cancellation core shared by the model-facing tool action and
/// the host `/workflow cancel` command. When a live controller exists this
/// signals the VM, aborts the run task, journals the terminal snapshot, and
/// streams the cancelled event. When the journal has a running line but no
/// controller (typical after a restart), the journal is still marked
/// cancelled with an honest nothing-live receipt. Nothing here waits on the
/// network.
fn cancel_workflow_run(
    run_id: &str,
    state: Arc<WorkflowWorkspaceState>,
) -> Result<ToolResult, ToolError> {
    let controller = {
        let mut controllers_guard = lock_mutex(&state.controllers)?;
        controllers_guard.remove(run_id)
    };
    let current_status = {
        let runs_guard = lock_mutex(&state.runs)?;
        let record = runs_guard.get(run_id).ok_or_else(|| {
            ToolError::invalid_input(format!("Unknown workflow run_id '{run_id}'"))
        })?;
        record.status
    };
    if current_status != WorkflowRunStatus::Running {
        state.reconcile_cancel(run_id, CancelOutcome::AlreadyFinished);
        if let Ok(runs_guard) = state.runs.lock()
            && let Some(record) = runs_guard.get(run_id)
        {
            state.reconcile_snapshot(record);
        }
        return workflow_result_for(run_id, state);
    }
    let live = controller.is_some();
    state.reconcile_cancel(
        run_id,
        if live {
            CancelOutcome::Requested
        } else {
            // Nothing live to signal; the journal cancel below is the receipt.
            CancelOutcome::Acknowledged
        },
    );
    if let Some(controller) = controller.as_ref() {
        controller.cancel();
    }
    let reason = if live {
        "cancelled by workflow tool"
    } else {
        "cancelled; no live process to stop"
    }
    .to_string();
    let cancelled_event = WorkflowUiEvent::new(WorkflowUiEventKind::RunCancelled {
        reason: reason.clone(),
    });
    let snapshot = {
        let mut runs_guard = lock_mutex(&state.runs)?;
        let record = runs_guard.get_mut(run_id).ok_or_else(|| {
            ToolError::invalid_input(format!("Unknown workflow run_id '{run_id}'"))
        })?;
        record.status = WorkflowRunStatus::Cancelled;
        record.lifecycle_seq = record.lifecycle_seq.saturating_add(1);
        record.completed_at_ms = Some(now_ms());
        record.error = Some(reason);
        record.push_event(cancelled_event.clone());
        record.clone()
    };
    if let Err(err) = state.try_record_snapshot(&snapshot) {
        state.mark_owner_missing(run_id);
        return Err(ToolError::execution_failed(format!(
            "workflow cancellation journal failed: {err}"
        )));
    }
    state.reconcile_snapshot(&snapshot);
    // The VM may publish its terminal `run_completed` event while cancellation
    // is racing it. Always stream the authoritative cancellation afterward so
    // the live panel finalizes running rows and cannot remain visually failed.
    if let Some(controller) = controller {
        controller.driver.emit_ui_event(&cancelled_event);
    }
    workflow_result_for(run_id, state)
}

fn workflow_fleet_name(input: &Value) -> Result<Option<String>, ToolError> {
    let named = match optional_str(input, "fleet")? {
        Some(name) => Some(name),
        None => match input.get("args") {
            Some(args) => optional_str(args, "fleet")?,
            None => None,
        },
    };
    Ok(named
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .map(str::to_string))
}

/// How a Workflow run is bound to a named Fleet.
///
/// The two saved forms share one store and one `fleet: "<name>"` option. Legacy
/// role maps keep their exact previous behavior; an exact fleet is frozen into
/// an immutable Workflow snapshot at start and drives every task launch from
/// that snapshot.
#[derive(Debug, Clone, Default)]
enum WorkflowFleetBinding {
    #[default]
    None,
    Legacy {
        name: String,
        roles: FleetRoleMap,
    },
    Exact(Arc<crate::fleet::exact::ExactFleetWorkflow>),
}

impl WorkflowFleetBinding {
    fn name(&self) -> Option<String> {
        match self {
            Self::None => None,
            Self::Legacy { name, .. } => Some(name.clone()),
            Self::Exact(operation) => Some(operation.snapshot().fleet().qualified()),
        }
    }

    fn legacy_roles(&self) -> Option<&FleetRoleMap> {
        match self {
            Self::Legacy { roles, .. } => Some(roles),
            Self::None | Self::Exact(_) => None,
        }
    }

    fn exact(&self) -> Option<&Arc<crate::fleet::exact::ExactFleetWorkflow>> {
        match self {
            Self::Exact(operation) => Some(operation),
            Self::None | Self::Legacy { .. } => None,
        }
    }
}

fn workflow_fleet_binding(
    input: &Value,
    context: &ToolContext,
    api_config: Option<&crate::config::Config>,
) -> Result<WorkflowFleetBinding, ToolError> {
    let Some(name) = workflow_fleet_name(input)? else {
        return Ok(WorkflowFleetBinding::None);
    };
    let roots = crate::fleet::exact::fleet_search_roots(&context.workspace);
    let (document, id) = crate::fleet::exact::load_fleet_document(&name, &context.workspace)
        .map_err(|err| {
            ToolError::invalid_input(format!(
                "Failed to load workflow fleet '{name}' from {}: {err}",
                roots
                    .iter()
                    .map(|root| format!("{}/{}", root.origin, root.root.display()))
                    .collect::<Vec<_>>()
                    .join(", ")
            ))
        })?;

    if let Some(legacy) = document.legacy() {
        let roles = FleetRoleMap::from_pairs(
            legacy
                .roles
                .iter()
                .map(|(role, profile)| (role.as_str(), profile.as_str())),
        )
        .map_err(|err| ToolError::invalid_input(err.to_string()))?;
        return Ok(WorkflowFleetBinding::Legacy { name, roles });
    }

    // Exact: freeze the definition now. Everything the run launches afterwards
    // comes from this value, so editing the file mid-run cannot move a route.
    // The same labelled roots resolve the Fleet *and* the Reasoning Router
    // profile it references, so a Router is qualified (`workspace/luna-low`)
    // exactly the way a Fleet is and cannot be resolved by shadowing.
    let operation = crate::fleet::exact::ExactFleetWorkflow::capture(
        &document,
        id,
        chrono::Utc::now().to_rfc3339(),
        api_config,
        &roots,
    )
    .map_err(ToolError::invalid_input)?;
    Ok(WorkflowFleetBinding::Exact(Arc::new(operation)))
}

fn apply_named_fleet_to_task_request(
    fleet_roles: Option<&FleetRoleMap>,
    request: &mut TaskRequest,
) -> Result<(), DriverError> {
    let Some(fleet_roles) = fleet_roles else {
        return Ok(());
    };
    let resolved = resolve_workflow_agent(
        request.role.as_deref(),
        request.profile.as_deref(),
        fleet_roles,
        true,
    )
    .map_err(|err| DriverError::Rejected(err.to_string()))?;
    request.role = resolved.resolved_role;
    request.profile = Some(resolved.resolved_profile);
    Ok(())
}

/// **Phase one** of an exact-Fleet task: resolve the member and stamp its
/// clamped authority onto the request, contacting nobody.
///
/// This runs *before* gate evaluation and before a concurrency slot is taken,
/// which is what makes it safe: a task that is about to be rejected or queued
/// must not have spent a router call or disclosed a summary to another
/// provider. Everything that can cost money lives in
/// [`route_admitted_exact_task`].
fn bind_exact_fleet_task_request(
    operation: &crate::fleet::exact::ExactFleetWorkflow,
    session: codewhale_workflow::PermissionCeiling,
    request: &mut TaskRequest,
) -> Result<crate::fleet::exact::ExactMemberBinding, DriverError> {
    let fleet = operation.snapshot().fleet().qualified();

    // A saved exact Fleet is the authority on routing and on posture. A task
    // that tries to re-route a member — or to widen it by asking for a
    // different agent type or a broader tool surface — is rejected outright
    // rather than silently ignored. `subagent_type` and `allowed_tools` matter
    // as much as `model` here: the member's posture role is derived from its
    // saved permission ceiling, and a task-supplied type would otherwise pick
    // a different tool surface than the one the operator saved.
    for (field, present) in [
        ("model", request.model.is_some()),
        ("model_strength", request.model_strength.is_some()),
        ("thinking", request.thinking.is_some()),
        ("subagent_type", request.subagent_type.is_some()),
        ("allowed_tools", request.allowed_tools.is_some()),
        ("write_authority", request.write_authority.is_some()),
    ] {
        if present {
            return Err(DriverError::Rejected(format!(
                "fleet `{fleet}` is an exact fleet: task option `{field}` is not allowed. Every \
                 member's provider, model, reasoning, and permission ceiling are fixed by the \
                 saved Fleet — switch Fleets or edit the Fleet, do not override a member per \
                 task."
            )));
        }
    }

    let binding = operation
        .bind_member(request.profile.as_deref(), request.role.as_deref(), session)
        .map_err(|err| DriverError::Rejected(format!("fleet `{fleet}`: {err}")))?;

    // Id and role are stamped **separately and semantically**. The member id
    // addresses the run-scoped roster profile projected from the snapshot,
    // which carries the exact provider pin and canonical wire model. The role
    // stays the Fleet's semantic role, because that is what gates, handoffs,
    // and records key on — overwriting it with the profile id (as an earlier
    // pass did) silently broke every gate whose member id differs from its
    // role.
    request.profile = Some(binding.member_id.clone());
    request.role = Some(binding.member_role.clone());

    // Ceilings narrow the child; they never widen it. `subagent_type` is
    // cleared rather than defaulted so the roster profile's posture role — the
    // one derived from the saved ceiling — is what picks the tool surface.
    request.subagent_type = None;
    // The clamped authority becomes an actual tool policy the child runtime
    // enforces: an empty allowlist when `tools = false`, and a deny list that
    // removes every model-visible network surface when `network_tool = false`.
    request.allowed_tools = binding.authority.allowed_tools.clone();
    request.disallowed_tools = binding.authority.disallowed_tools.clone();
    request.write_authority = Some(binding.authority.write_authority.to_string());
    request.max_depth = Some(
        request
            .max_depth
            .map_or(binding.authority.max_depth, |asked| {
                asked.min(binding.authority.max_depth)
            }),
    );

    // Everything the spawn boundary will reject *predictably* is rejected here,
    // while the task has still cost nothing. The write-scope contract is the
    // one that bites: a write-capable member launched with no declared scope
    // fails at `validate_spawn_write_contract`, which runs long after the
    // Router has been paid for a decision about a task that could never run.
    validate_exact_write_scope(&fleet, &binding, request)?;
    Ok(binding)
}

/// Which role a `task_started` event displays.
///
/// An exact-Fleet receipt wins over the spawn metadata, because the metadata's
/// role is the roster profile's **permission posture** — the tool surface the
/// clamped ceiling permits — and rendering that where the member's role belongs
/// renames the operator's `auditor` to `scout` in the panel, the history card,
/// and the journal. The posture is not lost: it rides the same receipt in its
/// own field. Non-Fleet tasks keep the previous metadata-then-request order
/// exactly.
fn displayed_resolved_role(
    fleet_receipt: Option<&codewhale_workflow::FleetTaskReceipt>,
    metadata_role: Option<&str>,
    request_role: Option<&str>,
) -> Option<String> {
    fleet_receipt
        .map(|receipt| receipt.member_role.clone())
        .or_else(|| metadata_role.map(str::to_string))
        .or_else(|| request_role.map(str::to_string))
}

/// The visible line for a routing decision whose spawn then failed.
///
/// Kept separate from the recorder so the wording is testable without a live
/// driver, and so the receipt's own content-free `line()` stays the single
/// source of what a receipt may say.
fn orphaned_fleet_receipt_line(
    receipt: &codewhale_workflow::FleetTaskReceipt,
    error: &str,
) -> String {
    format!(
        "fleet route {} spawn_failed=true reason={}",
        receipt.line(),
        error.replace('\n', " ")
    )
}

/// The write-scope half of the spawn contract, checked before anything costs.
///
/// Deliberately a mirror of the spawn-boundary rule rather than a replacement
/// for it: the boundary stays authoritative (it is reachable by other callers),
/// and this exists so an exact-Fleet task fails on the same terms *before* the
/// Router call rather than after it.
fn validate_exact_write_scope(
    fleet: &str,
    binding: &crate::fleet::exact::ExactMemberBinding,
    request: &TaskRequest,
) -> Result<(), DriverError> {
    let declares_scope = !request.write_roots.is_empty()
        || !request.exact_files.is_empty()
        || !request.coordination_contracts.is_empty();

    if binding.authority.write_authority == "read_only" {
        if declares_scope {
            return Err(DriverError::Rejected(format!(
                "fleet `{fleet}`: member `{}` is read-only under the clamped ceiling, so this \
                 task may not declare write_roots, exact_files, or coordination_contracts.",
                binding.member_id
            )));
        }
        return Ok(());
    }

    if !declares_scope {
        return Err(DriverError::Rejected(format!(
            "fleet `{fleet}`: member `{}` is write-capable, so this task must declare \
             write_roots, exact_files, or coordination_contracts before it can start. An \
             unbounded write claim is refused at the spawn boundary, and this task would spend a \
             reasoning-router call on its way to that refusal.",
            binding.member_id
        )));
    }
    Ok(())
}

/// **Phase two**: route an already admitted task.
///
/// Only reachable once the task has passed its gates and holds a concurrency
/// slot, so this is the one place a reasoning router call — and any
/// cross-provider disclosure — can happen.
async fn route_admitted_exact_task(
    operation: &crate::fleet::exact::ExactFleetWorkflow,
    binding: &crate::fleet::exact::ExactMemberBinding,
    request: &mut TaskRequest,
) -> Result<codewhale_workflow::FleetTaskReceipt, DriverError> {
    let fleet = operation.snapshot().fleet().qualified();
    let launch = operation
        .route_admitted_task(binding, &request.description)
        .await
        .map_err(|err| DriverError::Rejected(format!("fleet `{fleet}`: {err}")))?;

    request.thinking = Some(launch.thinking.clone());
    // **The launch authority is what the child runs under.** Binding stamped a
    // provisional copy so the write-scope contract could be checked for free;
    // this re-stamps from the value `route_admitted_task` recomputed and
    // verified, so the request that reaches the spawn boundary carries the
    // launched envelope and not an older one. Without this the launch's
    // `authority` was computed, put on a struct, and never read — a ceiling
    // that existed only as a field.
    apply_launch_authority(&fleet, &launch, request)?;
    Ok(launch.receipt)
}

/// Stamp the launched authority onto the request and refuse any drift.
///
/// Two things happen here and both are load-bearing. The envelope fields are
/// overwritten from `launch.authority`, so the spawn input is built from the
/// launched value rather than the admitted one. And `max_depth` is intersected
/// rather than replaced, because a task may legitimately ask for *less* nesting
/// than its ceiling allows — but never more.
fn apply_launch_authority(
    fleet: &str,
    launch: &crate::fleet::exact::ExactMemberLaunch,
    request: &mut TaskRequest,
) -> Result<(), DriverError> {
    let authority = &launch.authority;

    // Identity first: an envelope stamped onto the wrong member's request is a
    // widening as surely as a wider envelope would be.
    if request.profile.as_deref() != Some(launch.member_id.as_str())
        || request.role.as_deref() != Some(launch.member_role.as_str())
    {
        return Err(DriverError::Rejected(format!(
            "fleet `{fleet}`: task identity drifted between admission and launch (request \
             profile={:?} role={:?}, launch member `{}` role `{}`); the launch is refused rather \
             than run under an envelope resolved for a different member.",
            request.profile, request.role, launch.member_id, launch.member_role,
        )));
    }

    request.allowed_tools = authority.allowed_tools.clone();
    request.disallowed_tools = authority.disallowed_tools.clone();
    request.write_authority = Some(authority.write_authority.to_string());
    request.subagent_type = None;
    request.max_depth = Some(
        request
            .max_depth
            .map_or(authority.max_depth, |asked| asked.min(authority.max_depth)),
    );

    // The receipt records the fingerprint; the request now carries the envelope
    // it names. Recomputing the fingerprint from what was just stamped is the
    // check that the two describe each other — a mismatch here means a field
    // was added to the envelope and not to the stamping, which is exactly the
    // silent-gap failure this whole seam exists to prevent.
    let expected = authority.fingerprint();
    if launch.receipt.authority_fingerprint.as_deref() != Some(expected.as_str()) {
        return Err(DriverError::Rejected(format!(
            "fleet `{fleet}`: member `{}` produced a receipt whose authority fingerprint does not \
             match the envelope being installed (receipt={:?} envelope={expected}). Failing \
             closed.",
            launch.member_id, launch.receipt.authority_fingerprint,
        )));
    }
    Ok(())
}

// Pre-existing spawn signature that grew `vm_cancel` for the cancel-interrupt
// wiring; the args mirror one workflow run's context and are consumed once.
#[allow(clippy::too_many_arguments)]
async fn run_workflow_vm(
    run_id: String,
    source: String,
    spec: Option<WorkflowSpec>,
    args: Value,
    driver: Arc<SubAgentWorkflowDriver>,
    state: Arc<WorkflowWorkspaceState>,
    context: ToolContext,
    vm_cancel: WorkflowRunCancel,
) {
    let result = WorkflowVm::new()
        .run_script_with_cancel(&source, args, driver.clone(), vm_cancel)
        .await;
    let mut status = WorkflowRunStatus::Completed;
    let mut output = None;
    let mut error = None;
    match result {
        Ok(value) => {
            if let Some(gate_error) = driver.terminal_gate_failure() {
                status = WorkflowRunStatus::Failed;
                error = Some(gate_error);
            } else {
                output = Some(value);
            }
        }
        Err(err) => {
            status = WorkflowRunStatus::Failed;
            error = Some(err.to_string());
        }
    }
    let snapshot = {
        let mut runs_guard = match state.runs.lock() {
            Ok(guard) => guard,
            Err(_) => {
                state.mark_owner_missing(&run_id);
                return;
            }
        };
        let Some(record) = runs_guard.get_mut(&run_id) else {
            state.mark_owner_missing(&run_id);
            return;
        };
        if record.status != WorkflowRunStatus::Cancelled {
            // Receipt honesty: a script that returns a value has not
            // necessarily orchestrated anything. Classify against the slot
            // ledger — every requested task either became a child with a
            // terminal record or landed in `dispatch_failures` (driver
            // rejections and, via `ProgressEvent::TaskRejected`, VM-level
            // rejections that previously vanished into null slots).
            if status == WorkflowRunStatus::Completed {
                let task_records = driver.task_records_snapshot();
                let failed_children = task_records
                    .iter()
                    .filter(|task| task.status == IrWorkflowRunStatus::Failed)
                    .count();
                let rejected = record.dispatch_failures.len();
                if record.child_ids.is_empty() && rejected > 0 {
                    // #5035: every dispatch was rejected before a child ran.
                    status = WorkflowRunStatus::Failed;
                    error = Some(format!(
                        "no child agents ran: all {rejected} task dispatch(es) were rejected; first: {}",
                        record.dispatch_failures[0].message
                    ));
                } else if failed_children > 0 || rejected > 0 {
                    status = WorkflowRunStatus::Degraded;
                    let mut parts = Vec::new();
                    if failed_children > 0 {
                        parts.push(format!(
                            "{failed_children} of {} task(s) failed",
                            task_records.len()
                        ));
                    }
                    if rejected > 0 {
                        parts.push(format!("{rejected} dispatch(es) were rejected"));
                    }
                    error = Some(format!(
                        "completed with dropped slots: {}; the recorded result may be partial",
                        parts.join(" and ")
                    ));
                }
            }
            record.status = status;
            record.result = output;
            record.error = error.clone();
            record.execution = spec.as_ref().map(|spec| {
                execution_from_declarative_spec(spec, driver.task_records_snapshot(), status)
            });
            record.completed_at_ms = Some(now_ms());
        }
        record.clone()
    };
    let verify_on_complete = state
        .runs
        .lock()
        .ok()
        .and_then(|guard| guard.get(&run_id).map(|record| record.verify_on_complete))
        .unwrap_or(false);
    if status == WorkflowRunStatus::Completed && verify_on_complete {
        match run_workflow_completion_gates(&context).await {
            Ok(verification) => {
                if let Ok(mut runs_guard) = state.runs.lock()
                    && let Some(record) = runs_guard.get_mut(&run_id)
                {
                    record.verification = Some(verification);
                }
            }
            Err(err) => {
                if let Ok(mut runs_guard) = state.runs.lock()
                    && let Some(record) = runs_guard.get_mut(&run_id)
                {
                    record.status = WorkflowRunStatus::Failed;
                    record.error = Some(format!("verification gates failed: {err}"));
                }
            }
        }
    }
    let final_budget = driver.current_budget_snapshot();
    // Reconcile run-wide usage totals from per-task telemetry (#2974).
    let run_usage = run_usage_totals(&driver.task_records_snapshot());
    let snapshot = state
        .runs
        .lock()
        .ok()
        .and_then(|mut guard| {
            let record = guard.get_mut(&run_id)?;
            if record.status != WorkflowRunStatus::Cancelled {
                record.lifecycle_seq = record.lifecycle_seq.saturating_add(1);
                if run_usage.is_some() {
                    record.usage = run_usage.clone();
                }
                let budget_event = WorkflowUiEvent::new(budget_event_kind(final_budget));
                let completed = WorkflowUiEvent::new(WorkflowUiEventKind::RunCompleted {
                    status: record.status,
                    error: record.error.clone(),
                    usage: run_usage.clone(),
                });
                record.push_event(budget_event.clone());
                record.push_event(completed.clone());
                // Live stream terminal events even when recorded outside the
                // driver helper (completion path).
                driver.emit_ui_event(&budget_event);
                driver.emit_ui_event(&completed);
            }
            Some(record.clone())
        })
        .unwrap_or(snapshot);
    if state.try_record_snapshot(&snapshot).is_ok() {
        state.reconcile_snapshot(&snapshot);
    } else {
        state.mark_owner_missing(&run_id);
    }
    write_run_report_artifact(&context.workspace, &snapshot);
    if let Ok(mut controllers_guard) = state.controllers.lock() {
        controllers_guard.remove(&run_id);
    }
}

/// Persist a durable per-run report under `.codewhale/reports/<run_id>.md`
/// so a settled background run leaves one synthesized artifact even after
/// the session ends. Best-effort: report IO never affects the run outcome.
fn write_run_report_artifact(workspace: &Path, record: &WorkflowRunRecord) {
    if !matches!(
        record.status,
        WorkflowRunStatus::Completed
            | WorkflowRunStatus::Degraded
            | WorkflowRunStatus::Failed
            | WorkflowRunStatus::Cancelled
    ) {
        return;
    }
    // Run ids are generated slugs, but never trust one as a path segment.
    let safe_id: String = record
        .run_id
        .chars()
        .filter(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_'))
        .collect();
    if safe_id.is_empty() {
        return;
    }
    let dir = workspace.join(".codewhale").join("reports");
    if let Err(err) = std::fs::create_dir_all(&dir) {
        crate::logging::warn(format!(
            "workflow report dir {} not created: {err}",
            dir.display()
        ));
        return;
    }
    let path = dir.join(format!("{safe_id}.md"));
    if let Err(err) = std::fs::write(&path, render_run_report(record)) {
        crate::logging::warn(format!(
            "workflow report {} not written: {err}",
            path.display()
        ));
    }
}

fn render_run_report(record: &WorkflowRunRecord) -> String {
    let mut out = String::new();
    out.push_str(&format!("# Workflow run {}\n\n", record.run_id));
    out.push_str(&format!("- status: {:?}\n", record.status));
    if let Some(goal) = record.workflow_goal.as_deref() {
        out.push_str(&format!("- goal: {goal}\n"));
    }
    if let Some(source) = record.source_path.as_deref() {
        out.push_str(&format!("- source: {}\n", source.display()));
    }
    out.push_str(&format!("- started_at_ms: {}\n", record.started_at_ms));
    if let Some(completed) = record.completed_at_ms {
        out.push_str(&format!("- completed_at_ms: {completed}\n"));
    }
    if let Some(budget) = record.token_budget {
        out.push_str(&format!("- token_budget: {budget}\n"));
    }
    out.push_str(&format!("- child_agents: {}\n", record.child_ids.len()));
    if let Some(error) = record.error.as_deref() {
        out.push_str(&format!("- error: {error}\n"));
    }
    if !record.dispatch_failures.is_empty() {
        out.push_str(&format!(
            "\n## Dispatch failures ({})\n\n",
            record.dispatch_failures.len()
        ));
        for failure in &record.dispatch_failures {
            let slot = failure
                .label
                .as_deref()
                .or(failure.phase.as_deref())
                .unwrap_or("task");
            out.push_str(&format!("- {slot}: {}\n", failure.message));
        }
    }
    if !record.gate_status.is_empty() {
        out.push_str("\n## Gates\n\n");
        for line in &record.gate_status {
            out.push_str(&format!("- {line:?}\n"));
        }
    }
    if !record.progress.is_empty() {
        out.push_str("\n## Progress\n\n");
        for line in &record.progress {
            out.push_str(&format!("- {line}\n"));
        }
    }
    if !record.schema_errors.is_empty() {
        out.push_str(&format!(
            "\n## Schema errors ({})\n\n",
            record.schema_errors.len()
        ));
    }
    if let Some(result) = record.result.as_ref() {
        out.push_str("\n## Result\n\n```json\n");
        out.push_str(&serde_json::to_string_pretty(result).unwrap_or_else(|_| result.to_string()));
        out.push_str("\n```\n");
    }
    if let Some(verification) = record.verification.as_ref() {
        out.push_str("\n## Verification\n\n```json\n");
        out.push_str(
            &serde_json::to_string_pretty(verification)
                .unwrap_or_else(|_| verification.to_string()),
        );
        out.push_str("\n```\n");
    }
    out
}

fn session_workflow_config_store()
-> &'static Mutex<HashMap<PathBuf, codewhale_config::WorkflowConfigToml>> {
    static STORE: OnceLock<Mutex<HashMap<PathBuf, codewhale_config::WorkflowConfigToml>>> =
        OnceLock::new();
    STORE.get_or_init(|| Mutex::new(HashMap::new()))
}

fn workflow_session_key(workspace: &Path) -> PathBuf {
    workspace
        .canonicalize()
        .unwrap_or_else(|_| workspace.to_path_buf())
}

/// Install the session `[workflow]` table after a config.toml reload (or a
/// test mutation). `/workflow settings` and the workflow tool both read this
/// so a refresh cannot leave the two surfaces disagreeing.
pub(crate) fn set_session_workflow_config(
    workspace: &Path,
    config: codewhale_config::WorkflowConfigToml,
) {
    session_workflow_config_store()
        .lock()
        .unwrap_or_else(|poison| poison.into_inner())
        .insert(workflow_session_key(workspace), config);
}

/// The refreshed session `[workflow]` table, if a reload (or test) installed
/// one for this workspace.
pub(crate) fn session_workflow_config(
    workspace: &Path,
) -> Option<codewhale_config::WorkflowConfigToml> {
    session_workflow_config_store()
        .lock()
        .unwrap_or_else(|poison| poison.into_inner())
        .get(&workflow_session_key(workspace))
        .cloned()
}

/// The effective `[workflow]` table: the refreshed session table when one has
/// been installed, otherwise the runtime snapshot, otherwise product defaults.
fn workflow_config_for(runtime: &SubAgentRuntime) -> codewhale_config::WorkflowConfigToml {
    session_workflow_config(&runtime.context.workspace).unwrap_or_else(|| {
        runtime
            .api_config
            .as_deref()
            .map(crate::config::Config::workflow_config)
            .unwrap_or_default()
    })
}

fn workflow_result_for(
    run_id: &str,
    state: Arc<WorkflowWorkspaceState>,
) -> Result<ToolResult, ToolError> {
    let record = {
        let runs_guard = lock_mutex(&state.runs)?;
        runs_guard.get(run_id).cloned().ok_or_else(|| {
            ToolError::invalid_input(format!("Unknown workflow run_id '{run_id}'"))
        })?
    };
    let journal_path = state.journal_path().to_path_buf();
    let (payload, bounds) = bounded_run_record_value(&record, &journal_path);
    let mut result =
        ToolResult::json(&payload).map_err(|err| ToolError::execution_failed(err.to_string()))?;
    let summary = record.summary();
    result.metadata = Some(json!({
        "run_id": summary.run_id,
        "status": summary.status,
        "terminal": summary.status != WorkflowRunStatus::Running,
        "child_count": summary.child_count,
        "schema_error_count": summary.schema_error_count,
        "dispatch_failure_count": summary.dispatch_failure_count,
        "event_count": summary.event_count,
        "events_returned": bounds.events_returned,
        "events_omitted": bounds.events_omitted,
        "dispatch_failures_returned": bounds.dispatch_failures_returned,
        "dispatch_failures_omitted": bounds.dispatch_failures_omitted,
        "events_dropped": summary.events_dropped,
        "last_event_type": summary.last_event_type,
        "leaf_count": summary.leaf_count,
        "branch_count": summary.branch_count,
        "control_count": summary.control_count,
        "execution_status": summary.execution_status,
        "gate_count": summary.gate_count,
        "blocked_gate_count": summary.blocked_gate_count,
        "gate_status": summary.gate_status,
        // #2974: bounded payload; full detail stays in the durable journal.
        "truncated": bounds.truncated(),
        "payload_budget_chars": WORKFLOW_RESULT_MAX_CHARS,
        "journal_path": journal_path.display().to_string(),
        // #4126: durable plan-approval receipt for audit/receipt consumers.
        "plan_approval": record.plan_approval,
    }));
    Ok(result)
}

/// What `bounded_run_record_value` clipped out of the model-facing payload.
#[derive(Debug, Default)]
struct RunPayloadBounds {
    events_returned: usize,
    events_omitted: usize,
    progress_omitted: usize,
    dispatch_failures_returned: usize,
    dispatch_failures_omitted: usize,
    dispatch_failure_fields_truncated: usize,
    result_truncated: bool,
    leaf_outputs_truncated: usize,
}

impl RunPayloadBounds {
    fn truncated(&self) -> bool {
        self.events_omitted > 0
            || self.progress_omitted > 0
            || self.dispatch_failures_omitted > 0
            || self.dispatch_failure_fields_truncated > 0
            || self.result_truncated
            || self.leaf_outputs_truncated > 0
    }
}

/// Build the model-facing view of a run record (#2974). The JSON shape is
/// identical to the full record (panel hydration and history cards keep
/// working unchanged), but the unbounded parts are clipped:
///
/// - `events`: newest `WORKFLOW_RESULT_EVENTS_TAIL` entries.
/// - `progress`: newest `WORKFLOW_RESULT_PROGRESS_TAIL` lines.
/// - `dispatch_failures`: newest `WORKFLOW_RESULT_DISPATCH_FAILURES_TAIL`
///   entries with bounded string fields.
/// - `result` / `verification`: collapsed to a preview + journal pointer
///   when the serialized value exceeds `WORKFLOW_RESULT_VALUE_MAX_CHARS`.
/// - `execution.leaf_results[*].output`: per-leaf preview capped at
///   `WORKFLOW_RESULT_LEAF_OUTPUT_MAX_CHARS`.
///
/// Full detail remains available in `.codewhale/workflow-runs.jsonl`; every
/// clip adds an explicit note/pointer so the model can fetch more on demand.
fn bounded_run_record_value(
    record: &WorkflowRunRecord,
    journal_path: &Path,
) -> (Value, RunPayloadBounds) {
    let mut bounds = RunPayloadBounds::default();
    let journal = journal_path.display().to_string();
    let mut value = serde_json::to_value(record).unwrap_or_else(|_| json!({}));
    let Some(obj) = value.as_object_mut() else {
        return (value, bounds);
    };

    if let Some(events) = obj.get_mut("events").and_then(Value::as_array_mut) {
        if events.len() > WORKFLOW_RESULT_EVENTS_TAIL {
            let omitted = events.len() - WORKFLOW_RESULT_EVENTS_TAIL;
            events.drain(..omitted);
            bounds.events_omitted = omitted;
        }
        bounds.events_returned = events.len();
    }
    if bounds.events_omitted > 0 {
        obj.insert(
            "events_note".to_string(),
            json!(format!(
                "showing the newest {} of {} events; full stream: {journal}",
                bounds.events_returned,
                bounds.events_returned + bounds.events_omitted,
            )),
        );
    }

    if let Some(progress) = obj.get_mut("progress").and_then(Value::as_array_mut)
        && progress.len() > WORKFLOW_RESULT_PROGRESS_TAIL
    {
        let omitted = progress.len() - WORKFLOW_RESULT_PROGRESS_TAIL;
        progress.drain(..omitted);
        bounds.progress_omitted = omitted;
        obj.insert(
            "progress_note".to_string(),
            json!(format!(
                "showing the newest {WORKFLOW_RESULT_PROGRESS_TAIL} of {} progress lines; full log: {journal}",
                omitted + WORKFLOW_RESULT_PROGRESS_TAIL,
            )),
        );
    }

    if let Some(failures) = obj
        .get_mut("dispatch_failures")
        .and_then(Value::as_array_mut)
    {
        if failures.len() > WORKFLOW_RESULT_DISPATCH_FAILURES_TAIL {
            let omitted = failures.len() - WORKFLOW_RESULT_DISPATCH_FAILURES_TAIL;
            failures.drain(..omitted);
            bounds.dispatch_failures_omitted = omitted;
        }
        bounds.dispatch_failures_returned = failures.len();
        for failure in failures {
            let Some(fields) = failure.as_object_mut() else {
                continue;
            };
            for key in ["label", "phase", "message"] {
                let Some(slot) = fields.get_mut(key) else {
                    continue;
                };
                let Some(raw) = slot.as_str() else {
                    continue;
                };
                if raw.chars().count() > WORKFLOW_RESULT_DISPATCH_FAILURE_FIELD_MAX_CHARS {
                    *slot = Value::String(truncate_chars(
                        raw,
                        WORKFLOW_RESULT_DISPATCH_FAILURE_FIELD_MAX_CHARS,
                    ));
                    bounds.dispatch_failure_fields_truncated += 1;
                }
            }
        }
    }
    if bounds.dispatch_failures_omitted > 0 || bounds.dispatch_failure_fields_truncated > 0 {
        obj.insert(
            "dispatch_failures_note".to_string(),
            json!(format!(
                "showing {} of {} dispatch failures with bounded fields; full record: {journal}",
                bounds.dispatch_failures_returned,
                bounds.dispatch_failures_returned + bounds.dispatch_failures_omitted,
            )),
        );
    }

    for key in ["result", "verification"] {
        let Some(raw) = obj.get(key).filter(|value| !value.is_null()) else {
            continue;
        };
        let text = raw.to_string();
        if text.chars().count() > WORKFLOW_RESULT_VALUE_MAX_CHARS {
            obj.insert(
                key.to_string(),
                json!({
                    "truncated": true,
                    "omitted_chars": text.chars().count() - WORKFLOW_RESULT_VALUE_MAX_CHARS,
                    "preview": truncate_chars(&text, WORKFLOW_RESULT_VALUE_MAX_CHARS),
                    "full_detail": journal,
                }),
            );
            bounds.result_truncated = true;
        }
    }

    if let Some(leaves) = obj
        .get_mut("execution")
        .and_then(|execution| execution.get_mut("leaf_results"))
        .and_then(Value::as_array_mut)
    {
        for leaf in leaves {
            let too_long = leaf
                .get("output")
                .and_then(Value::as_str)
                .is_some_and(|output| {
                    output.chars().count() > WORKFLOW_RESULT_LEAF_OUTPUT_MAX_CHARS
                });
            if too_long
                && let Some(slot) = leaf.get_mut("output")
                && let Some(output) = slot.as_str()
            {
                let clipped = format!(
                    "{} [leaf output truncated to {WORKFLOW_RESULT_LEAF_OUTPUT_MAX_CHARS} chars; full text: {journal}]",
                    truncate_chars(output, WORKFLOW_RESULT_LEAF_OUTPUT_MAX_CHARS),
                );
                *slot = Value::String(clipped);
                bounds.leaf_outputs_truncated += 1;
            }
        }
    }

    (value, bounds)
}

/// Char-boundary-safe truncation with an ellipsis (precedent:
/// `cargo_failure_summary::truncate_chars`).
fn truncate_chars(text: &str, max_chars: usize) -> String {
    if let Some((idx, _)) = text.char_indices().nth(max_chars) {
        if max_chars < 3 {
            return text[..idx].to_string();
        }
        let truncate_at = text
            .char_indices()
            .nth(max_chars - 3)
            .map(|(idx, _)| idx)
            .unwrap_or(0);
        format!("{}...", &text[..truncate_at])
    } else {
        text.to_string()
    }
}

#[derive(Debug)]
struct WorkflowSource {
    source: String,
    path: Option<PathBuf>,
    spec: Option<WorkflowSpec>,
}

fn workflow_source(input: &Value, context: &ToolContext) -> Result<WorkflowSource, ToolError> {
    let script = match optional_str(input, "script")? {
        Some(script) => Some(script),
        None => optional_str(input, "source")?,
    }
    .map(str::to_string);
    let source_path = match optional_str(input, "source_path")? {
        Some(path) => Some(path),
        None => optional_str(input, "path")?,
    };
    let plan = input.get("plan").filter(|value| !value.is_null());

    let provided = [
        script.as_ref().is_some_and(|s| !s.trim().is_empty()),
        source_path.is_some(),
        plan.is_some(),
    ]
    .into_iter()
    .filter(|present| *present)
    .count();
    if provided > 1 {
        return Err(ToolError::invalid_input(
            "Use exactly one of script, source_path, or plan",
        ));
    }

    match (script, source_path, plan) {
        (Some(source), None, None) if !source.trim().is_empty() => {
            workflow_source_from_raw(source, None)
        }
        (None, Some(path), None) => read_workflow_source_path(path, context),
        (None, None, Some(plan_value)) => workflow_source_from_plan(plan_value),
        _ => Err(ToolError::missing_field("script")),
    }
}

/// Planner-to-workflow structured launch path (#4124).
///
/// Accepts product-shaped plans (`goal` + `phases`/`children`) or IR-shaped
/// plans (`goal` + `nodes`), validates them, and lowers to imperative JS that
/// uses `parallel()` (partial success) rather than raw `Promise.all()`.
fn workflow_source_from_plan(plan_value: &Value) -> Result<WorkflowSource, ToolError> {
    let spec = structured_plan_to_workflow_spec(plan_value)?;
    let lowered = lower_declarative_workflow_to_imperative_js(&spec)?;
    Ok(WorkflowSource {
        source: lowered,
        path: None,
        spec: Some(spec),
    })
}

#[derive(Debug, Deserialize)]
struct StructuredWorkflowPlan {
    goal: String,
    #[serde(default)]
    risk: Option<String>,
    #[serde(default)]
    max_children: Option<usize>,
    #[serde(default)]
    token_budget: Option<u64>,
    #[serde(default)]
    phases: Vec<StructuredPlanPhase>,
    #[serde(default)]
    children: Vec<StructuredPlanChild>,
    /// Escape hatch: full Workflow IR nodes (kind/spec or JS authoring shapes).
    #[serde(default)]
    nodes: Option<Value>,
    /// Optional Workflow-owned gate specs (#4179).
    #[serde(default)]
    gates: Vec<GateSpec>,
}

#[derive(Debug, Deserialize)]
struct StructuredPlanPhase {
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    parallel: Option<bool>,
    #[serde(default)]
    children: Vec<StructuredPlanChild>,
}

#[derive(Debug, Deserialize)]
struct StructuredPlanChild {
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    label: Option<String>,
    #[serde(alias = "description")]
    prompt: String,
    #[serde(default, alias = "type", alias = "agent_type")]
    agent_type: Option<String>,
    /// Fleet role name (#4177). Preferred step identity; resolved via roster.
    #[serde(default)]
    role: Option<String>,
    #[serde(default)]
    profile: Option<String>,
    #[serde(default)]
    mode: Option<String>,
    #[serde(default)]
    file_scope: Vec<String>,
}

fn structured_plan_to_workflow_spec(plan_value: &Value) -> Result<WorkflowSpec, ToolError> {
    if !plan_value.is_object() {
        return Err(ToolError::invalid_input(
            "Workflow plan must be a JSON object with goal and phases/children (or nodes)",
        ));
    }

    let plan: StructuredWorkflowPlan =
        serde_json::from_value(plan_value.clone()).map_err(|err| {
            ToolError::invalid_input(format!("Invalid structured Workflow plan: {err}"))
        })?;

    let goal = plan.goal.trim();
    if goal.is_empty() {
        return Err(ToolError::invalid_input(
            "Workflow plan goal must be a non-empty string",
        ));
    }

    // IR / declarative nodes escape hatch: re-parse as workflow({...}) object.
    if let Some(nodes) = plan.nodes.as_ref() {
        if !nodes.is_array() {
            return Err(ToolError::invalid_input(
                "Workflow plan.nodes must be an array of workflow nodes",
            ));
        }
        let mut object = plan_value.clone();
        if let Some(obj) = object.as_object_mut() {
            obj.insert("goal".to_string(), Value::String(goal.to_string()));
            if let Some(token_budget) = plan.token_budget {
                let mut budget = obj.get("budget").cloned().unwrap_or_else(|| json!({}));
                if let Some(budget_obj) = budget.as_object_mut() {
                    budget_obj.insert("max_tokens".to_string(), json!(token_budget));
                }
                obj.insert("budget".to_string(), budget);
            }
        }
        let wrapped = format!("workflow({});", object);
        return compile_javascript_workflow("<structured plan>", &wrapped).map_err(|err| {
            ToolError::invalid_input(format!("Invalid structured Workflow plan nodes: {err}"))
        });
    }

    let default_mode = plan_risk_to_mode(plan.risk.as_deref())?;
    let mut nodes = Vec::new();

    if !plan.phases.is_empty() {
        for (phase_index, phase) in plan.phases.iter().enumerate() {
            let phase_id = phase
                .id
                .as_deref()
                .or(phase.title.as_deref())
                .map(str::trim)
                .filter(|id| !id.is_empty())
                .map(str::to_string)
                .unwrap_or_else(|| format!("phase-{}", phase_index + 1));
            let children = plan_children_to_leaves(
                &phase.children,
                default_mode,
                plan.token_budget,
                &phase_id,
            )?;
            if children.is_empty() {
                return Err(ToolError::invalid_input(format!(
                    "Workflow plan phase '{phase_id}' must declare at least one child"
                )));
            }
            let parallel = phase.parallel.unwrap_or(children.len() > 1);
            if parallel && children.len() > 1 {
                nodes.push(WorkflowNode::BranchSet(BranchSpec {
                    id: phase_id,
                    description: phase.title.clone(),
                    parallel: true,
                    budget: BudgetSpec {
                        max_tokens: plan.token_budget,
                        ..BudgetSpec::default()
                    },
                    permissions: Default::default(),
                    model_policy: Default::default(),
                    children: children.into_iter().map(WorkflowNode::Leaf).collect(),
                }));
            } else if children.len() == 1 {
                nodes.push(WorkflowNode::Leaf(
                    children.into_iter().next().expect("one child"),
                ));
            } else {
                nodes.push(WorkflowNode::Sequence(SequenceSpec {
                    id: phase_id,
                    children: children.into_iter().map(WorkflowNode::Leaf).collect(),
                }));
            }
        }
    } else if !plan.children.is_empty() {
        let children =
            plan_children_to_leaves(&plan.children, default_mode, plan.token_budget, "plan")?;
        if children.len() == 1 {
            nodes.push(WorkflowNode::Leaf(
                children.into_iter().next().expect("one child"),
            ));
        } else {
            nodes.push(WorkflowNode::BranchSet(BranchSpec {
                id: "plan".to_string(),
                description: Some(goal.to_string()),
                parallel: true,
                budget: BudgetSpec {
                    max_tokens: plan.token_budget,
                    ..BudgetSpec::default()
                },
                permissions: Default::default(),
                model_policy: Default::default(),
                children: children.into_iter().map(WorkflowNode::Leaf).collect(),
            }));
        }
    } else {
        return Err(ToolError::invalid_input(
            "Workflow plan must include phases, children, or nodes",
        ));
    }

    let mut total_children = 0usize;
    count_plan_leaves(&nodes, &mut total_children);
    if let Some(max_children) = plan.max_children
        && total_children > max_children
    {
        return Err(ToolError::invalid_input(format!(
            "Workflow plan declares {total_children} children which exceeds max_children={max_children}"
        )));
    }

    Ok(WorkflowSpec {
        id: None,
        goal: goal.to_string(),
        description: plan.risk.clone(),
        budget: BudgetSpec {
            max_tokens: plan.token_budget,
            ..BudgetSpec::default()
        },
        permissions: Default::default(),
        model_policy: Default::default(),
        promotion_policy: Default::default(),
        gates: plan.gates,
        nodes,
    })
}

fn plan_risk_to_mode(risk: Option<&str>) -> Result<TaskMode, ToolError> {
    match risk.map(str::trim).filter(|s| !s.is_empty()) {
        None | Some("read_only") | Some("readonly") | Some("low") | Some("safe") => {
            Ok(TaskMode::ReadOnly)
        }
        Some("writes") | Some("write") | Some("read_write") | Some("readwrite")
        | Some("medium") => Ok(TaskMode::ReadWrite),
        Some("elevated") | Some("high") | Some("shell") | Some("network") => {
            // Elevated risk still launches as read_write; approval gates (#4126)
            // consume the risk string via plan description.
            Ok(TaskMode::ReadWrite)
        }
        Some(other) => Err(ToolError::invalid_input(format!(
            "Invalid plan risk '{other}'. Use read_only, writes, or elevated."
        ))),
    }
}

fn plan_children_to_leaves(
    children: &[StructuredPlanChild],
    default_mode: TaskMode,
    token_budget: Option<u64>,
    phase_id: &str,
) -> Result<Vec<LeafSpec>, ToolError> {
    if children.is_empty() {
        return Ok(Vec::new());
    }
    let mut leaves = Vec::with_capacity(children.len());
    for (index, child) in children.iter().enumerate() {
        let prompt = child.prompt.trim();
        if prompt.is_empty() {
            return Err(ToolError::invalid_input(format!(
                "Workflow plan child {} in phase '{phase_id}' must have a non-empty prompt",
                index + 1
            )));
        }
        let id = child
            .id
            .as_deref()
            .or(child.label.as_deref())
            .map(str::trim)
            .filter(|id| !id.is_empty())
            .map(str::to_string)
            .unwrap_or_else(|| format!("{phase_id}-child-{}", index + 1));
        let agent_type = parse_plan_agent_type(child.agent_type.as_deref())?;
        let mode = match child.mode.as_deref().map(str::trim) {
            None | Some("") => default_mode,
            Some("read_only") | Some("readonly") => TaskMode::ReadOnly,
            Some("read_write") | Some("readwrite") | Some("writes") | Some("write") => {
                TaskMode::ReadWrite
            }
            Some(other) => {
                return Err(ToolError::invalid_input(format!(
                    "Invalid plan child mode '{other}' on '{id}'. Use read_only or read_write."
                )));
            }
        };
        let role = child
            .role
            .as_deref()
            .map(str::trim)
            .filter(|r| !r.is_empty())
            .map(|r| r.to_ascii_lowercase());
        let profile = child
            .profile
            .as_deref()
            .map(str::trim)
            .filter(|p| !p.is_empty())
            .map(|p| p.to_ascii_lowercase());
        leaves.push(LeafSpec {
            id,
            prompt: prompt.to_string(),
            agent_type,
            role,
            profile,
            mode,
            isolation: Default::default(),
            file_scope: child.file_scope.clone(),
            depends_on_results: Vec::new(),
            budget: BudgetSpec {
                max_tokens: token_budget,
                ..BudgetSpec::default()
            },
            permissions: Default::default(),
            model_policy: Default::default(),
        });
    }
    Ok(leaves)
}

/// Plan-child `type` vocabulary. Accepts the Agent tool's canonical types and
/// legacy aliases so the same option value works for direct Agent dispatch and
/// for Workflow plan children (#5035), normalized onto the workflow IR schema.
/// Rejections use the Agent tool's error contract ("Invalid sub-agent type
/// `'<value>'. Use: ...`") with field-specific guidance.
fn parse_plan_agent_type(raw: Option<&str>) -> Result<AgentType, ToolError> {
    let Some(kind) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
        return Ok(AgentType::General);
    };
    match kind.to_ascii_lowercase().as_str() {
        "general" | "worker" | "delegate" => Ok(AgentType::General),
        "explore" | "explorer" | "scout" => Ok(AgentType::Explore),
        "plan" | "planner" | "awaiter" => Ok(AgentType::Plan),
        // Consultant/oracle/advisor are the Agent tool's read-only advisory
        // roles; Review is the workflow IR's read-only advisory posture.
        "review" | "reviewer" | "consultant" | "oracle" | "advisor" => Ok(AgentType::Review),
        "implementer" | "implement" | "builder" => Ok(AgentType::Implementer),
        "verifier" | "verify" => Ok(AgentType::Verifier),
        "custom" => Err(ToolError::invalid_input(
            "Invalid sub-agent type 'custom' for a Workflow plan child: custom requires an \
             explicit allowed_tools list, which plan children cannot declare. Use role/profile \
             or another type.",
        )),
        _ => Err(ToolError::invalid_input(format!(
            "Invalid sub-agent type '{kind}'. Use: worker, scout, planner, reviewer, builder, \
             verifier (legacy aliases remain accepted: general, explore/explorer, plan/awaiter, \
             review, implementer, consultant/oracle/advisor)."
        ))),
    }
}

fn count_plan_leaves(nodes: &[WorkflowNode], total: &mut usize) {
    for node in nodes {
        match node {
            WorkflowNode::Leaf(_) => *total += 1,
            WorkflowNode::BranchSet(spec) => count_plan_leaves(&spec.children, total),
            WorkflowNode::Sequence(spec) => count_plan_leaves(&spec.children, total),
            WorkflowNode::Reduce(_)
            | WorkflowNode::TeacherReview(_)
            | WorkflowNode::LoopUntil(_)
            | WorkflowNode::Cond(_)
            | WorkflowNode::Expand(_) => {}
        }
    }
}

fn read_workflow_source_path(
    path: &str,
    context: &ToolContext,
) -> Result<WorkflowSource, ToolError> {
    let raw = Path::new(path);
    let joined = if raw.is_absolute() {
        raw.to_path_buf()
    } else {
        context.workspace.join(raw)
    };
    let canonical = joined.canonicalize().map_err(|err| {
        ToolError::invalid_input(format!(
            "Failed to resolve workflow source_path '{path}': {err}"
        ))
    })?;
    if !context.trust_mode {
        let workspace = context
            .workspace
            .canonicalize()
            .unwrap_or_else(|_| context.workspace.clone());
        // The user-global saved-workflow store is a first-class source
        // alongside the workspace: `~/.codewhale/workflows/*.workflow.js`
        // definitions surface as slash commands and must launch from any
        // workspace without trust_mode.
        let home_store = crate::config::effective_home_dir()
            .map(|home| home.join(".codewhale").join("workflows"))
            .and_then(|dir| dir.canonicalize().ok());
        let inside_home_store = home_store
            .as_deref()
            .is_some_and(|dir| canonical.starts_with(dir));
        if !canonical.starts_with(&workspace) && !inside_home_store {
            return Err(ToolError::permission_denied(format!(
                "workflow source_path must stay inside the workspace or ~/.codewhale/workflows: {}",
                canonical.display()
            )));
        }
    }
    let source = std::fs::read_to_string(&canonical).map_err(|err| {
        ToolError::execution_failed(format!(
            "Failed to read workflow source_path '{}': {err}",
            canonical.display()
        ))
    })?;
    workflow_source_from_raw(source, Some(canonical))
}

fn workflow_source_from_raw(
    source: String,
    path: Option<PathBuf>,
) -> Result<WorkflowSource, ToolError> {
    let adapted = adapt_workflow_source(&source, path.as_deref())?;
    Ok(WorkflowSource {
        source: adapted.source,
        path,
        spec: adapted.spec,
    })
}

struct AdaptedWorkflowSource {
    source: String,
    spec: Option<WorkflowSpec>,
}

fn adapt_workflow_source(
    source: &str,
    path: Option<&Path>,
) -> Result<AdaptedWorkflowSource, ToolError> {
    if !looks_like_declarative_workflow(source) {
        return Ok(AdaptedWorkflowSource {
            source: source.to_string(),
            spec: None,
        });
    }

    let identifier = path
        .map(|path| path.display().to_string())
        .unwrap_or_else(|| "<inline workflow>".to_string());
    let extension = path
        .and_then(Path::extension)
        .and_then(|extension| extension.to_str())
        .unwrap_or_default();
    let spec = if extension.eq_ignore_ascii_case("ts") {
        compile_typescript_workflow(&identifier, source)
    } else {
        compile_javascript_workflow(&identifier, source)
    }
    .map_err(|err| {
        ToolError::invalid_input(format!(
            "Failed to compile declarative Workflow source '{identifier}': {err}"
        ))
    })?;

    let lowered = lower_declarative_workflow_to_imperative_js(&spec)?;
    Ok(AdaptedWorkflowSource {
        source: lowered,
        spec: Some(spec),
    })
}

fn looks_like_declarative_workflow(source: &str) -> bool {
    // Match a top-level `workflow(...)` / `export default workflow(...)` call on
    // any line, ignoring leading indentation, so an indented (non-column-0)
    // declarative call is still recognized rather than misrun as an imperative
    // script (#dogfood 0.8.67).
    source.lines().any(|line| {
        let trimmed = line.trim_start();
        trimmed.starts_with("workflow(") || trimmed.starts_with("export default workflow(")
    })
}

fn lower_declarative_workflow_to_imperative_js(spec: &WorkflowSpec) -> Result<String, ToolError> {
    let mut lowerer = DeclarativeWorkflowLowerer::default();
    lowerer.line("\"use strict\";");
    lowerer.line("const __results = {};");
    lowerer.line(format!(
        "phase({});",
        js_string(&format!("workflow: {}", spec.goal))
    ));
    for node in &spec.nodes {
        lowerer.lower_node(node, None)?;
    }
    lowerer.line("return __results;");
    Ok(lowerer.finish())
}

#[derive(Default)]
struct DeclarativeWorkflowLowerer {
    source: String,
    next_var: usize,
}

impl DeclarativeWorkflowLowerer {
    fn finish(self) -> String {
        self.source
    }

    fn line(&mut self, line: impl AsRef<str>) {
        self.source.push_str(line.as_ref());
        self.source.push('\n');
    }

    fn next_temp(&mut self, prefix: &str) -> String {
        let value = format!("__{prefix}_{}", self.next_var);
        self.next_var += 1;
        value
    }

    fn lower_node(&mut self, node: &WorkflowNode, phase: Option<&str>) -> Result<(), ToolError> {
        match node {
            WorkflowNode::Leaf(spec) => self.lower_leaf(spec, phase, /* parallel */ false),
            WorkflowNode::BranchSet(spec) => self.lower_branch(spec),
            WorkflowNode::Sequence(spec) => self.lower_sequence(spec),
            WorkflowNode::Reduce(spec) => self.lower_reduce(spec),
            WorkflowNode::TeacherReview(_) => Err(unsupported_declarative_node("teacher_review")),
            WorkflowNode::LoopUntil(_) => Err(unsupported_declarative_node("loop_until")),
            WorkflowNode::Cond(_) => Err(unsupported_declarative_node("cond")),
            WorkflowNode::Expand(_) => Err(unsupported_declarative_node("expand")),
        }
    }

    fn lower_leaf(
        &mut self,
        spec: &LeafSpec,
        phase: Option<&str>,
        parallel: bool,
    ) -> Result<(), ToolError> {
        self.line(format!(
            "__results[{}] = await task({});",
            js_string(&spec.id),
            leaf_task_options_expression(spec, phase, parallel)?
        ));
        Ok(())
    }

    fn lower_branch(&mut self, spec: &BranchSpec) -> Result<(), ToolError> {
        self.line(format!("phase({});", js_string(&spec.id)));
        if spec.parallel {
            let mut leaves = Vec::new();
            for child in &spec.children {
                let WorkflowNode::Leaf(leaf) = child else {
                    return Err(ToolError::invalid_input(format!(
                        "Declarative Workflow adapter only supports leaf children inside parallel branch '{}'",
                        spec.id
                    )));
                };
                leaves.push(leaf);
            }
            // #4124: use Workflow `parallel()` (all-settled / partial success)
            // instead of raw Promise.all, which aborts siblings on first failure.
            let temp = self.next_temp("parallel");
            self.line(format!("const {temp} = await parallel(["));
            for leaf in &leaves {
                // Parallel write-capable children default to worktree isolation
                // (#4120) unless the plan explicitly sets isolation: shared.
                self.line(format!(
                    "  () => task({}),",
                    leaf_task_options_expression(leaf, Some(&spec.id), /* parallel */ true)?
                ));
            }
            self.line("]);");
            for (index, leaf) in leaves.iter().enumerate() {
                self.line(format!(
                    "__results[{}] = {temp}[{index}];",
                    js_string(&leaf.id)
                ));
            }
            return Ok(());
        }

        for child in &spec.children {
            self.lower_node(child, Some(&spec.id))?;
        }
        Ok(())
    }

    fn lower_sequence(&mut self, spec: &SequenceSpec) -> Result<(), ToolError> {
        self.line(format!("phase({});", js_string(&spec.id)));
        for child in &spec.children {
            self.lower_node(child, Some(&spec.id))?;
        }
        Ok(())
    }

    fn lower_reduce(&mut self, spec: &ReduceSpec) -> Result<(), ToolError> {
        let inputs = result_inputs_expression(&spec.inputs);
        self.line(format!(
            "__results[{}] = await task({});",
            js_string(&spec.id),
            task_options_expression(
                format!(
                    "{} + \"\\n\\nInputs:\\n\" + {inputs}",
                    js_string(&spec.prompt)
                ),
                Some("plan"),
                None,
                None,
                false,
                None,
                None,
                None,
                Some("read_only"),
                &[],
                &spec.id,
                Some("reduce"),
                None,
            )
        ));
        Ok(())
    }
}

fn unsupported_declarative_node(kind: &str) -> ToolError {
    ToolError::invalid_input(format!(
        "Declarative Workflow adapter does not yet support {kind} nodes"
    ))
}

fn leaf_description(spec: &LeafSpec) -> String {
    let mut description = spec.prompt.trim().to_string();
    let mut metadata = Vec::new();
    metadata.push(format!("Workflow leaf id: {}", spec.id));
    metadata.push(format!("Mode: {}", task_mode_name(spec.mode)));
    if !spec.file_scope.is_empty() {
        metadata.push(format!("File scope: {}", spec.file_scope.join(", ")));
    }
    if !spec.depends_on_results.is_empty() {
        metadata.push(format!(
            "Depends on results: {}",
            spec.depends_on_results.join(", ")
        ));
    }
    if spec.budget != BudgetSpec::default() {
        let mut budget = Vec::new();
        if let Some(max_steps) = spec.budget.max_steps {
            budget.push(format!("max_steps={max_steps}"));
        }
        if let Some(timeout_secs) = spec.budget.timeout_secs {
            budget.push(format!("timeout_secs={timeout_secs}"));
        }
        if let Some(max_parallel) = spec.budget.max_parallel {
            budget.push(format!("max_parallel={max_parallel}"));
        }
        if let Some(max_tokens) = spec.budget.max_tokens {
            budget.push(format!("max_tokens={max_tokens}"));
        }
        if !budget.is_empty() {
            metadata.push(format!("Budget: {}", budget.join(", ")));
        }
    }
    if !metadata.is_empty() {
        description.push_str("\n\nWorkflow metadata:\n");
        for item in metadata {
            description.push_str("- ");
            description.push_str(&item);
            description.push('\n');
        }
    }
    description
}

fn leaf_task_options_expression(
    spec: &LeafSpec,
    phase: Option<&str>,
    parallel: bool,
) -> Result<String, ToolError> {
    validate_leaf_runtime_contract(spec)?;
    let worktree = leaf_wants_worktree(spec, parallel);
    let write_authority = match spec.mode {
        TaskMode::ReadOnly => "read_only",
        TaskMode::ReadWrite if worktree => "worktree_write",
        TaskMode::ReadWrite => "workspace_write",
    };
    let write_roots = if spec.mode == TaskMode::ReadWrite {
        spec.file_scope
            .iter()
            .map(|scope| codewhale_workflow::normalize_file_scope_root(scope))
            .collect::<Vec<_>>()
    } else {
        Vec::new()
    };
    Ok(task_options_expression(
        leaf_description_expression(spec),
        leaf_subagent_type(spec),
        spec.role.as_deref(),
        spec.profile.as_deref(),
        // Parallel write-capable children default to worktree isolation (#4120).
        // Explicit isolation: shared is the approved same-worktree override.
        worktree,
        spec.budget.max_tokens,
        spec.budget.max_steps,
        spec.budget.timeout_secs,
        Some(write_authority),
        &write_roots,
        &spec.id,
        phase,
        leaf_allowed_tools(spec)?,
    ))
}

fn validate_leaf_runtime_contract(spec: &LeafSpec) -> Result<(), ToolError> {
    if spec.mode == TaskMode::ReadOnly && spec.permissions.allow_write {
        return Err(ToolError::invalid_input(format!(
            "Workflow leaf '{}' is read_only but requests allow_write permissions",
            spec.id
        )));
    }
    if spec.mode == TaskMode::ReadWrite && spec.file_scope.is_empty() {
        return Err(ToolError::invalid_input(format!(
            "Workflow leaf '{}' is read_write but declares no file_scope for its bounded write claim",
            spec.id
        )));
    }
    for scope in &spec.file_scope {
        let normalized = codewhale_workflow::normalize_file_scope_root(scope);
        if normalized.is_empty() || normalized.contains('*') {
            return Err(ToolError::invalid_input(format!(
                "Workflow leaf '{}' has unsupported file_scope '{}'; use a concrete path or a trailing /* or /** directory scope",
                spec.id, scope
            )));
        }
    }
    // A Fleet role and its authority posture are independent. In particular,
    // acceptance workflows must be able to resolve the `implementer` role to
    // its saved profile while narrowing that child to the read-only tool set.
    // `leaf_allowed_tools` enforces the mode below; rejecting the combination
    // made verification-only role/gate dogfood impossible.
    if spec.mode == TaskMode::ReadWrite
        && matches!(
            spec.agent_type,
            AgentType::Explore | AgentType::Plan | AgentType::Review | AgentType::Verifier
        )
    {
        return Err(ToolError::invalid_input(format!(
            "Workflow leaf '{}' is read_write but uses read-only agent_type {}",
            spec.id,
            agent_type_name(spec.agent_type)
        )));
    }
    if spec.mode == TaskMode::ReadOnly
        && spec
            .permissions
            .allowed_tools
            .iter()
            .any(|tool| is_write_or_shell_tool(tool))
    {
        return Err(ToolError::invalid_input(format!(
            "Workflow leaf '{}' is read_only but requests write/shell allowed_tools",
            spec.id
        )));
    }
    if spec.permissions.deny_all_tools && !spec.permissions.allowed_tools.is_empty() {
        return Err(ToolError::invalid_input(format!(
            "Workflow leaf '{}' cannot combine deny_all_tools with allowed_tools",
            spec.id
        )));
    }
    Ok(())
}

fn leaf_description_expression(spec: &LeafSpec) -> String {
    let description = js_string(&leaf_description(spec));
    if spec.depends_on_results.is_empty() {
        return description;
    }
    let inputs = result_inputs_expression(&spec.depends_on_results);
    format!("{description} + \"\\n\\nInputs:\\n\" + {inputs}")
}

fn result_inputs_expression(inputs: &[String]) -> String {
    let entries = inputs
        .iter()
        .map(|input| format!("[{}, __results[{}]]", js_string(input), js_string(input)))
        .collect::<Vec<_>>()
        .join(", ");
    format!(
        "[{entries}].map(([id, value]) => \"--- \" + id + \" ---\\n\" + String(value ?? \"\")).join(\"\\n\\n\")"
    )
}

fn leaf_subagent_type(spec: &LeafSpec) -> Option<&'static str> {
    // A named Fleet profile owns the child's runtime type. Emitting the IR's
    // default `general` here makes role-only leaves look like an explicit type
    // override and can conflict with the resolved roster member (for example,
    // scout -> explore). Preserve non-General types because those represent an
    // authored override and the spawn path must still validate compatibility.
    if (spec.role.is_some() || spec.profile.is_some()) && spec.agent_type == AgentType::General {
        return None;
    }
    if spec.mode == TaskMode::ReadOnly && spec.agent_type == AgentType::General {
        return Some("review");
    }
    // A read_only leaf must not *name* a write-capable type. `type` is a claim
    // about what the child can do, and claiming it while the leaf narrows the
    // child to read-only tools is the contradiction #5123 asks the spawn path
    // to reject. The leaf's role/profile already carries the identity roster
    // resolution needs, so drop the redundant type and let the role speak —
    // this is the `implementer` role narrowed to verification-only work that
    // `validate_leaf_runtime_contract` deliberately allows.
    if spec.mode == TaskMode::ReadOnly
        && spec.agent_type == AgentType::Implementer
        && (spec.role.is_some() || spec.profile.is_some())
    {
        return None;
    }
    Some(agent_type_name(spec.agent_type))
}

fn leaf_allowed_tools(spec: &LeafSpec) -> Result<Option<Vec<String>>, ToolError> {
    if spec.permissions.deny_all_tools {
        return Ok(Some(Vec::new()));
    }
    if !spec.permissions.allowed_tools.is_empty() {
        return Ok(Some(spec.permissions.allowed_tools.clone()));
    }
    if spec.mode != TaskMode::ReadOnly {
        return Ok(None);
    }
    Ok(Some(
        read_only_allowed_tools(spec.agent_type)
            .iter()
            .map(|tool| (*tool).to_string())
            .collect(),
    ))
}

fn read_only_allowed_tools(agent_type: AgentType) -> &'static [&'static str] {
    match agent_type {
        AgentType::Verifier => &["File"],
        _ => &["File"],
    }
}

fn is_write_or_shell_tool(tool: &str) -> bool {
    // One list, owned by the workflow crate. This used to be a second copy
    // that drifted from `elevation.rs`'s — see `codewhale_workflow::is_write_tool`.
    codewhale_workflow::is_write_tool(tool) || codewhale_workflow::is_shell_tool(tool)
}

// Pre-existing builder that grew `allowed_tools`; each arg maps 1:1 onto one
// optional field of the generated JS options literal.
#[allow(clippy::too_many_arguments)]
fn task_options_expression(
    description_expr: String,
    subagent_type: Option<&str>,
    role: Option<&str>,
    profile: Option<&str>,
    worktree: bool,
    token_budget: Option<u64>,
    max_steps: Option<u32>,
    wall_time_secs: Option<u64>,
    write_authority: Option<&str>,
    write_roots: &[String],
    label: &str,
    phase: Option<&str>,
    allowed_tools: Option<Vec<String>>,
) -> String {
    let mut fields = vec![format!("description: {description_expr}")];
    if let Some(subagent_type) = subagent_type {
        fields.push(format!("type: {}", js_string(subagent_type)));
    }
    fields.push(format!("label: {}", js_string(label)));
    if let Some(phase) = phase {
        fields.push(format!("phase: {}", js_string(phase)));
    }
    if let Some(role) = role {
        fields.push(format!("role: {}", js_string(role)));
    }
    if let Some(profile) = profile {
        fields.push(format!("profile: {}", js_string(profile)));
    }
    if worktree {
        fields.push("worktree: true".to_string());
    }
    if let Some(token_budget) = token_budget {
        fields.push(format!("tokenBudget: {token_budget}"));
    }
    if let Some(max_steps) = max_steps {
        fields.push(format!("maxSteps: {max_steps}"));
    }
    if let Some(wall_time_secs) = wall_time_secs {
        fields.push(format!("wallTimeSecs: {wall_time_secs}"));
    }
    if let Some(write_authority) = write_authority {
        fields.push(format!("writeAuthority: {}", js_string(write_authority)));
    }
    if !write_roots.is_empty() {
        fields.push(format!(
            "writeRoots: {}",
            serde_json::to_string(write_roots).expect("serializing write roots cannot fail")
        ));
    }
    if let Some(allowed_tools) = allowed_tools {
        fields.push(format!(
            "allowedTools: {}",
            serde_json::to_string(&allowed_tools).expect("serializing tool names cannot fail")
        ));
    }
    format!("{{ {} }}", fields.join(", "))
}

fn js_string(value: &str) -> String {
    serde_json::to_string(value).expect("serializing JS string cannot fail")
}

fn agent_type_name(agent_type: AgentType) -> &'static str {
    match agent_type {
        AgentType::General => "general",
        AgentType::Explore => "explore",
        AgentType::Plan => "plan",
        AgentType::Review => "review",
        AgentType::Implementer => "implementer",
        AgentType::Verifier => "verifier",
    }
}

fn task_mode_name(mode: TaskMode) -> &'static str {
    match mode {
        TaskMode::ReadOnly => "read_only",
        TaskMode::ReadWrite => "read_write",
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExplicitGateVerdict {
    Approve,
    Reject,
}

/// Recognize only a standalone verdict token on the first non-empty line.
///
/// This deliberately does not interpret prose, Markdown bullets, or verdict
/// words later in an otherwise successful child response. Existing workflows
/// whose children return ordinary prose therefore remain pass-on-success,
/// while review-style children can fail closed with `BLOCK` or `FAIL`.
fn explicit_gate_verdict(output: Option<&str>) -> Option<ExplicitGateVerdict> {
    let first_meaningful = output?
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty())?;
    if first_meaningful.eq_ignore_ascii_case("APPROVE")
        || first_meaningful.eq_ignore_ascii_case("PASS")
    {
        Some(ExplicitGateVerdict::Approve)
    } else if first_meaningful.eq_ignore_ascii_case("BLOCK")
        || first_meaningful.eq_ignore_ascii_case("FAIL")
    {
        Some(ExplicitGateVerdict::Reject)
    } else {
        None
    }
}

fn has_gate_artifact_body(output: Option<&str>) -> bool {
    let Some(output) = output else {
        return false;
    };
    let mut meaningful_lines = output
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty());
    // A declared artifact needs both a body label and at least one concrete
    // entry after the verdict. This keeps `APPROVE\nok` from promoting a
    // placeholder while remaining format-agnostic for arbitrary artifact kinds.
    meaningful_lines.next();
    meaningful_lines.next().is_some() && meaningful_lines.next().is_some()
}

fn gate_outcome_for_completed_role(
    record: &RuntimeTaskRecord,
    require_explicit_verdict: bool,
    artifact_kind: Option<&str>,
) -> GateOutcome {
    match record.status {
        IrWorkflowRunStatus::Succeeded => match explicit_gate_verdict(record.output.as_deref()) {
            Some(ExplicitGateVerdict::Reject) => GateOutcome::Fail {
                reason: record
                    .output
                    .clone()
                    .unwrap_or_else(|| "child returned an explicit rejection verdict".into()),
            },
            Some(ExplicitGateVerdict::Approve)
                if require_explicit_verdict
                    && artifact_kind.is_some()
                    && !has_gate_artifact_body(record.output.as_deref()) =>
            {
                GateOutcome::Fail {
                    reason: format!(
                        "task {} approved without the required {} artifact body",
                        record.agent_id,
                        artifact_kind.unwrap_or("gate")
                    ),
                }
            }
            Some(ExplicitGateVerdict::Approve) => GateOutcome::Pass,
            None if require_explicit_verdict => GateOutcome::Fail {
                reason: format!(
                    "task {} completed without the required first-line gate verdict; expected exactly APPROVE, PASS, BLOCK, or FAIL",
                    record.agent_id
                ),
            },
            None => GateOutcome::Pass,
        },
        _ => GateOutcome::Fail {
            reason: record.output.clone().unwrap_or_else(|| {
                format!("task {} ended as {:?}", record.agent_id, record.status)
            }),
        },
    }
}

#[derive(Debug, Clone)]
struct RuntimeTaskRecord {
    agent_id: String,
    label: Option<String>,
    role: Option<String>,
    status: IrWorkflowRunStatus,
    output: Option<String>,
    schema_error: Option<String>,
    usage: Option<WorkflowTaskUsage>,
}

struct SubAgentWorkflowDriver {
    run_id: String,
    manager: SharedSubAgentManager,
    runtime: SubAgentRuntime,
    state: Arc<WorkflowWorkspaceState>,
    completion_tx: mpsc::UnboundedSender<SubAgentCompletion>,
    completion_state: Arc<Mutex<CompletionState>>,
    child_ids: Arc<Mutex<Vec<String>>>,
    /// Monotonic 0-based child admission counter for `workflow_child_index`.
    child_counter: AtomicU32,
    /// Latest `phase(...)` title observed on this run (used when a task omits
    /// an explicit `phase` option).
    current_phase: Mutex<Option<String>>,
    task_records: Arc<Mutex<HashMap<String, RuntimeTaskRecord>>>,
    total_budget: Option<u64>,
    last_budget_event: Arc<Mutex<Option<BudgetSnapshot>>>,
    /// Workflow-owned gates installed for this run (#4179).
    gate_specs: Arc<Vec<GateSpec>>,
    /// Lane-scoped gate and handoff state keyed by run id.
    gate_board: Arc<Mutex<LaneGateBoard>>,
    /// Caps concurrently live `task()` children for this run (product: 16).
    concurrent_gate: Arc<Semaphore>,
    /// Held permits for in-flight children; released on completion/cancel.
    spawn_permits: Mutex<HashMap<String, OwnedSemaphorePermit>>,
    /// Optional named Fleet roster for resolving Workflow task roles (#4177/#4178).
    fleet_name: Option<String>,
    /// The Fleet this Workflow is bound to, frozen at start. For an exact
    /// fleet this holds the immutable snapshot every task launch reads from,
    /// which is why editing `fleets/<name>.toml` mid-run cannot move a route.
    fleet: WorkflowFleetBinding,
}

impl SubAgentWorkflowDriver {
    #[allow(clippy::too_many_arguments)]
    fn new(
        run_id: String,
        manager: SharedSubAgentManager,
        runtime: SubAgentRuntime,
        state: Arc<WorkflowWorkspaceState>,
        total_budget: Option<u64>,
        fleet: WorkflowFleetBinding,
        gate_specs: Vec<GateSpec>,
    ) -> Arc<Self> {
        let fleet_name = fleet.name();
        let (completion_tx, completion_rx) = mpsc::unbounded_channel();
        let mut gate_board = LaneGateBoard::new(run_id.clone());
        gate_board.install_gates(&gate_specs);
        let driver = Arc::new(Self {
            run_id,
            manager,
            runtime,
            state,
            completion_tx,
            completion_state: Arc::new(Mutex::new(CompletionState::default())),
            child_ids: Arc::new(Mutex::new(Vec::new())),
            child_counter: AtomicU32::new(0),
            current_phase: Mutex::new(None),
            task_records: Arc::new(Mutex::new(HashMap::new())),
            total_budget,
            last_budget_event: Arc::new(Mutex::new(None)),
            gate_specs: Arc::new(gate_specs),
            gate_board: Arc::new(Mutex::new(gate_board)),
            concurrent_gate: Arc::new(Semaphore::new(WORKFLOW_MAX_CONCURRENT.max(1))),
            spawn_permits: Mutex::new(HashMap::new()),
            fleet_name,
            fleet,
        });
        spawn_completion_pump(driver.clone(), completion_rx);
        driver
    }

    fn force_cancel_all(&self) {
        let ids = self
            .child_ids
            .lock()
            .map(|ids| ids.clone())
            .unwrap_or_default();
        if let Ok(mut permits) = self.spawn_permits.lock() {
            permits.clear();
        }
        cancel_child_agents(self.manager.clone(), ids);
        if let Ok(mut state) = self.completion_state.lock() {
            for (_, waiter) in state.waiters.drain() {
                let _ = waiter.send(TaskCompletion::Cancelled);
            }
        }
    }

    fn finalize_running_tasks_cancelled(&self) {
        let ids = self
            .child_ids
            .lock()
            .map(|ids| ids.clone())
            .unwrap_or_default();
        for id in &ids {
            self.record_task_completion(id, &TaskCompletion::Cancelled, None);
        }
    }

    fn record_child(&self, agent_id: &str) {
        if let Ok(mut ids) = self.child_ids.lock()
            && !ids.iter().any(|id| id == agent_id)
        {
            ids.push(agent_id.to_string());
        }
        if let Ok(mut runs) = self.state.runs.lock()
            && let Some(record) = runs.get_mut(&self.run_id)
            && !record.child_ids.iter().any(|id| id == agent_id)
        {
            record.child_ids.push(agent_id.to_string());
        }
    }

    fn current_budget_snapshot(&self) -> BudgetSnapshot {
        let spent = self
            .manager
            .try_read()
            .ok()
            .map(|manager| manager.budget_spent_for_scope(&self.run_id))
            .unwrap_or(0);
        BudgetSnapshot {
            total: self.total_budget,
            spent,
        }
    }

    /// Return the first authoritative gate failure after the VM has no more
    /// children to admit. Intermediate blocks already reject the downstream
    /// spawn; this final check gives a terminal role's BLOCK verdict the same
    /// fail-closed semantics.
    fn terminal_gate_failure(&self) -> Option<String> {
        let board = match self.gate_board.lock() {
            Ok(board) => board,
            Err(_) => {
                return Some(
                    "workflow gate board was unavailable during terminal finalization".to_string(),
                );
            }
        };
        self.gate_specs.iter().find_map(|spec| {
            let state = board.gates.get(&spec.id)?;
            state.is_blocking().then(|| {
                format!(
                    "workflow gate `{}` ended {}: {}",
                    spec.id,
                    state.as_str(),
                    gate_state_reason(state)
                )
            })
        })
    }

    fn record_run_event(&self, event: WorkflowUiEvent) {
        let recorded = if let Ok(mut runs) = self.state.runs.lock()
            && let Some(record) = runs.get_mut(&self.run_id)
        {
            record.push_event(event.clone());
            true
        } else {
            false
        };
        if recorded {
            self.state.record_event(&self.run_id, &event);
        }
        // #4122: stream typed events live into the panel + history card.
        self.emit_ui_event(&event);
    }

    /// Publish a flattened WorkflowUiEvent on the engine event bus so the TUI
    /// can hydrate the panel while the tool is still running.
    fn emit_ui_event(&self, event: &WorkflowUiEvent) {
        let Some(tx) = self.runtime.event_tx.as_ref() else {
            return;
        };
        let Ok(mut value) = serde_json::to_value(event) else {
            return;
        };
        if let Some(obj) = value.as_object_mut() {
            obj.insert("run_id".to_string(), json!(self.run_id));
        }
        let _ = tx.try_send(Event::WorkflowUi {
            run_id: self.run_id.clone(),
            event: value,
        });
    }

    fn record_budget_snapshot(&self, snapshot: BudgetSnapshot) {
        let changed = if let Ok(mut last) = self.last_budget_event.lock() {
            if last.as_ref() == Some(&snapshot) {
                false
            } else {
                *last = Some(snapshot);
                true
            }
        } else {
            false
        };
        let event = WorkflowUiEvent::new(budget_event_kind(snapshot));
        if changed {
            self.record_run_event(event);
        } else {
            // The VM polls the budget before it can admit its first child.
            // Keep that live path warm even when no token value changed, but
            // do not journal an unbounded stream of identical snapshots.
            self.emit_ui_event(&event);
        }
    }

    fn prepare_request_for_gates(
        &self,
        request: &mut TaskRequest,
    ) -> Result<Vec<HandoffArtifact>, DriverError> {
        let Some(role) = request.role.as_deref().filter(|role| !role.is_empty()) else {
            return Ok(Vec::new());
        };
        if self.gate_specs.is_empty() {
            return Ok(Vec::new());
        }

        let (blocked, handoffs) = {
            let mut board = self
                .gate_board
                .lock()
                .map_err(|_| DriverError::Rejected("workflow gate board lock poisoned".into()))?;
            let blocked = board.role_is_blocked(&self.gate_specs, role).cloned();
            // Handoffs are consumed (removed from the board) as they are
            // delivered — but only when the role is actually admitted. A
            // blocked task must leave them in place for the retry after the
            // gate clears.
            let handoffs = if blocked.is_none() {
                board.consume_handoffs_for(role, 4)
            } else {
                Vec::new()
            };
            (blocked, handoffs)
        };

        if let Some(state) = blocked {
            return Err(DriverError::Rejected(format!(
                "workflow gate blocks role `{role}`: {}",
                gate_state_reason(&state)
            )));
        }

        if !handoffs.is_empty() {
            append_handoff_context(request, &handoffs);
        }
        Ok(handoffs)
    }

    fn update_gate_status(&self, status: Vec<GateStatusLine>) {
        let snapshot = if let Ok(mut runs) = self.state.runs.lock()
            && let Some(record) = runs.get_mut(&self.run_id)
        {
            record.gate_status = status;
            Some(record.clone())
        } else {
            None
        };
        if let Some(record) = snapshot {
            self.state.record_snapshot(&record);
        }
    }

    fn evaluate_gates_for_completed_role(&self, record: &RuntimeTaskRecord) {
        let Some(role) = record.role.as_deref().filter(|role| !role.is_empty()) else {
            return;
        };
        if self.gate_specs.is_empty() {
            return;
        }
        let specs = self
            .gate_specs
            .iter()
            .filter(|spec| spec.on == GateOn::RoleComplete && spec.role.eq_ignore_ascii_case(role))
            .cloned()
            .collect::<Vec<_>>();
        if specs.is_empty() {
            return;
        }

        let mut events = Vec::new();
        let mut next_status = Vec::new();
        if let Ok(mut board) = self.gate_board.lock() {
            for spec in specs {
                let outcome = gate_outcome_for_completed_role(
                    record,
                    spec.require_explicit_verdict,
                    spec.artifact_kind.as_deref(),
                );
                let mut state = match board.evaluate(&spec, outcome.clone()) {
                    Ok(state) => state,
                    Err(err) => {
                        let state = GateState::Blocked {
                            reason: err.to_string(),
                        };
                        // Evaluation errors must become authoritative board state.
                        // Otherwise the emitted receipt can say `blocked` while the
                        // admission check still sees the gate as pending.
                        board.gates.insert(spec.id.clone(), state.clone());
                        state
                    }
                };
                let mut promotion = None;
                if matches!(state, GateState::Passed)
                    && let (Some(kind), Some(to_role)) =
                        (spec.artifact_kind.as_deref(), spec.blocks_role.as_deref())
                {
                    let artifact = HandoffArtifact {
                        // Gate ids are authored input and are not guaranteed unique.
                        // Use an opaque id so every promotion has a stable, distinct
                        // identity even when a malformed workflow repeats a gate id.
                        id: format!("handoff_{}", Uuid::new_v4()),
                        lane_id: self.run_id.clone(),
                        from_role: spec.role.clone(),
                        to_role: to_role.to_string(),
                        kind: kind.to_string(),
                        payload: record.output.clone().unwrap_or_default(),
                        created_at: now_ms().to_string(),
                    };
                    match board.record_handoff(artifact.clone()) {
                        Ok(()) => {
                            promotion =
                                Some(WorkflowUiEvent::new(WorkflowUiEventKind::HandoffPromoted {
                                    artifact_id: artifact.id,
                                    gate_id: spec.id.clone(),
                                    kind: artifact.kind,
                                    from_role: artifact.from_role,
                                    to_role: artifact.to_role,
                                    producer_task_id: record.agent_id.clone(),
                                }));
                        }
                        Err(err) => {
                            state = GateState::Blocked {
                                reason: format!(
                                    "gate passed but its handoff could not be recorded: {err}"
                                ),
                            };
                            board.gates.insert(spec.id.clone(), state.clone());
                        }
                    }
                }
                events.push(WorkflowUiEvent::new(WorkflowUiEventKind::GateUpdated {
                    gate_id: spec.id.clone(),
                    role: spec.role.clone(),
                    gate: gate_kind_label(spec.gate).to_string(),
                    state: state.as_str().to_string(),
                    blocked_role: spec.blocks_role.clone(),
                    blocked_reason: state.blocked_reason().map(str::to_string),
                }));
                if let Some(event) = promotion {
                    events.push(event);
                }
            }
            next_status = board.status_summary();
        }
        if !events.is_empty() || !next_status.is_empty() {
            self.update_gate_status(next_status);
        }
        for event in events {
            self.record_run_event(event);
        }
    }

    fn record_task_started(
        &self,
        agent_id: &str,
        request: &TaskRequest,
        metadata: &WorkflowTaskSpawnMetadata,
        result: &crate::tools::subagent::SubAgentResult,
        fleet_receipt: Option<codewhale_workflow::FleetTaskReceipt>,
    ) {
        // Prefer typed spawn metadata over request fields so panel/history never
        // need to re-derive labels from the child prompt (#4119).
        let label = metadata
            .workflow_task_label
            .clone()
            .or_else(|| request.label.clone());
        self.record_run_event(WorkflowUiEvent::new(WorkflowUiEventKind::TaskStarted(
            Box::new(WorkflowTaskStartedEvent {
                task_id: agent_id.to_string(),
                label,
                role: request.role.clone(),
                profile: request.profile.clone(),
                model: request.model.clone(),
                strength: request.model_strength.clone(),
                thinking: request.thinking.clone(),
                // #4039: both sides of the reasoning receipt come from the
                // spawn metadata the runtime minted, never from the request or
                // from current session config.
                requested_reasoning: metadata
                    .requested_reasoning
                    .clone()
                    .or_else(|| request.thinking.clone()),
                effective_reasoning: metadata.effective_reasoning.clone(),
                // Prefer spawn metadata (fleet-resolved); fall back to request.
                //
                // An exact-Fleet receipt overrides both, because the spawn
                // metadata's role is the roster profile's **posture** role —
                // the tool surface the clamped ceiling permits — and displaying
                // that where the member's role belongs silently renames the
                // operator's `auditor` to `scout`. The posture is not lost: it
                // rides the receipt as its own field.
                resolved_role: displayed_resolved_role(
                    fleet_receipt.as_ref(),
                    metadata.resolved_role.as_deref(),
                    request.role.as_deref(),
                ),
                resolved_profile: metadata
                    .resolved_profile
                    .clone()
                    .or_else(|| request.profile.clone()),
                resolved_provider: metadata.resolved_provider.clone(),
                resolved_model: metadata.resolved_model.clone(),
                route_source: metadata.route_source.clone(),
                child_route: Some(metadata.child_route.clone()),
                worktree: request.worktree,
                workspace: result.workspace.clone(),
                git_branch: result.git_branch.clone(),
                parent_task_id: metadata.parent_task_id.clone(),
                depth: metadata.depth,
                workflow_run_id: metadata.workflow_run_id.clone(),
                workflow_phase_id: metadata.workflow_phase_id.clone(),
                workflow_task_label: metadata.workflow_task_label.clone(),
                workflow_child_index: metadata.workflow_child_index,
                fleet_receipt: fleet_receipt.clone(),
            }),
        )));
        // Also surface the decision as a run log line, so the receipt is
        // *visible* in the panel and transcript rather than only structured on
        // an event a UI has to know to unpack.
        if let Some(receipt) = fleet_receipt {
            self.record_run_event(WorkflowUiEvent::new(WorkflowUiEventKind::Log {
                message: format!("fleet route {}", receipt.line()),
            }));
        }
    }

    /// Preserve a routing receipt whose task never became a child.
    ///
    /// A receipt normally rides the `task_started` event, which a failed spawn
    /// never emits. Recording it here keeps the run's history complete: the
    /// decision happened, the tokens were spent, and — if the Router ran on
    /// another provider — a bounded summary already left the host. Silence
    /// would make all three unrecoverable.
    fn record_orphaned_fleet_receipt(
        &self,
        receipt: &codewhale_workflow::FleetTaskReceipt,
        error: &str,
    ) {
        self.record_run_event(WorkflowUiEvent::new(WorkflowUiEventKind::Log {
            message: orphaned_fleet_receipt_line(receipt, error),
        }));
    }

    fn record_task_request(&self, agent_id: &str, request: &TaskRequest) {
        if let Ok(mut records) = self.task_records.lock() {
            records.insert(
                agent_id.to_string(),
                RuntimeTaskRecord {
                    agent_id: agent_id.to_string(),
                    label: request.label.clone(),
                    role: request.role.clone(),
                    status: IrWorkflowRunStatus::Running,
                    output: None,
                    schema_error: None,
                    usage: None,
                },
            );
        }
        let pending_completion = self
            .completion_state
            .lock()
            .ok()
            .and_then(|state| state.pending.get(agent_id).cloned());
        if let Some(completion) = pending_completion {
            self.record_task_completion(agent_id, &completion.completion, completion.usage);
        }
    }

    fn record_task_completion(
        &self,
        agent_id: &str,
        completion: &TaskCompletion,
        usage: Option<WorkflowTaskUsage>,
    ) {
        let mut terminal_event = None;
        let mut completed_record = None;
        if let Ok(mut records) = self.task_records.lock()
            && let Some(record) = records.get_mut(agent_id)
        {
            let was_running = record.status == IrWorkflowRunStatus::Running;
            let (status, output) = task_completion_status(completion);
            record.status = status;
            record.output = output;
            if usage.is_some() {
                record.usage = usage;
            }
            if was_running {
                terminal_event = Some(WorkflowUiEvent::new(WorkflowUiEventKind::TaskCompleted {
                    task_id: agent_id.to_string(),
                    status,
                    usage: record.usage.clone(),
                }));
                completed_record = Some(record.clone());
            }
        }
        if let Some(event) = terminal_event {
            self.record_run_event(event);
        }
        if let Some(record) = completed_record.as_ref() {
            // A role-complete gate is caused by this terminal transition, so its
            // durable task receipt must precede gate evaluation and promotion.
            self.evaluate_gates_for_completed_role(record);
        }
    }

    /// A rejected dispatch never produces a child agent, and inside
    /// `parallel()` the JS throw collapses to a `null` slot; this ledger keeps
    /// the rejection visible on the run record and result payload (#5035).
    fn record_dispatch_failure(
        &self,
        label: Option<String>,
        phase: Option<String>,
        message: String,
    ) {
        let failure = WorkflowDispatchFailure {
            at_ms: now_ms(),
            label,
            phase,
            message,
        };
        let slot = failure
            .label
            .as_deref()
            .or(failure.phase.as_deref())
            .unwrap_or("task");
        let progress_line = format!("dispatch failed for {slot}: {}", failure.message);
        let ui_event = WorkflowUiEvent::new(WorkflowUiEventKind::TaskDispatchFailed {
            label: failure.label.clone(),
            phase: failure.phase.clone(),
            message: failure.message.clone(),
        });
        if let Ok(mut runs) = self.state.runs.lock()
            && let Some(record) = runs.get_mut(&self.run_id)
        {
            record.progress.push(progress_line.clone());
            record.push_event(ui_event.clone());
            record.dispatch_failures.push(failure);
        }
        self.state.record_progress(&self.run_id, &progress_line);
        self.state.record_event(&self.run_id, &ui_event);
        self.emit_ui_event(&ui_event);
    }

    fn record_schema_validation_failure(&self, agent_id: &str, message: String) {
        if let Ok(mut records) = self.task_records.lock()
            && let Some(record) = records.get_mut(agent_id)
        {
            record.status = IrWorkflowRunStatus::Failed;
            record.schema_error = Some(message.clone());
            record.output = Some(message);
        }
    }

    fn task_records_snapshot(&self) -> Vec<RuntimeTaskRecord> {
        self.task_records
            .lock()
            .map(|records| records.values().cloned().collect())
            .unwrap_or_default()
    }

    fn add_waiter_or_complete(&self, agent_id: String, waiter: oneshot::Sender<TaskCompletion>) {
        let mut state = self
            .completion_state
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        if let Some(completion) = state.pending.remove(&agent_id) {
            let _ = waiter.send(completion.completion);
        } else {
            state.waiters.insert(agent_id, waiter);
        }
    }

    fn deliver_completion(
        &self,
        agent_id: String,
        completion: TaskCompletion,
        usage: Option<WorkflowTaskUsage>,
    ) {
        self.record_task_completion(&agent_id, &completion, usage.clone());
        if let Ok(mut permits) = self.spawn_permits.lock() {
            permits.remove(&agent_id);
        }
        let mut state = self
            .completion_state
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        if let Some(waiter) = state.waiters.remove(&agent_id) {
            let _ = waiter.send(completion);
        } else {
            state
                .pending
                .insert(agent_id, PendingCompletion { completion, usage });
        }
    }
}

#[derive(Clone)]
struct PendingCompletion {
    completion: TaskCompletion,
    usage: Option<WorkflowTaskUsage>,
}

#[derive(Default)]
struct CompletionState {
    waiters: HashMap<String, oneshot::Sender<TaskCompletion>>,
    pending: HashMap<String, PendingCompletion>,
}

impl SubAgentWorkflowDriver {
    /// The admission half of [`WorkflowDriver::spawn_task`]; every `Err` it
    /// returns is recorded as a dispatch failure by the trait wrapper.
    async fn spawn_task_admitted(
        &self,
        mut request: TaskRequest,
    ) -> Result<SpawnedTask, DriverError> {
        // Exact fleets resolve from the frozen snapshot; legacy role maps keep
        // their previous path unchanged.
        //
        // The exact path is deliberately split in two. **Binding** resolves the
        // member, its frozen route, and its clamped authority, and contacts
        // nobody. **Routing** — the half that may call the fleet's reasoning
        // router, spend the operator's tokens, and disclose a bounded summary
        // to another provider — happens only after this task has passed its
        // gates and holds a concurrency slot. A task that is rejected or
        // capacity-blocked therefore costs nothing and reveals nothing.
        let exact_binding = if let Some(operation) = self.fleet.exact() {
            // The depth budget is the other failure the spawn boundary can be
            // predicted to raise, and it does not depend on the member. Check
            // it here so an over-deep task is refused for free rather than
            // after a routing request has already been paid for.
            if self.runtime.would_exceed_depth() {
                return Err(DriverError::Rejected(format!(
                    "fleet `{}`: sub-agent depth limit reached (depth {}, max {}); this task \
                     cannot spawn a child, so it is refused before the reasoning router is asked \
                     anything.",
                    operation.snapshot().fleet().qualified(),
                    self.runtime.spawn_depth,
                    self.runtime.max_spawn_depth,
                )));
            }
            Some(bind_exact_fleet_task_request(
                operation,
                crate::fleet::exact::session_permission_ceiling(&self.runtime),
                &mut request,
            )?)
        } else {
            apply_named_fleet_to_task_request(self.fleet.legacy_roles(), &mut request).map_err(
                |err| {
                    if let Some(fleet) = self.fleet_name.as_deref() {
                        DriverError::Rejected(format!(
                            "fleet `{fleet}` role resolution failed: {err}"
                        ))
                    } else {
                        err
                    }
                },
            )?;
            None
        };
        let consumed_handoffs = self.prepare_request_for_gates(&mut request)?;
        // Wait for a concurrent slot (max 16 live children per run).
        let permit = self
            .concurrent_gate
            .clone()
            .acquire_owned()
            .await
            .map_err(|_| DriverError::Rejected("workflow concurrent admission closed".into()))?;

        // Admitted. Only now may the reasoning router be consulted.
        let fleet_receipt = match (self.fleet.exact(), exact_binding) {
            (Some(operation), Some(binding)) => {
                match route_admitted_exact_task(operation, &binding, &mut request).await {
                    Ok(receipt) => Some(receipt),
                    Err(err) => {
                        drop(permit);
                        return Err(err);
                    }
                }
            }
            _ => None,
        };

        let runtime = self
            .runtime
            .clone()
            .with_parent_completion_tx(self.completion_tx.clone());
        let request_record = request.clone();
        let workflow_child_index = self.child_counter.fetch_add(1, Ordering::SeqCst);
        let workflow_phase_id = request
            .phase
            .as_ref()
            .map(|phase| phase.trim())
            .filter(|phase| !phase.is_empty())
            .map(str::to_string)
            .or_else(|| {
                self.current_phase
                    .lock()
                    .ok()
                    .and_then(|phase| phase.clone())
            });
        let workflow_task_label = request
            .label
            .as_ref()
            .map(|label| label.trim())
            .filter(|label| !label.is_empty())
            .map(str::to_string);
        let identity = WorkflowTaskSpawnIdentity {
            workflow_run_id: self.run_id.clone(),
            workflow_phase_id,
            workflow_task_label,
            workflow_child_index,
            // The Fleet decision travels to the spawn boundary as a value that
            // boundary re-checks, rather than as trust in the caller.
            fleet_authority_fingerprint: fleet_receipt
                .as_ref()
                .and_then(|receipt| receipt.authority_fingerprint.clone()),
        };
        let result =
            match spawn_workflow_task(request, self.manager.clone(), runtime, identity).await {
                Ok(result) => result,
                Err(err) => {
                    drop(permit);
                    // The Router decision was already made and already paid
                    // for. Dropping the receipt with the failed spawn would
                    // erase the only record that a routing request was spent —
                    // and, when a bounded summary crossed to another provider,
                    // the only disclosure that it did. It survives the failure.
                    if let Some(receipt) = fleet_receipt {
                        self.record_orphaned_fleet_receipt(&receipt, &err.to_string());
                    }
                    return Err(DriverError::Rejected(err.to_string()));
                }
            };
        let task_id = result.result.agent_id.clone();
        if let Ok(mut permits) = self.spawn_permits.lock() {
            permits.insert(task_id.clone(), permit);
        }
        self.record_child(&task_id);
        self.record_task_started(
            &task_id,
            &request_record,
            &result.metadata,
            &result.result,
            fleet_receipt,
        );
        for artifact in consumed_handoffs {
            self.record_run_event(WorkflowUiEvent::new(WorkflowUiEventKind::HandoffConsumed {
                artifact_id: artifact.id,
                kind: artifact.kind,
                from_role: artifact.from_role,
                to_role: artifact.to_role,
                consumer_task_id: task_id.clone(),
            }));
        }
        self.record_task_request(&task_id, &request_record);
        if let Some(limit) = self.total_budget {
            let mut manager = self.manager.write().await;
            manager.attach_shared_budget_scope(&task_id, &self.run_id, limit);
        }
        let (tx, rx) = oneshot::channel();
        self.add_waiter_or_complete(task_id.clone(), tx);
        Ok(SpawnedTask {
            task_id,
            completion: rx,
        })
    }
}

#[async_trait]
impl WorkflowDriver for SubAgentWorkflowDriver {
    async fn spawn_task(&self, request: TaskRequest) -> Result<SpawnedTask, DriverError> {
        let label = request
            .label
            .as_deref()
            .map(str::trim)
            .filter(|label| !label.is_empty())
            .map(str::to_string);
        let phase = request
            .phase
            .as_deref()
            .map(str::trim)
            .filter(|phase| !phase.is_empty())
            .map(str::to_string)
            .or_else(|| {
                self.current_phase
                    .lock()
                    .ok()
                    .and_then(|phase| phase.clone())
            });
        let result = self.spawn_task_admitted(request).await;
        if let Err(err) = &result {
            self.record_dispatch_failure(label, phase, err.to_string());
        }
        result
    }

    fn cancel_all(&self) {
        self.force_cancel_all();
    }

    fn budget(&self) -> BudgetSnapshot {
        let snapshot = self.current_budget_snapshot();
        self.record_budget_snapshot(snapshot);
        snapshot
    }

    fn progress(&self, event: ProgressEvent) {
        let mut schema_error = None;
        let (message, ui_event) = match event {
            // Pre-spawn rejections share the dispatch-failure ledger so the
            // completion classifier sees every requested slot, whether the VM
            // or the driver refused it.
            ProgressEvent::TaskRejected {
                label,
                phase,
                message,
            } => {
                self.record_dispatch_failure(label, phase, message);
                return;
            }
            ProgressEvent::Log { message } => (
                format!("log: {message}"),
                WorkflowUiEvent::new(WorkflowUiEventKind::Log { message }),
            ),
            ProgressEvent::Phase { title } => {
                if let Ok(mut current) = self.current_phase.lock() {
                    *current = Some(title.clone());
                }
                (
                    format!("phase: {title}"),
                    WorkflowUiEvent::new(WorkflowUiEventKind::PhaseStarted { title }),
                )
            }
            ProgressEvent::TaskSchemaValidationFailed { task_id, message } => {
                self.record_schema_validation_failure(&task_id, message.clone());
                schema_error = Some(WorkflowSchemaError {
                    task_id: task_id.clone(),
                    message: message.clone(),
                });
                (
                    format!("schema validation failed for {task_id}: {message}"),
                    WorkflowUiEvent::new(WorkflowUiEventKind::TaskSchemaValidationFailed {
                        task_id,
                        message,
                    }),
                )
            }
        };
        if let Ok(mut runs) = self.state.runs.lock()
            && let Some(record) = runs.get_mut(&self.run_id)
        {
            record.progress.push(message.clone());
            record.push_event(ui_event.clone());
            if let Some(schema_error) = schema_error {
                record.schema_errors.push(schema_error);
            }
        }
        self.state.record_progress(&self.run_id, &message);
        self.state.record_event(&self.run_id, &ui_event);
        // #4122: phase/schema/log progress streams into the live panel path.
        self.emit_ui_event(&ui_event);
    }
}

fn budget_event_kind(snapshot: BudgetSnapshot) -> WorkflowUiEventKind {
    WorkflowUiEventKind::BudgetUpdated {
        total: snapshot.total,
        spent: snapshot.spent,
        remaining: snapshot.remaining(),
    }
}

fn gate_kind_label(kind: GateKind) -> &'static str {
    match kind {
        GateKind::Verify => "verify",
        GateKind::Review => "review",
        GateKind::Approve => "approve",
    }
}

fn gate_state_reason(state: &GateState) -> String {
    state
        .blocked_reason()
        .map(str::to_string)
        .unwrap_or_else(|| state.as_str().to_string())
}

fn append_handoff_context(request: &mut TaskRequest, handoffs: &[HandoffArtifact]) {
    request
        .description
        .push_str("\n\nWorkflow handoff artifacts available for this role:\n");
    for artifact in handoffs {
        request.description.push_str(&format!(
            "- id: {} kind: {} from: {} to: {}\n  payload: {}\n",
            artifact.id,
            artifact.kind,
            artifact.from_role,
            artifact.to_role,
            compact_handoff_payload(&artifact.payload, WORKFLOW_HANDOFF_MAX_CHARS)
        ));
    }
}

fn compact_handoff_payload(payload: &str, max_chars: usize) -> String {
    let trimmed = payload.trim();
    if trimmed.chars().count() <= max_chars {
        return trimmed.to_string();
    }
    let mut out = trimmed.chars().take(max_chars).collect::<String>();
    out.push_str("...");
    out
}

fn task_completion_status(completion: &TaskCompletion) -> (IrWorkflowRunStatus, Option<String>) {
    match completion {
        TaskCompletion::Completed { text } => (IrWorkflowRunStatus::Succeeded, Some(text.clone())),
        TaskCompletion::Failed { message } => (IrWorkflowRunStatus::Failed, Some(message.clone())),
        TaskCompletion::Cancelled => (IrWorkflowRunStatus::Cancelled, None),
        TaskCompletion::BudgetExhausted { message } => {
            (IrWorkflowRunStatus::BudgetExceeded, Some(message.clone()))
        }
    }
}

/// Sum per-task telemetry into run-wide totals for `run_completed` (#2974).
/// Returns `None` when no task contributed telemetry (e.g. a plan that ran
/// zero children) so the event stays byte-identical to its pre-#2974 shape.
fn run_usage_totals(records: &[RuntimeTaskRecord]) -> Option<WorkflowRunUsage> {
    let mut usages = records.iter().filter_map(|record| record.usage.as_ref());
    let mut totals = WorkflowRunUsage::from_task(usages.next()?);
    for usage in usages {
        totals.add_task(usage);
    }
    Some(totals)
}

/// Convert captured task telemetry into the shared `WorkflowUsage` aggregate
/// used by the workflow execution record (#2974).
fn workflow_usage_from_task(usage: &WorkflowTaskUsage) -> WorkflowUsage {
    WorkflowUsage {
        input_tokens: usage.input_tokens,
        output_tokens: usage.output_tokens,
        cost_microusd: usage.cost_microusd,
    }
}

fn execution_from_declarative_spec(
    spec: &WorkflowSpec,
    records: Vec<RuntimeTaskRecord>,
    terminal_status: WorkflowRunStatus,
) -> IrWorkflowExecution {
    let by_label = records
        .into_iter()
        .filter_map(|record| record.label.clone().map(|label| (label, record)))
        .collect::<HashMap<_, _>>();
    let mut execution = IrWorkflowExecution::default();
    for node in &spec.nodes {
        push_execution_node(node, &by_label, &mut execution);
    }
    let mut leaf_usage = execution.leaf_results.iter().map(|leaf| leaf.usage);
    execution.usage = leaf_usage
        .next()
        .map_or_else(WorkflowUsage::default, |first| {
            leaf_usage.fold(first, |mut totals, usage| {
                totals.input_tokens = sum_optional_usage(totals.input_tokens, usage.input_tokens);
                totals.output_tokens =
                    sum_optional_usage(totals.output_tokens, usage.output_tokens);
                totals.cost_microusd =
                    sum_optional_usage(totals.cost_microusd, usage.cost_microusd);
                totals
            })
        });
    match terminal_status {
        WorkflowRunStatus::Completed | WorkflowRunStatus::Degraded => {}
        WorkflowRunStatus::Failed => mark_ir_status(&mut execution, IrWorkflowRunStatus::Failed),
        WorkflowRunStatus::Cancelled => {
            mark_ir_status(&mut execution, IrWorkflowRunStatus::Cancelled);
        }
        WorkflowRunStatus::Running => {
            execution.status = IrWorkflowRunStatus::Running;
        }
    }
    execution
}

fn push_execution_node(
    node: &WorkflowNode,
    records: &HashMap<String, RuntimeTaskRecord>,
    execution: &mut IrWorkflowExecution,
) {
    match node {
        WorkflowNode::Leaf(spec) => push_leaf_execution(spec, records, execution),
        WorkflowNode::BranchSet(spec) => push_branch_execution(spec, records, execution),
        WorkflowNode::Sequence(spec) => push_sequence_execution(spec, records, execution),
        WorkflowNode::Reduce(spec) => push_control_execution(
            spec.id.as_str(),
            ControlNodeKind::Reduce,
            records.get(&spec.id),
            spec.inputs.clone(),
            Some(spec.prompt.clone()),
            execution,
        ),
        WorkflowNode::TeacherReview(spec) => push_control_execution(
            spec.id.as_str(),
            ControlNodeKind::TeacherReview,
            records.get(&spec.id),
            spec.candidates.clone(),
            Some("teacher review not lowered by the production adapter".to_string()),
            execution,
        ),
        WorkflowNode::LoopUntil(spec) => push_control_execution(
            spec.id.as_str(),
            ControlNodeKind::LoopUntil,
            records.get(&spec.id),
            spec.children.iter().map(declarative_node_id).collect(),
            Some("loop_until not lowered by the production adapter".to_string()),
            execution,
        ),
        WorkflowNode::Cond(spec) => push_control_execution(
            spec.id.as_str(),
            ControlNodeKind::Cond,
            records.get(&spec.id),
            spec.then_nodes
                .iter()
                .chain(spec.else_nodes.iter())
                .map(declarative_node_id)
                .collect(),
            Some("cond not lowered by the production adapter".to_string()),
            execution,
        ),
        WorkflowNode::Expand(spec) => push_control_execution(
            spec.id.as_str(),
            ControlNodeKind::Expand,
            records.get(&spec.id),
            Vec::new(),
            Some(format!("expand not lowered from {}", spec.source)),
            execution,
        ),
    }
}

fn push_leaf_execution(
    spec: &LeafSpec,
    records: &HashMap<String, RuntimeTaskRecord>,
    execution: &mut IrWorkflowExecution,
) {
    let record = records.get(&spec.id);
    let status = record
        .map(|record| record.status)
        .unwrap_or(IrWorkflowRunStatus::Pending);
    mark_ir_status(execution, status);
    execution.leaf_results.push(LeafResult {
        leaf_id: spec.id.clone(),
        task_id: record
            .map(|record| record.agent_id.clone())
            .unwrap_or_else(|| spec.id.clone()),
        role: spec.role.clone(),
        profile: spec.profile.clone(),
        status,
        usage: record
            .and_then(|record| record.usage.as_ref())
            .map(workflow_usage_from_task)
            .unwrap_or_default(),
        memo_usage: WorkflowMemoUsage::default(),
        output: record.and_then(|record| record.output.clone()),
        artifacts: Vec::new(),
        schema_error: record.and_then(|record| record.schema_error.clone()),
    });
}

fn push_branch_execution(
    spec: &BranchSpec,
    records: &HashMap<String, RuntimeTaskRecord>,
    execution: &mut IrWorkflowExecution,
) {
    let before = execution.leaf_results.len();
    for child in &spec.children {
        push_execution_node(child, records, execution);
    }
    let status = aggregate_ir_status(
        execution.leaf_results[before..]
            .iter()
            .map(|result| result.status),
    );
    mark_ir_status(execution, status);
    execution.branch_results.push(BranchResult {
        branch_id: spec.id.clone(),
        task_id: spec.id.clone(),
        status,
        usage: WorkflowUsage::default(),
        memo_usage: WorkflowMemoUsage::default(),
        artifacts: Vec::new(),
        notes: Some("production driver branch receipt from child task outcomes".to_string()),
    });
    execution.control_node_results.push(ControlNodeResult {
        node_id: spec.id.clone(),
        kind: ControlNodeKind::BranchSet,
        status,
        selected_children: spec.children.iter().map(declarative_node_id).collect(),
        summary: Some("branch set lowered into production child tasks".to_string()),
    });
}

fn push_sequence_execution(
    spec: &SequenceSpec,
    records: &HashMap<String, RuntimeTaskRecord>,
    execution: &mut IrWorkflowExecution,
) {
    let before_leaf = execution.leaf_results.len();
    let before_control = execution.control_node_results.len();
    for child in &spec.children {
        push_execution_node(child, records, execution);
    }
    let status = aggregate_ir_status(
        execution.leaf_results[before_leaf..]
            .iter()
            .map(|result| result.status)
            .chain(
                execution.control_node_results[before_control..]
                    .iter()
                    .map(|result| result.status),
            ),
    );
    mark_ir_status(execution, status);
    execution.control_node_results.push(ControlNodeResult {
        node_id: spec.id.clone(),
        kind: ControlNodeKind::Sequence,
        status,
        selected_children: spec.children.iter().map(declarative_node_id).collect(),
        summary: Some("sequence lowered in declaration order".to_string()),
    });
}

fn push_control_execution(
    node_id: &str,
    kind: ControlNodeKind,
    record: Option<&RuntimeTaskRecord>,
    selected_children: Vec<String>,
    fallback_summary: Option<String>,
    execution: &mut IrWorkflowExecution,
) {
    let status = record
        .map(|record| record.status)
        .unwrap_or(IrWorkflowRunStatus::Pending);
    mark_ir_status(execution, status);
    execution.control_node_results.push(ControlNodeResult {
        node_id: node_id.to_string(),
        kind,
        status,
        selected_children,
        summary: record
            .and_then(|record| record.output.clone())
            .or(fallback_summary),
    });
}

fn aggregate_ir_status(
    statuses: impl IntoIterator<Item = IrWorkflowRunStatus>,
) -> IrWorkflowRunStatus {
    let mut saw_pending = false;
    let mut saw_running = false;
    for status in statuses {
        match status {
            IrWorkflowRunStatus::BudgetExceeded => return IrWorkflowRunStatus::BudgetExceeded,
            IrWorkflowRunStatus::Cancelled => return IrWorkflowRunStatus::Cancelled,
            IrWorkflowRunStatus::Failed | IrWorkflowRunStatus::ReplayDiverged => {
                return IrWorkflowRunStatus::Failed;
            }
            IrWorkflowRunStatus::Running => saw_running = true,
            IrWorkflowRunStatus::Pending => saw_pending = true,
            IrWorkflowRunStatus::Succeeded => {}
        }
    }
    if saw_running {
        IrWorkflowRunStatus::Running
    } else if saw_pending {
        IrWorkflowRunStatus::Pending
    } else {
        IrWorkflowRunStatus::Succeeded
    }
}

fn mark_ir_status(execution: &mut IrWorkflowExecution, status: IrWorkflowRunStatus) {
    match status {
        IrWorkflowRunStatus::Failed | IrWorkflowRunStatus::ReplayDiverged => {
            execution.mark_failed()
        }
        IrWorkflowRunStatus::Cancelled => execution.mark_cancelled(),
        IrWorkflowRunStatus::BudgetExceeded => execution.mark_budget_exceeded(),
        IrWorkflowRunStatus::Running => {
            if execution.status == IrWorkflowRunStatus::Succeeded {
                execution.status = IrWorkflowRunStatus::Running;
            }
        }
        IrWorkflowRunStatus::Pending => {
            if execution.status == IrWorkflowRunStatus::Succeeded {
                execution.status = IrWorkflowRunStatus::Pending;
            }
        }
        IrWorkflowRunStatus::Succeeded => {}
    }
}

fn declarative_node_id(node: &WorkflowNode) -> String {
    match node {
        WorkflowNode::BranchSet(spec) => spec.id.clone(),
        WorkflowNode::Leaf(spec) => spec.id.clone(),
        WorkflowNode::Sequence(spec) => spec.id.clone(),
        WorkflowNode::Reduce(spec) => spec.id.clone(),
        WorkflowNode::TeacherReview(spec) => spec.id.clone(),
        WorkflowNode::LoopUntil(spec) => spec.id.clone(),
        WorkflowNode::Cond(spec) => spec.id.clone(),
        WorkflowNode::Expand(spec) => spec.id.clone(),
    }
}

fn spawn_completion_pump(
    driver: Arc<SubAgentWorkflowDriver>,
    mut rx: mpsc::UnboundedReceiver<SubAgentCompletion>,
) {
    spawn_supervised(
        "workflow-completion-pump",
        std::panic::Location::caller(),
        async move {
            while let Some(completion) = rx.recv().await {
                let agent_id = completion.agent_id.clone();
                let (task_completion, usage) =
                    completion_from_manager(driver.manager.clone(), &agent_id, completion.payload)
                        .await;
                driver.deliver_completion(agent_id, task_completion, usage);
            }
        },
    );
}

async fn completion_from_manager(
    manager: SharedSubAgentManager,
    agent_id: &str,
    fallback_payload: String,
) -> (TaskCompletion, Option<WorkflowTaskUsage>) {
    for _ in 0..50 {
        let snapshot_and_usage = {
            let manager = manager.read().await;
            let snapshot = manager.get_result(agent_id).ok();
            let usage = snapshot
                .as_ref()
                .filter(|snapshot| snapshot.status != SubAgentStatus::Running)
                .map(|snapshot| task_usage_from_manager(&manager, agent_id, snapshot));
            (snapshot, usage)
        };
        if let (Some(snapshot), usage) = snapshot_and_usage
            && snapshot.status != SubAgentStatus::Running
        {
            let completion = match snapshot.status {
                SubAgentStatus::Completed => TaskCompletion::Completed {
                    text: snapshot.result.clone().unwrap_or(fallback_payload),
                },
                SubAgentStatus::Failed(ref message) => TaskCompletion::Failed {
                    message: message.clone(),
                },
                SubAgentStatus::Interrupted(ref message) => TaskCompletion::Failed {
                    message: message.clone(),
                },
                SubAgentStatus::Cancelled => TaskCompletion::Cancelled,
                SubAgentStatus::BudgetExhausted => TaskCompletion::BudgetExhausted {
                    message: "sub-agent budget exhausted".to_string(),
                },
                SubAgentStatus::Running => unreachable!("guarded above"),
            };
            return (completion, usage);
        }
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    }
    (
        TaskCompletion::Failed {
            message: format!("sub-agent '{agent_id}' did not report a terminal status within 1s"),
        },
        None,
    )
}

/// Capture per-worker telemetry at terminal delivery (#2974): provider-reported
/// tokens from the worker ledger, the model/tool step count and duration from
/// the agent snapshot, and a durable artifact reference for the full output.
fn task_usage_from_manager(
    manager: &SubAgentManager,
    agent_id: &str,
    snapshot: &SubAgentResult,
) -> WorkflowTaskUsage {
    let record = manager.get_worker_record(agent_id);
    let usage = record.as_ref().map(|record| &record.usage);
    let result_ref = record.as_ref().and_then(|record| {
        record
            .artifacts
            .iter()
            .find(|artifact| artifact.kind == "transcript")
            .or_else(|| record.artifacts.last())
            .map(|artifact| artifact.target.clone())
    });
    let input_tokens = usage.and_then(|usage| usage.input_tokens);
    let output_tokens = usage.and_then(|usage| usage.output_tokens);
    let total_tokens = usage.and_then(|usage| usage.total_tokens);
    // #4039: the worker ledger leaves these fields `None` until it receives a
    // typed provider usage envelope. Presence, not magnitude, is the receipt:
    // a provider-reported zero is still a real observation and must survive.
    let reported = provider_usage_was_reported(input_tokens, output_tokens, total_tokens);
    WorkflowTaskUsage {
        input_tokens: reported.then_some(input_tokens).flatten(),
        output_tokens: reported.then_some(output_tokens).flatten(),
        total_tokens: reported.then_some(total_tokens).flatten(),
        cost_microusd: usage.and_then(|usage| usage.cost_microusd),
        tool_calls: Some(snapshot.steps_taken),
        duration_ms: Some(snapshot.duration_ms),
        result_ref,
        token_source: reported.then_some(WorkflowTokenSource::ProviderReported),
    }
}

fn provider_usage_was_reported(
    input_tokens: Option<u64>,
    output_tokens: Option<u64>,
    total_tokens: Option<u64>,
) -> bool {
    [input_tokens, output_tokens, total_tokens]
        .iter()
        .any(Option::is_some)
}

fn cancel_child_agents(manager: SharedSubAgentManager, ids: Vec<String>) {
    if ids.is_empty() {
        return;
    }
    if let Ok(mut manager_guard) = manager.try_write() {
        for id in ids {
            let _ = manager_guard.cancel_agent(&id);
        }
        return;
    }
    if tokio::runtime::Handle::try_current().is_ok() {
        spawn_supervised(
            "workflow-cancel-children",
            std::panic::Location::caller(),
            async move {
                let mut manager_guard = manager.write().await;
                for id in ids {
                    let _ = manager_guard.cancel_agent(&id);
                }
            },
        );
    }
}

fn lock_mutex<T>(mutex: &Mutex<T>) -> Result<MutexGuard<'_, T>, ToolError> {
    mutex
        .lock()
        .map_err(|_| ToolError::execution_failed("workflow state lock poisoned"))
}

fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
        .try_into()
        .unwrap_or(u64::MAX)
}

mod journal {
    use super::{
        SharedWorkflowControllers, SharedWorkflowLifecycles, SharedWorkflowRuns, WorkflowRunRecord,
        WorkflowRunStatus, WorkflowUiEvent, WorkflowWorkLifecycle,
    };
    use serde::{Deserialize, Serialize};
    use std::collections::HashMap;
    use std::fs::OpenOptions;
    use std::io::{BufRead, Write};
    use std::path::{Path, PathBuf};
    use std::sync::{Arc, Mutex, OnceLock};
    use tracing::warn;

    pub(super) const CODEWHALE_DIR: &str = ".codewhale";
    pub(super) const WORKFLOW_RUNS_FILE: &str = "workflow-runs.jsonl";

    /// Per-workspace workflow state shared across tool-registry rebuilds.
    pub(super) struct WorkflowWorkspaceState {
        pub runs: SharedWorkflowRuns,
        pub controllers: SharedWorkflowControllers,
        lifecycles: SharedWorkflowLifecycles,
        journal: WorkflowRunJournal,
    }

    impl WorkflowWorkspaceState {
        pub fn open(workspace: &Path) -> Arc<Self> {
            Self::open_inner(workspace, true)
        }

        /// Hydrate the journal without rewriting leftover `running` rows to
        /// `failed`. Host cancel uses this after a restart so a controller-less
        /// run can still be marked cancelled instead of looking like a crash.
        pub fn open_preserving_running(workspace: &Path) -> Arc<Self> {
            Self::open_inner(workspace, false)
        }

        fn open_inner(workspace: &Path, recover_orphans: bool) -> Arc<Self> {
            let journal = WorkflowRunJournal::open(workspace);
            let runs = Arc::new(Mutex::new(journal.hydrate_runs(recover_orphans)));
            Arc::new(Self {
                runs,
                controllers: Arc::new(Mutex::new(HashMap::new())),
                lifecycles: Arc::new(Mutex::new(HashMap::new())),
                journal,
            })
        }

        pub fn attach_lifecycle(&self, run_id: &str, lifecycle: WorkflowWorkLifecycle) {
            self.lifecycles
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .entry(run_id.to_string())
                .or_insert(lifecycle);
        }

        pub fn reconcile_snapshot(&self, record: &WorkflowRunRecord) {
            let lifecycle = self
                .lifecycles
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .get(&record.run_id)
                .cloned();
            if let Some(lifecycle) = lifecycle
                && let Err(err) = lifecycle.reconcile_record(record)
            {
                warn!(
                    run_id = record.run_id,
                    "workflow Work reconciliation failed: {err}"
                );
            }
        }

        pub fn reconcile_cancel(&self, run_id: &str, outcome: super::CancelOutcome) {
            let lifecycle = self
                .lifecycles
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .get(run_id)
                .cloned();
            if let Some(lifecycle) = lifecycle
                && let Err(err) = lifecycle.reconcile_cancel(outcome)
            {
                warn!(run_id, "workflow cancellation reconciliation failed: {err}");
            }
        }

        pub fn mark_owner_missing(&self, run_id: &str) {
            let lifecycle = self
                .lifecycles
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .get(run_id)
                .cloned();
            if let Some(lifecycle) = lifecycle {
                lifecycle.reconcile_missing();
            }
        }

        pub fn try_record_snapshot(&self, record: &WorkflowRunRecord) -> Result<(), String> {
            self.journal
                .append_snapshot(record)
                .map_err(|err| err.to_string())
        }

        pub fn record_snapshot(&self, record: &WorkflowRunRecord) {
            if let Err(err) = self.try_record_snapshot(record) {
                warn!("workflow journal snapshot failed: {err}");
            }
        }

        pub fn record_progress(&self, run_id: &str, message: &str) {
            if let Err(err) = self.journal.append_progress(run_id, message) {
                warn!("workflow journal progress failed: {err}");
            }
        }

        pub fn record_event(&self, run_id: &str, event: &WorkflowUiEvent) {
            if let Err(err) = self.journal.append_event(run_id, event) {
                warn!("workflow journal event failed: {err}");
            }
        }

        /// Durable journal location for full-fidelity run detail (#2974).
        pub fn journal_path(&self) -> &Path {
            &self.journal.ledger_path
        }
    }

    fn workspace_store() -> &'static Mutex<HashMap<PathBuf, Arc<WorkflowWorkspaceState>>> {
        static STORE: OnceLock<Mutex<HashMap<PathBuf, Arc<WorkflowWorkspaceState>>>> =
            OnceLock::new();
        STORE.get_or_init(|| Mutex::new(HashMap::new()))
    }

    pub(super) fn shared_workflow_state(workspace: &Path) -> Arc<WorkflowWorkspaceState> {
        let key = workspace
            .canonicalize()
            .unwrap_or_else(|_| workspace.to_path_buf());
        let mut store = workspace_store()
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        store
            .entry(key)
            .or_insert_with(|| WorkflowWorkspaceState::open(workspace))
            .clone()
    }

    /// Read-only lookup that never creates workspace state, a journal
    /// directory, or a ledger file. Used by the human-only `/structcopy`
    /// command (#2033), which must stay side-effect free.
    pub(super) fn peek_shared_workflow_state(
        workspace: &Path,
    ) -> Option<Arc<WorkflowWorkspaceState>> {
        let key = workspace
            .canonicalize()
            .unwrap_or_else(|_| workspace.to_path_buf());
        workspace_store()
            .lock()
            .unwrap_or_else(|poison| poison.into_inner())
            .get(&key)
            .cloned()
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(tag = "kind", rename_all = "snake_case")]
    enum WorkflowJournalRecord {
        // Boxed: a full run record dwarfs the progress variant
        // (clippy::large_enum_variant).
        Snapshot {
            run: Box<WorkflowRunRecord>,
        },
        Progress {
            run_id: String,
            message: String,
        },
        Event {
            run_id: String,
            event: Box<WorkflowUiEvent>,
        },
    }

    #[derive(Debug)]
    struct WorkflowRunJournal {
        ledger_path: PathBuf,
    }

    impl WorkflowRunJournal {
        fn open(workspace: &Path) -> Self {
            let dir = workspace.join(CODEWHALE_DIR);
            if let Err(err) = std::fs::create_dir_all(&dir) {
                warn!(
                    "workflow journal dir create failed ({}): {err}",
                    dir.display()
                );
            }
            let ledger_path = dir.join(WORKFLOW_RUNS_FILE);
            if !ledger_path.exists()
                && let Err(err) = std::fs::write(&ledger_path, "")
            {
                warn!(
                    "workflow journal create failed ({}): {err}",
                    ledger_path.display()
                );
            }
            Self { ledger_path }
        }

        fn hydrate_runs(&self, recover_orphans: bool) -> HashMap<String, WorkflowRunRecord> {
            let file = match std::fs::File::open(&self.ledger_path) {
                Ok(file) => file,
                Err(_) => return HashMap::new(),
            };
            let mut runs = HashMap::new();
            for line in std::io::BufReader::new(file).lines() {
                let Ok(line) = line else { continue };
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    continue;
                }
                let record = match serde_json::from_str::<WorkflowJournalRecord>(trimmed) {
                    Ok(record) => record,
                    Err(err) => {
                        warn!("workflow journal skipped malformed line: {err}");
                        continue;
                    }
                };
                match record {
                    WorkflowJournalRecord::Snapshot { run } => {
                        runs.insert(run.run_id.clone(), *run);
                    }
                    WorkflowJournalRecord::Progress { run_id, message } => {
                        if let Some(run) = runs.get_mut(&run_id) {
                            run.progress.push(message);
                        }
                    }
                    WorkflowJournalRecord::Event { run_id, event } => {
                        if let Some(run) = runs.get_mut(&run_id) {
                            run.push_event(*event);
                        }
                    }
                }
            }
            // Journals written before #2974 have no counters; rebuild them
            // from the retained tail so summaries stay truthful.
            for run in runs.values_mut() {
                run.events_total = run.events_total.max(run.events.len() as u64);
            }
            // A run journaled as Running belongs to a process that is gone;
            // without this it would show as live forever after a restart.
            // Host cancel skips this rewrite so it can still mark the line
            // cancelled with an honest "nothing live to stop" receipt.
            if recover_orphans {
                let mut recovered = Vec::new();
                for run in runs.values_mut() {
                    if run.status == WorkflowRunStatus::Running {
                        run.status = WorkflowRunStatus::Failed;
                        run.lifecycle_seq = run.lifecycle_seq.saturating_add(1);
                        run.completed_at_ms.get_or_insert_with(super::now_ms);
                        run.error = Some(
                            "process exited before the run completed (recovered on startup)"
                                .to_string(),
                        );
                        recovered.push(run.clone());
                    }
                }
                // The recovery decision is owner truth, not a presentation-only
                // repair. Append it so another restart replays the same terminal
                // sequence instead of rediscovering and incrementing it again.
                for run in recovered {
                    if let Err(err) = self.append_snapshot(&run) {
                        warn!(
                            run_id = run.run_id,
                            "workflow recovery snapshot append failed: {err}"
                        );
                    }
                }
            }
            runs
        }

        fn append_record(&self, record: &WorkflowJournalRecord) -> std::io::Result<()> {
            let mut line = serde_json::to_string(record)
                .map_err(|err| std::io::Error::other(err.to_string()))?;
            line.push('\n');
            let mut file = OpenOptions::new()
                .create(true)
                .append(true)
                .open(&self.ledger_path)?;
            file.write_all(line.as_bytes())?;
            file.flush()?;
            Ok(())
        }

        fn append_snapshot(&self, record: &WorkflowRunRecord) -> std::io::Result<()> {
            self.append_record(&WorkflowJournalRecord::Snapshot {
                run: Box::new(record.clone()),
            })
        }

        fn append_progress(&self, run_id: &str, message: &str) -> std::io::Result<()> {
            self.append_record(&WorkflowJournalRecord::Progress {
                run_id: run_id.to_string(),
                message: message.to_string(),
            })
        }

        fn append_event(&self, run_id: &str, event: &WorkflowUiEvent) -> std::io::Result<()> {
            self.append_record(&WorkflowJournalRecord::Event {
                run_id: run_id.to_string(),
                event: Box::new(event.clone()),
            })
        }
    }

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

        fn sample_record(run_id: &str, status: WorkflowRunStatus) -> WorkflowRunRecord {
            WorkflowRunRecord {
                run_id: run_id.to_string(),
                status,
                lifecycle_seq: 1,
                started_at_ms: 1,
                completed_at_ms: None,
                source_path: None,
                workflow_id: Some("fixture".to_string()),
                workflow_goal: Some("journal test".to_string()),
                token_budget: None,
                child_ids: Vec::new(),
                progress: Vec::new(),
                events: Vec::new(),
                schema_errors: Vec::new(),
                dispatch_failures: Vec::new(),
                result: None,
                execution: None,
                error: None,
                verify_on_complete: false,
                verification: None,
                plan_approval: None,
                gate_status: Vec::new(),
                usage: None,
                events_total: 0,
                events_dropped: 0,
            }
        }

        #[test]
        fn workflow_journal_hydrates_snapshots_and_progress() {
            let tmp = tempfile::tempdir().expect("tempdir");
            let state = WorkflowWorkspaceState::open(tmp.path());
            let running = sample_record("workflow_abc", WorkflowRunStatus::Running);
            state.record_snapshot(&running);
            state.record_progress("workflow_abc", "phase: scan");
            state.record_event(
                "workflow_abc",
                &WorkflowUiEvent::at(
                    5,
                    WorkflowUiEventKind::PhaseStarted {
                        title: "scan".to_string(),
                    },
                ),
            );

            let completed = WorkflowRunRecord {
                status: WorkflowRunStatus::Completed,
                completed_at_ms: Some(99),
                progress: vec!["phase: scan".to_string()],
                events: vec![WorkflowUiEvent::at(
                    5,
                    WorkflowUiEventKind::PhaseStarted {
                        title: "scan".to_string(),
                    },
                )],
                ..sample_record("workflow_abc", WorkflowRunStatus::Completed)
            };
            state.record_snapshot(&completed);
            state.record_event(
                "workflow_abc",
                &WorkflowUiEvent::at(
                    6,
                    WorkflowUiEventKind::HandoffPromoted {
                        artifact_id: "workflow_abc:scout-1:scout-gate:findings".to_string(),
                        gate_id: "scout-gate".to_string(),
                        kind: "findings".to_string(),
                        from_role: "scout".to_string(),
                        to_role: "implementer".to_string(),
                        producer_task_id: "scout-1".to_string(),
                    },
                ),
            );
            state.record_event(
                "workflow_abc",
                &WorkflowUiEvent::at(
                    7,
                    WorkflowUiEventKind::HandoffConsumed {
                        artifact_id: "workflow_abc:scout-1:scout-gate:findings".to_string(),
                        kind: "findings".to_string(),
                        from_role: "scout".to_string(),
                        to_role: "implementer".to_string(),
                        consumer_task_id: "implementer-1".to_string(),
                    },
                ),
            );

            let reloaded = WorkflowWorkspaceState::open(tmp.path());
            let runs = reloaded
                .runs
                .lock()
                .expect("runs lock")
                .get("workflow_abc")
                .cloned()
                .expect("hydrated run");
            assert_eq!(runs.status, WorkflowRunStatus::Completed);
            assert_eq!(runs.progress, vec!["phase: scan"]);
            assert_eq!(runs.events.len(), 3);
            assert_eq!(runs.events[0].event_type(), "phase_started");
            let promoted = serde_json::to_value(&runs.events[1]).expect("promoted receipt");
            assert_eq!(promoted["type"], "handoff_promoted");
            assert_eq!(
                promoted["artifact_id"],
                "workflow_abc:scout-1:scout-gate:findings"
            );
            assert_eq!(promoted["gate_id"], "scout-gate");
            assert_eq!(promoted["producer_task_id"], "scout-1");
            assert!(promoted.get("payload").is_none(), "{promoted}");
            let consumed = serde_json::to_value(&runs.events[2]).expect("consumed receipt");
            assert_eq!(consumed["type"], "handoff_consumed");
            assert_eq!(consumed["artifact_id"], promoted["artifact_id"]);
            assert_eq!(consumed["consumer_task_id"], "implementer-1");
            assert!(consumed.get("payload").is_none(), "{consumed}");
            assert_eq!(runs.completed_at_ms, Some(99));

            // The event-line replay above must also survive compaction into a
            // final Snapshot record containing both handoff variants.
            reloaded.record_snapshot(&runs);
            let reopened = WorkflowWorkspaceState::open(tmp.path());
            let compacted = reopened
                .runs
                .lock()
                .expect("runs lock")
                .get("workflow_abc")
                .cloned()
                .expect("snapshot with handoff receipts");
            assert_eq!(
                compacted
                    .events
                    .iter()
                    .map(WorkflowUiEvent::event_type)
                    .collect::<Vec<_>>(),
                vec!["phase_started", "handoff_promoted", "handoff_consumed"]
            );
        }

        #[test]
        fn workflow_journal_marks_orphaned_running_runs_failed() {
            let tmp = tempfile::tempdir().expect("tempdir");
            let state = WorkflowWorkspaceState::open(tmp.path());
            state.record_snapshot(&sample_record(
                "workflow_orphan",
                WorkflowRunStatus::Running,
            ));

            let reloaded = WorkflowWorkspaceState::open(tmp.path());
            let run = reloaded
                .runs
                .lock()
                .expect("runs lock")
                .get("workflow_orphan")
                .cloned()
                .expect("hydrated run");
            assert_eq!(run.status, WorkflowRunStatus::Failed);
            assert_eq!(
                run.lifecycle_seq, 2,
                "restart recovery is a durable owner lifecycle transition"
            );
            assert!(
                run.completed_at_ms.is_some(),
                "restart recovery must terminalize the durable owner record"
            );
            assert!(
                run.error
                    .as_deref()
                    .is_some_and(|error| error.contains("process exited")),
                "expected orphan recovery error, got {:?}",
                run.error
            );

            let reopened = WorkflowWorkspaceState::open(tmp.path());
            let replayed = reopened
                .runs
                .lock()
                .expect("runs lock")
                .get("workflow_orphan")
                .cloned()
                .expect("durably recovered run");
            assert_eq!(replayed.status, WorkflowRunStatus::Failed);
            assert_eq!(
                replayed.lifecycle_seq, 2,
                "reopening must replay the recovery snapshot without another transition"
            );
        }

        #[test]
        fn host_cancel_hydrates_a_journal_without_live_process_state() {
            let tmp = tempfile::tempdir().expect("tempdir");
            let state = WorkflowWorkspaceState::open(tmp.path());
            let record = sample_record("workflow_prior", WorkflowRunStatus::Running);
            state.record_snapshot(&record);
            drop(state);

            assert!(
                peek_shared_workflow_state(tmp.path()).is_none(),
                "writing the journal must not insert process-wide live state"
            );

            let line = super::super::host_cancel_workflow(tmp.path(), "workflow_prior")
                .expect("a journaled run must be visible to host cancel after restart");
            assert_eq!(line.run_id, "workflow_prior");
            assert_eq!(line.status, "cancelled");
            assert!(
                line.error
                    .as_deref()
                    .is_some_and(|error| error.contains("no live process")),
                "controller-less cancel must leave an honest receipt, got {:?}",
                line.error
            );

            let reopened = WorkflowWorkspaceState::open(tmp.path());
            let replayed = reopened
                .runs
                .lock()
                .expect("runs lock")
                .get("workflow_prior")
                .cloned()
                .expect("cancelled journal line");
            assert_eq!(replayed.status, WorkflowRunStatus::Cancelled);
        }
    }
}

use journal::{WorkflowWorkspaceState, peek_shared_workflow_state, shared_workflow_state};

/// Bounded, read-only projection of one workflow run for the human-only
/// `/structcopy` command (#2033).
///
/// Built on the existing [`WorkflowRunSummary`] projection so retention and
/// truncation accounting (`events_total` / `events_dropped`) stay in exactly
/// one place. Two extra constraints beyond the model-facing summary:
/// `source_path` collapses to a bare file-name label so no filesystem path
/// leaves the process, and raw event/hook payloads never enter the
/// projection. Returns `None` when `run_id` is unknown to this session;
/// never creates workspace state or touches the journal.
pub(crate) fn structcopy_run_projection(workspace: &Path, run_id: &str) -> Option<Value> {
    let state = peek_shared_workflow_state(workspace)?;
    let runs = state
        .runs
        .lock()
        .unwrap_or_else(|poison| poison.into_inner());
    let record = runs.get(run_id)?;
    let mut value = serde_json::to_value(record.summary()).ok()?;
    if let Some(object) = value.as_object_mut() {
        let source_file = record
            .source_path
            .as_ref()
            .and_then(|path| path.file_name())
            .and_then(|name| name.to_str())
            .map(|name| Value::String(name.to_string()))
            .unwrap_or(Value::Null);
        object.remove("source_path");
        object.insert("source_file".to_string(), source_file);
        // `WorkflowRunSummary` predates truthful unavailable-state rendering
        // and uses zero defaults when no execution projection exists. A
        // structural export must not turn that absence into measured zeros.
        if record.execution.is_none() {
            object.insert("leaf_count".to_string(), Value::Null);
            object.insert("branch_count".to_string(), Value::Null);
            object.insert("control_count".to_string(), Value::Null);
        }
    }
    Some(value)
}

/// One workflow run as the human-facing `/workflow` command reads it: a
/// bounded projection of the run record with no raw event payloads and no
/// filesystem paths beyond the source file name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HostWorkflowRunLine {
    pub run_id: String,
    /// Machine token: running | completed | degraded | failed | cancelled.
    pub status: &'static str,
    /// The run's goal, its workflow id, or the source file name.
    pub label: String,
    pub started_at_ms: u64,
    pub completed_at_ms: Option<u64>,
    pub child_count: usize,
    pub last_progress: Option<String>,
    pub error: Option<String>,
}

fn host_run_line(record: &WorkflowRunRecord) -> HostWorkflowRunLine {
    let summary = record.summary();
    let label = summary
        .workflow_goal
        .clone()
        .or_else(|| summary.workflow_id.clone())
        .or_else(|| {
            summary
                .source_path
                .as_ref()
                .and_then(|path| path.file_name())
                .map(|name| name.to_string_lossy().into_owned())
        })
        .unwrap_or_else(|| "workflow".to_string());
    HostWorkflowRunLine {
        run_id: summary.run_id,
        status: match summary.status {
            WorkflowRunStatus::Running => "running",
            WorkflowRunStatus::Completed => "completed",
            WorkflowRunStatus::Degraded => "degraded",
            WorkflowRunStatus::Failed => "failed",
            WorkflowRunStatus::Cancelled => "cancelled",
        },
        label,
        started_at_ms: summary.started_at_ms,
        completed_at_ms: summary.completed_at_ms,
        child_count: summary.child_count,
        last_progress: summary.last_progress,
        error: summary.error,
    }
}

/// Live workspace state if this process already has it, otherwise the
/// existing run journal. Never creates `.codewhale/` or the ledger.
fn host_workflow_state(workspace: &Path) -> Option<Arc<WorkflowWorkspaceState>> {
    if let Some(state) = peek_shared_workflow_state(workspace) {
        return Some(state);
    }
    // No live state yet: hydrate only if a journal already exists so
    // status/cancel can see runs from a previous process without creating
    // files in a workspace that never ran a workflow.
    workflow_journal_exists(workspace).then(|| shared_workflow_state(workspace))
}

/// Cancel hydrates an on-disk journal without the restart-orphan Failed
/// rewrite so a running line with no live controller can still be cancelled.
fn host_workflow_state_for_cancel(workspace: &Path) -> Option<Arc<WorkflowWorkspaceState>> {
    if let Some(state) = peek_shared_workflow_state(workspace) {
        return Some(state);
    }
    workflow_journal_exists(workspace)
        .then(|| WorkflowWorkspaceState::open_preserving_running(workspace))
}

fn workflow_journal_exists(workspace: &Path) -> bool {
    workspace
        .join(journal::CODEWHALE_DIR)
        .join(journal::WORKFLOW_RUNS_FILE)
        .is_file()
}

/// Every workflow run this workspace knows about (live and journaled),
/// oldest first. Read-only: never creates the journal or workspace state.
/// The `/workflow status` command reads this directly so status never costs
/// a model turn.
pub(crate) fn host_workflow_runs(workspace: &Path) -> Vec<HostWorkflowRunLine> {
    let Some(state) = host_workflow_state(workspace) else {
        return Vec::new();
    };
    let runs = state
        .runs
        .lock()
        .unwrap_or_else(|poison| poison.into_inner());
    let mut lines: Vec<HostWorkflowRunLine> = runs.values().map(host_run_line).collect();
    lines.sort_by_key(|line| line.started_at_ms);
    lines
}

/// Cancel a running workflow directly from the host (the `/workflow cancel`
/// command and the panel's cancel control), without a model turn. Returns
/// the run's projection after cancellation, or a plain reason when the run
/// is unknown. A run that already finished is reported as it is. After a
/// restart, a journaled running line with no live controller is cancelled
/// in the journal rather than rejected as unknown or controller-missing.
pub(crate) fn host_cancel_workflow(
    workspace: &Path,
    run_id: &str,
) -> Result<HostWorkflowRunLine, String> {
    let Some(state) = host_workflow_state_for_cancel(workspace) else {
        return Err(format!("Unknown workflow run '{run_id}'."));
    };
    match cancel_workflow_run(run_id, state.clone()) {
        Ok(_) => {
            let runs = state
                .runs
                .lock()
                .unwrap_or_else(|poison| poison.into_inner());
            runs.get(run_id)
                .map(host_run_line)
                .ok_or_else(|| format!("Unknown workflow run '{run_id}'."))
        }
        Err(err) => Err(err.to_string()),
    }
}

/// Seed a minimal run record so `/structcopy` tests can exercise the
/// workflow projection without standing up the JS VM.
#[cfg(test)]
pub(crate) fn structcopy_test_seed_run(workspace: &Path, run_id: &str) {
    let state = shared_workflow_state(workspace);
    let record = WorkflowRunRecord::new(run_id.to_string(), None, None, None);
    state
        .runs
        .lock()
        .unwrap_or_else(|poison| poison.into_inner())
        .insert(run_id.to_string(), record);
}

/// Reconcile workflow bindings after the journal has replayed restart
/// recovery. The journal owns lifecycle truth; the graph only receives its
/// monotonic projection.
pub(crate) fn reconcile_persisted_workflow_bindings(
    work: &SharedWorkRuntime,
    session_id: &str,
    workspace: &Path,
) -> Result<usize, String> {
    let state = shared_workflow_state(workspace);
    let records = state
        .runs
        .lock()
        .unwrap_or_else(|poison| poison.into_inner())
        .values()
        .cloned()
        .collect::<Vec<_>>();
    let candidates = work
        .reconcilable_durable_bindings(Some(session_id))
        .into_iter()
        .filter(|external| external.starts_with("workflow:"))
        .collect::<std::collections::HashSet<_>>();
    let mut seen = std::collections::HashSet::new();
    let mut changed = 0usize;
    for record in records {
        let external = format!("workflow:{}", record.run_id);
        if !candidates.contains(&external) {
            continue;
        }
        seen.insert(external.clone());
        let lifecycle = WorkflowWorkLifecycle {
            work: work.clone(),
            session_id: session_id.to_string(),
            external,
        };
        changed += usize::from(lifecycle.reconcile_record(&record)?);
    }
    for external in candidates.difference(&seen) {
        changed += usize::from(work.reconcile_observation(
            session_id,
            external,
            OperationObservation::OwnerMissing {
                checked_at: i64::try_from(now_ms()).unwrap_or(i64::MAX),
            },
        )?);
    }
    Ok(changed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::DeepSeekClient;
    use crate::tools::ToolRegistryBuilder;
    use crate::tools::subagent::{SubAgentRuntime, new_shared_subagent_manager};
    use axum::{Json, Router, routing::post};
    use codewhale_workflow::{IsolationMode, leaf_is_write_capable};
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn settled_runs_leave_a_report_artifact_under_codewhale_reports() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let mut record = WorkflowRunRecord::new("workflow_report_1".to_string(), None, None, None);
        record.status = WorkflowRunStatus::Completed;
        record.workflow_goal = Some("prove the report artifact".to_string());
        record.progress.push("phase: scan".to_string());
        record.result = Some(serde_json::json!({"confirmed": 2}));

        write_run_report_artifact(tmp.path(), &record);

        let path = tmp
            .path()
            .join(".codewhale")
            .join("reports")
            .join("workflow_report_1.md");
        let body = std::fs::read_to_string(&path).expect("report written");
        assert!(body.contains("# Workflow run workflow_report_1"), "{body}");
        assert!(body.contains("status: Completed"), "{body}");
        assert!(body.contains("prove the report artifact"), "{body}");
        assert!(body.contains("phase: scan"), "{body}");
        assert!(body.contains("\"confirmed\": 2"), "{body}");
    }

    #[test]
    fn running_runs_write_no_report_artifact() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let record = WorkflowRunRecord::new("workflow_report_2".to_string(), None, None, None);
        write_run_report_artifact(tmp.path(), &record);
        assert!(
            !tmp.path().join(".codewhale").join("reports").exists(),
            "running runs must not leave report files"
        );
    }

    #[test]
    fn source_path_accepts_the_home_workflow_store_and_rejects_elsewhere() {
        let _lock = crate::test_support::lock_test_env();
        let tmp = tempfile::tempdir().expect("tempdir");
        let home = tmp.path().join("home");
        let store = home.join(".codewhale").join("workflows");
        std::fs::create_dir_all(&store).expect("store");
        let _home_guard = crate::test_support::EnvVarGuard::set("HOME", &home);
        let _userprofile_guard = crate::test_support::EnvVarGuard::set("USERPROFILE", &home);

        let saved = store.join("triage.workflow.js");
        std::fs::write(&saved, "phase('scan');\n").expect("write saved workflow");
        let elsewhere = tmp.path().join("outside.workflow.js");
        std::fs::write(&elsewhere, "phase('scan');\n").expect("write outside workflow");

        let workspace = tmp.path().join("ws");
        std::fs::create_dir_all(&workspace).expect("workspace");
        let context = ToolContext::new(workspace);

        let resolved = read_workflow_source_path(saved.to_str().expect("utf8 path"), &context)
            .expect("home workflow store is a first-class source");
        assert!(resolved.source.contains("phase('scan')"));

        let err = read_workflow_source_path(elsewhere.to_str().expect("utf8 path"), &context)
            .expect_err("arbitrary outside paths stay denied");
        assert!(
            err.to_string()
                .contains("workspace or ~/.codewhale/workflows"),
            "{err}"
        );
    }

    #[test]
    fn restored_workflow_binding_consumes_journal_recovery() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let state = WorkflowWorkspaceState::open(tmp.path());
        let record = WorkflowRunRecord::new("workflow_restore".to_string(), None, None, None);
        state.record_snapshot(&record);

        let work = crate::work_graph::new_shared_work_runtime(
            crate::tools::todo::new_shared_todo_list(),
            crate::tools::plan::new_shared_plan_state(),
        );
        work.register_operation(
            "restored-workflow-session",
            OperationIntent::new(
                "workflow:workflow_restore",
                "restored workflow",
                true,
                "workflow",
                "restore-test",
            ),
        )
        .expect("register saved workflow binding");
        work.reconcile_operation(
            "restored-workflow-session",
            OperationOwnerSnapshot::new("workflow:workflow_restore", OwnerState::Running, 1, 1),
        )
        .expect("saved running owner state");
        work.register_operation(
            "restored-workflow-session",
            OperationIntent::new(
                "workflow:workflow_absent",
                "absent workflow",
                true,
                "workflow",
                "absent-restore-test",
            ),
        )
        .expect("register absent workflow binding");
        work.reconcile_operation(
            "restored-workflow-session",
            OperationOwnerSnapshot::new("workflow:workflow_absent", OwnerState::Running, 1, 1),
        )
        .expect("saved absent owner state");

        assert_eq!(
            reconcile_persisted_workflow_bindings(&work, "restored-workflow-session", tmp.path(),),
            Ok(2)
        );
        let graph = work
            .capture(Some("restored-workflow-session"))
            .expect("capture restored workflow")
            .expect("graph")
            .graph;
        let operation = graph
            .nodes
            .iter()
            .find(|node| {
                node.binding
                    .as_ref()
                    .is_some_and(|binding| binding.external == "workflow:workflow_restore")
            })
            .expect("workflow operation");
        assert_eq!(operation.state, crate::work_graph::NodeState::Failed);
        assert_eq!(
            operation
                .binding
                .as_ref()
                .and_then(|binding| binding.last_observation.as_ref())
                .map(|observation| observation.seq),
            Some(2),
            "journal replay must advance the lost live owner before graph reconciliation"
        );
        let absent = graph
            .nodes
            .iter()
            .find(|node| {
                node.binding
                    .as_ref()
                    .is_some_and(|binding| binding.external == "workflow:workflow_absent")
            })
            .expect("absent workflow operation");
        assert_eq!(absent.state, crate::work_graph::NodeState::Stale);
        assert_eq!(
            reconcile_persisted_workflow_bindings(&work, "restored-workflow-session", tmp.path(),),
            Ok(0),
            "rechecking an already stale missing owner must be idempotent"
        );
    }

    #[tokio::test]
    async fn cancellation_without_controller_marks_the_journal_cancelled() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let state = WorkflowWorkspaceState::open(tmp.path());
        let record =
            WorkflowRunRecord::new("workflow_missing_controller".to_string(), None, None, None);
        state
            .runs
            .lock()
            .expect("runs lock")
            .insert(record.run_id.clone(), record.clone());
        state.record_snapshot(&record);

        let work = crate::work_graph::new_shared_work_runtime(
            crate::tools::todo::new_shared_todo_list(),
            crate::tools::plan::new_shared_plan_state(),
        );
        work.register_operation(
            "missing-controller-session",
            OperationIntent::new(
                "workflow:workflow_missing_controller",
                "missing controller",
                true,
                "workflow",
                "missing-controller-test",
            ),
        )
        .expect("register workflow");
        work.reconcile_operation(
            "missing-controller-session",
            OperationOwnerSnapshot::new(
                "workflow:workflow_missing_controller",
                OwnerState::Running,
                1,
                1,
            ),
        )
        .expect("running workflow");
        state.attach_lifecycle(
            "workflow_missing_controller",
            WorkflowWorkLifecycle {
                work: work.clone(),
                session_id: "missing-controller-session".to_string(),
                external: "workflow:workflow_missing_controller".to_string(),
            },
        );

        cancel_workflow(
            json!({"run_id": "workflow_missing_controller"}),
            state.clone(),
        )
        .await
        .expect("controller-less cancel must still journal cancelled");
        let record = state
            .runs
            .lock()
            .expect("runs lock")
            .get("workflow_missing_controller")
            .cloned()
            .expect("workflow owner");
        assert_eq!(record.status, WorkflowRunStatus::Cancelled);
        assert_eq!(record.lifecycle_seq, 2);
        assert!(
            record
                .error
                .as_deref()
                .is_some_and(|error| error.contains("no live process")),
            "expected an honest nothing-live receipt, got {:?}",
            record.error
        );
        let operation = work
            .capture(Some("missing-controller-session"))
            .expect("capture")
            .expect("graph")
            .graph
            .nodes
            .into_iter()
            .find(|node| node.kind == crate::work_graph::NodeKind::Operation)
            .expect("workflow operation");
        assert_eq!(operation.state, crate::work_graph::NodeState::Cancelled);
    }

    #[test]
    fn handoff_compaction_preserves_release_sized_evidence() {
        let payload = format!("APPROVE\n{}\nterminal: RunCompleted", "e".repeat(1_500));

        assert_eq!(
            compact_handoff_payload(&payload, WORKFLOW_HANDOFF_MAX_CHARS),
            payload
        );
    }

    #[test]
    fn handoff_compaction_still_caps_oversized_artifacts() {
        let payload = "e".repeat(WORKFLOW_HANDOFF_MAX_CHARS + 1);
        let compacted = compact_handoff_payload(&payload, WORKFLOW_HANDOFF_MAX_CHARS);

        assert_eq!(compacted.chars().count(), WORKFLOW_HANDOFF_MAX_CHARS + 3);
        assert!(compacted.ends_with("..."));
    }

    #[test]
    fn declarative_detection_matches_indented_and_nonleading_workflow_calls() {
        // column-0 forms
        assert!(looks_like_declarative_workflow("workflow({ tasks: [] })"));
        assert!(looks_like_declarative_workflow(
            "export default workflow({})"
        ));
        // #dogfood 0.8.67: a leading statement/comment followed by an INDENTED
        // top-level workflow( call must still be detected as declarative.
        assert!(looks_like_declarative_workflow(
            "// build the run\n  workflow({\n    tasks: [],\n  })"
        ));
        // imperative scripts must not be misdetected as declarative
        assert!(!looks_like_declarative_workflow(
            "return await parallel([() => task({ description: \"x\" })]);"
        ));
        assert!(!looks_like_declarative_workflow("const x = myworkflow(1);"));
    }

    #[test]
    fn workflow_action_defaults_to_start() {
        assert_eq!(
            parse_workflow_action(&json!({})).unwrap(),
            WorkflowAction::Start
        );
        assert_eq!(
            parse_workflow_action(&json!({"action": "run"})).unwrap(),
            WorkflowAction::Run
        );
    }

    #[test]
    fn named_fleet_maps_workflow_role_to_profile_before_spawn() {
        let fleet = FleetRoleMap::from_pairs([
            ("scout", "scout"),
            ("implementer", "builder"),
            ("reviewer", "reviewer"),
            ("verifier", "verifier"),
            ("release_lead", "manager"),
        ])
        .expect("fleet");
        let mut request = TaskRequest {
            description: "fix it".to_string(),
            subagent_type: None,
            role: Some("implementer".to_string()),
            profile: None,
            model: None,
            model_strength: None,
            thinking: None,
            cwd: None,
            worktree: true,
            write_authority: Some("worktree_write".to_string()),
            write_roots: vec!["src".to_string()],
            exact_files: Vec::new(),
            coordination_contracts: vec!["test-contract".to_string()],
            dependencies: Vec::new(),
            acceptance: Vec::new(),
            allowed_tools: None,
            disallowed_tools: Vec::new(),
            max_depth: None,
            token_budget: None,
            max_steps: None,
            wall_time_secs: None,
            response_schema: None,
            label: Some("fix".to_string()),
            phase: Some("implement".to_string()),
        };

        apply_named_fleet_to_task_request(Some(&fleet), &mut request).expect("resolve");

        assert_eq!(request.role.as_deref(), Some("implementer"));
        assert_eq!(request.profile.as_deref(), Some("builder"));
    }

    // ── Exact named Fleet (schema = "exact") ────────────────────────────────

    /// A Fleet that references a saved, reusable Reasoning Router service, and
    /// whose members' ids differ from their semantic roles — the case a gate
    /// keyed on a role has to keep working through.
    const EXACT_GLM_FLEET: &str = r#"
name = "glm-pair"
schema = "exact"
reasoning_router = "luna-low"

[[members]]
id = "implementer"
role = "builder"
provider = "zai"
model = "glm-5"
reasoning = "auto"
permissions = "read_write"

[[members]]
id = "auditor"
role = "reviewer"
provider = "zai"
model = "glm-5"
reasoning = "high"
permissions = "read_only"
"#;

    fn exact_task_request(role: &str) -> TaskRequest {
        TaskRequest {
            description: "land the fix".to_string(),
            subagent_type: None,
            role: Some(role.to_string()),
            profile: None,
            model: None,
            model_strength: None,
            thinking: None,
            cwd: None,
            worktree: false,
            write_authority: None,
            write_roots: Vec::new(),
            exact_files: Vec::new(),
            coordination_contracts: Vec::new(),
            dependencies: Vec::new(),
            acceptance: Vec::new(),
            allowed_tools: None,
            disallowed_tools: Vec::new(),
            max_depth: None,
            token_budget: None,
            max_steps: None,
            wall_time_secs: None,
            response_schema: None,
            label: None,
            phase: None,
        }
    }

    /// A task for a write-capable member. The spawn boundary refuses an
    /// unbounded write claim, so a write-capable exact task always carries a
    /// declared scope — the same contract, checked before the Router runs.
    fn exact_write_task_request(role: &str) -> TaskRequest {
        TaskRequest {
            write_roots: vec!["crates/tui".to_string()],
            ..exact_task_request(role)
        }
    }

    fn exact_session() -> codewhale_workflow::PermissionCeiling {
        codewhale_workflow::PermissionCeiling::preset("full").expect("preset")
    }

    fn exact_workflow_with(
        text: &str,
        router: Option<std::sync::Arc<crate::fleet::exact::StaticFleetRouter>>,
    ) -> crate::fleet::exact::ExactFleetWorkflow {
        let document = codewhale_workflow::FleetDocument::parse(text).expect("exact fleet parses");
        crate::fleet::exact::ExactFleetWorkflow::for_tests(
            &document,
            codewhale_workflow::QualifiedFleetId {
                name: "glm-pair".to_string(),
                origin: "workspace".to_string(),
            },
            router,
        )
    }

    fn exact_workflow(text: &str) -> crate::fleet::exact::ExactFleetWorkflow {
        exact_workflow_with(
            text,
            Some(crate::fleet::exact::StaticFleetRouter::new(
                r#"{"reasoning":"max"}"#,
            )),
        )
    }

    /// Binding resolves the member and its ceiling; routing resolves reasoning.
    /// Both halves land on the request, in that order.
    #[tokio::test]
    async fn exact_fleet_task_launch_resolves_the_member_route_and_ceiling() {
        let operation = exact_workflow(EXACT_GLM_FLEET);
        let mut request = exact_write_task_request("builder");

        let binding = bind_exact_fleet_task_request(&operation, exact_session(), &mut request)
            .expect("exact member resolves");

        // Addressed by member id, so the run-scoped roster profile (which
        // carries the exact provider pin and canonical wire model) is what the
        // spawn resolves…
        assert_eq!(request.profile.as_deref(), Some("implementer"));
        // …while the semantic role is preserved for gates and records.
        assert_eq!(request.role.as_deref(), Some("builder"));
        let member = operation.roster().get("implementer").expect("roster");
        assert_eq!(member.profile.provider.as_deref(), Some("zai"));
        assert_eq!(member.profile.model.as_deref(), Some("glm-5"));

        // The saved ceiling reached the spawn request before any routing.
        assert_eq!(request.write_authority.as_deref(), Some("workspace_write"));
        assert_eq!(request.max_depth, Some(0));
        assert!(request.thinking.is_none(), "reasoning is not decided yet");

        route_admitted_exact_task(&operation, &binding, &mut request)
            .await
            .expect("routing");
        // `auto` was resolved by the Router into a concrete tier — never the
        // literal sentinel, and never the legacy local heuristic.
        assert_eq!(request.thinking.as_deref(), Some("max"));

        // A read-only member is launched read-only, with no router call.
        let mut auditor = exact_task_request("reviewer");
        let auditor_binding =
            bind_exact_fleet_task_request(&operation, exact_session(), &mut auditor)
                .expect("auditor resolves");
        route_admitted_exact_task(&operation, &auditor_binding, &mut auditor)
            .await
            .expect("routing");
        assert_eq!(auditor.write_authority.as_deref(), Some("read_only"));
        assert_eq!(auditor.thinking.as_deref(), Some("high"));
        assert_eq!(auditor.role.as_deref(), Some("reviewer"));
        assert_eq!(auditor.profile.as_deref(), Some("auditor"));
    }

    /// The session's `[workflow]` table must decide the approval requirement;
    /// before this the tool consulted product defaults only, so a user who
    /// set `require_approval_for_writes = false` (documented in
    /// docs/AUTOMATIC_WORKFLOWS.md) still got the approval card.
    #[test]
    fn workflow_tool_honors_the_session_workflow_config() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let mut runtime = SubAgentRuntime::new(
            stub_client(),
            "deepseek-v4-flash".to_string(),
            ctx,
            true,
            None,
            manager.clone(),
        );
        let input = json!({
            "action": "start",
            "plan": {
                "goal": "write freely",
                "risk": "writes",
                "children": [{ "prompt": "edit", "type": "implementer" }]
            }
        });
        let tool = WorkflowTool::new(Arc::clone(&manager), runtime.clone());
        assert_eq!(
            tool.approval_requirement_for(&input),
            ApprovalRequirement::Required,
            "product default: writes need approval"
        );

        let config = crate::config::Config {
            workflow: Some(codewhale_config::WorkflowConfigToml {
                require_approval_for_writes: false,
                ..Default::default()
            }),
            ..Default::default()
        };
        runtime.api_config = Some(Arc::new(config));
        let tool = WorkflowTool::new(Arc::clone(&manager), runtime.clone());
        assert_eq!(
            tool.approval_requirement_for(&input),
            ApprovalRequirement::Auto,
            "the session config must win"
        );

        let read_only = json!({
            "action": "start",
            "plan": {
                "goal": "scout crates",
                "risk": "read_only",
                "children": [{ "prompt": "look", "type": "explore" }]
            }
        });
        let config = crate::config::Config {
            workflow: Some(codewhale_config::WorkflowConfigToml {
                auto_start_read_only: false,
                ..Default::default()
            }),
            ..Default::default()
        };
        runtime.api_config = Some(Arc::new(config));
        let tool = WorkflowTool::new(manager, runtime);
        assert_eq!(
            tool.approval_requirement_for(&read_only),
            ApprovalRequirement::Required,
            "auto_start_read_only = false must still ask"
        );
    }

    /// The gate machinery keys on the **semantic role**. It must still fire
    /// when a member's id differs from that role — the exact failure an earlier
    /// pass introduced by stamping the profile id into `role`.
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn a_role_keyed_gate_still_fires_when_the_member_id_differs() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let runtime = SubAgentRuntime::new(
            stub_client(),
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let state = WorkflowWorkspaceState::open(tmp.path());
        let run_id = "workflow_exact_gate".to_string();
        // The gate blocks the semantic role `builder`, whose member id is the
        // *different* string `implementer`.
        let gates = vec![GateSpec {
            id: "scout-findings".to_string(),
            role: "scout".to_string(),
            on: GateOn::RoleComplete,
            gate: GateKind::Approve,
            on_fail: codewhale_workflow::GateOnFail::Block,
            blocks_role: Some("builder".to_string()),
            max_retries: 0,
            artifact_kind: Some("findings".to_string()),
            require_explicit_verdict: false,
        }];
        state.runs.lock().expect("runs").insert(
            run_id.clone(),
            WorkflowRunRecord::new(run_id.clone(), None, None, None),
        );
        let driver = SubAgentWorkflowDriver::new(
            run_id.clone(),
            manager,
            runtime,
            state.clone(),
            None,
            WorkflowFleetBinding::None,
            gates,
        );

        // The upstream scout fails, which puts the gate into a blocking state.
        driver.evaluate_gates_for_completed_role(&RuntimeTaskRecord {
            agent_id: "scout-agent".to_string(),
            label: Some("scout".to_string()),
            role: Some("scout".to_string()),
            status: IrWorkflowRunStatus::Failed,
            output: None,
            schema_error: None,
            usage: None,
        });

        let operation = exact_workflow(EXACT_GLM_FLEET);
        let mut request = exact_write_task_request("builder");
        bind_exact_fleet_task_request(&operation, exact_session(), &mut request).expect("bind");

        assert_ne!(
            request.role.as_deref(),
            request.profile.as_deref(),
            "this fleet's ids and roles differ, which is the whole point"
        );
        assert_eq!(request.role.as_deref(), Some("builder"));

        let err = driver
            .prepare_request_for_gates(&mut request)
            .expect_err("a blocking gate on `builder` must still see `builder`");
        assert!(err.to_string().contains("builder"), "{err}");

        // The same gate does *not* block a task carrying the member id, which
        // is exactly why stamping the id into `role` silently disabled it.
        let mut by_id = exact_task_request("builder");
        by_id.role = Some("implementer".to_string());
        by_id.profile = None;
        assert!(
            driver.prepare_request_for_gates(&mut by_id).is_ok(),
            "the profile id is not the semantic role the gate keys on"
        );
    }

    /// A task whose `role` and `profile` name different members is rejected
    /// rather than resolved by precedence.
    #[test]
    fn exact_fleet_rejects_a_conflicting_task_role_and_profile() {
        let operation = exact_workflow(EXACT_GLM_FLEET);
        let mut request = exact_task_request("reviewer");
        request.profile = Some("implementer".to_string());

        let err = bind_exact_fleet_task_request(&operation, exact_session(), &mut request)
            .expect_err("conflicting identity");
        let message = format!("{err:?}");
        assert!(message.contains("different members"), "{message}");
    }

    #[test]
    fn exact_fleet_rejects_task_level_route_overrides() {
        let operation = exact_workflow(EXACT_GLM_FLEET);

        for mutate in [
            (|request: &mut TaskRequest| request.model = Some("glm-4".to_string()))
                as fn(&mut TaskRequest),
            |request: &mut TaskRequest| request.model_strength = Some("faster".to_string()),
            |request: &mut TaskRequest| request.thinking = Some("off".to_string()),
        ] {
            let mut request = exact_task_request("builder");
            mutate(&mut request);
            let err = bind_exact_fleet_task_request(&operation, exact_session(), &mut request)
                .expect_err("an exact fleet member may not be re-routed per task");
            let message = format!("{err:?}");
            assert!(
                message.contains("not allowed"),
                "override must be rejected, not ignored: {message}"
            );
        }
    }

    /// A task must not be able to widen a member's saved ceiling by asking for
    /// a different agent type, a broader tool surface, or write authority.
    #[test]
    fn exact_fleet_rejects_task_level_posture_widening() {
        let operation = exact_workflow(EXACT_GLM_FLEET);

        for (field, mutate) in [
            (
                "subagent_type",
                (|request: &mut TaskRequest| {
                    request.subagent_type = Some("general".to_string());
                }) as fn(&mut TaskRequest),
            ),
            ("allowed_tools", |request: &mut TaskRequest| {
                request.allowed_tools = Some(vec!["shell".to_string()]);
            }),
            ("write_authority", |request: &mut TaskRequest| {
                request.write_authority = Some("workspace_write".to_string());
            }),
        ] {
            // The read-only auditor is the interesting victim: its saved
            // ceiling is the narrowest in the fleet.
            let mut request = exact_task_request("reviewer");
            mutate(&mut request);
            let err = bind_exact_fleet_task_request(&operation, exact_session(), &mut request)
                .expect_err("an exact ceiling must win over a task option");
            let message = format!("{err:?}");
            assert!(
                message.contains(field) && message.contains("not allowed"),
                "{field} must be rejected: {message}"
            );
        }

        // And with no task options at all, the saved ceiling is what lands.
        let mut clean = exact_task_request("reviewer");
        bind_exact_fleet_task_request(&operation, exact_session(), &mut clean)
            .expect("clean launch");
        assert_eq!(clean.write_authority.as_deref(), Some("read_only"));
        assert_eq!(clean.subagent_type, None);
    }

    /// The saved ceiling becomes a real tool policy on the spawn request: a
    /// member with no network tool carries a deny list the child enforces.
    #[test]
    fn exact_fleet_ceilings_reach_the_spawn_request_as_a_tool_policy() {
        let operation = exact_workflow(EXACT_GLM_FLEET);
        let mut request = exact_task_request("reviewer");

        bind_exact_fleet_task_request(&operation, exact_session(), &mut request).expect("bind");

        // `read_only` has tools but no network tool.
        assert_eq!(
            request.allowed_tools, None,
            "a tool-using member keeps full inheritance, narrowed by the deny list"
        );
        // The Web family *name* survives so the read-only search/fetch actions
        // stay reachable; every reaching spelling is denied by the list the
        // child registry enforces.
        for denied in [
            "web.run",
            "web_search",
            "fetch_url",
            "wait_for_dev_server",
            "mcp*",
        ] {
            assert!(
                request.disallowed_tools.iter().any(|name| name == denied),
                "{denied} must be denied: {:?}",
                request.disallowed_tools
            );
        }
        assert!(
            !request.disallowed_tools.iter().any(|name| name == "Web"),
            "the Web family name must stay reachable so search/fetch survive: {:?}",
            request.disallowed_tools
        );
    }

    /// A Router decision is paid for before the child exists. If the spawn then
    /// fails, the receipt is the only record that tokens were spent and — for a
    /// cross-provider Router — that a bounded summary already left the host. It
    /// must survive the failure rather than being dropped with it.
    #[tokio::test]
    async fn a_routing_receipt_survives_a_failed_spawn() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let runtime = SubAgentRuntime::new(
            stub_client(),
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let state = WorkflowWorkspaceState::open(tmp.path());
        let run_id = "workflow_orphaned_receipt".to_string();
        state.runs.lock().expect("runs").insert(
            run_id.clone(),
            WorkflowRunRecord::new(run_id.clone(), None, None, None),
        );
        let driver = SubAgentWorkflowDriver::new(
            run_id.clone(),
            manager,
            runtime,
            state.clone(),
            None,
            WorkflowFleetBinding::None,
            Vec::new(),
        );

        let operation = exact_workflow(EXACT_GLM_FLEET);
        let mut request = exact_write_task_request("builder");
        let binding =
            bind_exact_fleet_task_request(&operation, exact_session(), &mut request).expect("bind");
        let receipt = route_admitted_exact_task(&operation, &binding, &mut request)
            .await
            .expect("routing");

        driver.record_orphaned_fleet_receipt(&receipt, "Sub-agent depth limit reached");

        let events = state
            .runs
            .lock()
            .expect("runs")
            .get(&run_id)
            .expect("run")
            .events
            .clone();
        let logged = events
            .iter()
            .filter_map(|event| match &event.kind {
                WorkflowUiEventKind::Log { message } => Some(message.clone()),
                _ => None,
            })
            .find(|message| message.contains("spawn_failed=true"))
            .expect("the receipt must outlive the failed spawn");

        assert!(logged.contains("member=implementer"), "{logged}");
        assert!(logged.contains("source=fleet_router"), "{logged}");
        assert!(
            logged.contains("reasoning_router:workspace/luna-low"),
            "{logged}"
        );
        assert!(logged.contains("Sub-agent depth limit reached"), "{logged}");
        // Still content-free: a failure line is no excuse to echo the task.
        assert!(!logged.contains("land the fix"), "{logged}");
    }

    /// A member's semantic role is what the operator named and what gates key
    /// on; the roster profile's role is the permission **posture** the clamped
    /// ceiling permits. The started event must show the first, not the second.
    #[tokio::test]
    async fn a_started_event_shows_the_members_role_not_its_permission_posture() {
        const AUDIT_FLEET: &str = r#"
name = "glm-pair"
schema = "exact"

[[members]]
id = "auditor"
role = "auditor"
provider = "zai"
model = "glm-5"
reasoning = "high"
permissions = "read_only"
"#;
        let operation = exact_workflow_with(AUDIT_FLEET, None);
        let mut request = exact_task_request("auditor");
        let binding =
            bind_exact_fleet_task_request(&operation, exact_session(), &mut request).expect("bind");
        let receipt = route_admitted_exact_task(&operation, &binding, &mut request)
            .await
            .expect("routing");

        // The roster profile — and therefore the spawn metadata — carries the
        // posture role, because that is what picked the child's tool surface.
        let posture = operation
            .roster()
            .get("auditor")
            .expect("roster entry")
            .profile
            .role
            .name
            .clone();
        assert_eq!(posture, "scout");
        assert_eq!(receipt.posture_role.as_deref(), Some("scout"));

        // What the run displays is the member's role, not that posture.
        assert_eq!(
            displayed_resolved_role(Some(&receipt), Some(&posture), request.role.as_deref()),
            Some("auditor".to_string()),
            "the panel must not rename the operator's member to its posture"
        );

        // A non-Fleet task keeps the previous precedence untouched.
        assert_eq!(
            displayed_resolved_role(None, Some("builder"), Some("reviewer")),
            Some("builder".to_string())
        );
        assert_eq!(
            displayed_resolved_role(None, None, Some("reviewer")),
            Some("reviewer".to_string())
        );
    }

    /// The spawn boundary refuses an unbounded write claim. A task that will
    /// hit that refusal must be stopped while it is still free — before the
    /// Router is asked anything — or the operator pays for a routing decision
    /// about work that could never have started.
    #[test]
    fn a_predictably_invalid_write_scope_is_rejected_before_the_router_runs() {
        let router = crate::fleet::exact::StaticFleetRouter::new(r#"{"reasoning":"max"}"#);
        let operation = exact_workflow_with(EXACT_GLM_FLEET, Some(router.clone()));

        // Write-capable member, no declared scope: refused at the spawn
        // boundary, so refused here first.
        let mut unbounded = exact_task_request("builder");
        let err = bind_exact_fleet_task_request(&operation, exact_session(), &mut unbounded)
            .expect_err("an unbounded write claim never reaches a spawn");
        let message = format!("{err:?}");
        assert!(message.contains("write_roots"), "{message}");

        // Read-only member declaring a write scope is the mirror error.
        let mut scoped_read_only = exact_task_request("reviewer");
        scoped_read_only.exact_files = vec!["crates/tui/src/main.rs".to_string()];
        let err = bind_exact_fleet_task_request(&operation, exact_session(), &mut scoped_read_only)
            .expect_err("a read-only member may not claim files");
        assert!(format!("{err:?}").contains("read-only"), "{err:?}");

        // Neither spent a routing request.
        assert_eq!(
            router.call_count(),
            0,
            "validation that the spawn will fail must precede the router call"
        );

        // The same task with a declared scope binds cleanly.
        let mut bounded = exact_write_task_request("builder");
        bind_exact_fleet_task_request(&operation, exact_session(), &mut bounded)
            .expect("a bounded write claim is valid");
    }

    /// The parent posture wins over the saved Fleet, in the request the child
    /// actually receives.
    #[test]
    fn a_read_only_session_narrows_a_write_capable_exact_member() {
        let operation = exact_workflow(EXACT_GLM_FLEET);
        let session = codewhale_workflow::PermissionCeiling {
            write: false,
            network_tool: false,
            shell: codewhale_workflow::ShellCeiling::ReadOnly,
            delegation_depth: 0,
            tools: true,
        };

        let mut request = exact_task_request("builder");
        bind_exact_fleet_task_request(&operation, session, &mut request).expect("bind");

        assert_eq!(
            request.write_authority.as_deref(),
            Some("read_only"),
            "a saved read_write member must not write inside a read-only session"
        );
        assert_eq!(request.max_depth, Some(0));
    }

    /// A task that never reaches admission must never reach the Router.
    #[test]
    fn a_rejected_or_unadmitted_task_spends_no_router_call() {
        let router = crate::fleet::exact::StaticFleetRouter::new(r#"{"reasoning":"max"}"#);
        let operation = exact_workflow_with(EXACT_GLM_FLEET, Some(router.clone()));

        // Rejected by an override check, before the member is even resolved.
        let mut overridden = exact_task_request("builder");
        overridden.model = Some("glm-4".to_string());
        assert!(
            bind_exact_fleet_task_request(&operation, exact_session(), &mut overridden).is_err()
        );

        // Rejected by member resolution.
        let mut unknown = exact_task_request("wizard");
        assert!(bind_exact_fleet_task_request(&operation, exact_session(), &mut unknown).is_err());

        // Admitted-shaped but never routed: the capacity-blocked case.
        let mut queued = exact_write_task_request("builder");
        bind_exact_fleet_task_request(&operation, exact_session(), &mut queued).expect("bind");

        assert_eq!(
            router.call_count(),
            0,
            "binding must never contact the reasoning router"
        );
    }

    /// The routing decision must survive the run as a durable, visible receipt
    /// that carries no task content.
    #[tokio::test]
    async fn an_exact_fleet_launch_produces_a_durable_routing_receipt() {
        let operation = exact_workflow(EXACT_GLM_FLEET);
        let mut request = exact_write_task_request("builder");

        let binding =
            bind_exact_fleet_task_request(&operation, exact_session(), &mut request).expect("bind");
        let receipt = route_admitted_exact_task(&operation, &binding, &mut request)
            .await
            .expect("routing");

        assert_eq!(receipt.fleet, "workspace/glm-pair");
        assert_eq!(receipt.member_id, "implementer");
        assert_eq!(receipt.member_role, "builder");
        assert_eq!(receipt.provider, "zai");
        assert_eq!(receipt.model, "glm-5");
        assert_eq!(receipt.requested_reasoning, "auto");
        assert_eq!(receipt.effective_reasoning, "max");
        assert_eq!(receipt.selection_source, "fleet_router");
        let router = receipt.router.as_ref().expect("router identity");
        assert_eq!(router.service_kind, "reasoning_router");
        assert_eq!(router.qualified(), "workspace/luna-low");
        let call = router.call.as_ref().expect("call disclosure");
        assert_eq!(call.requested, "low");
        assert_eq!(call.effective, "low");

        // It rides the durable task_started event, and older consumers that
        // never saw this field still deserialize.
        let event = WorkflowUiEvent::new(WorkflowUiEventKind::TaskStarted(Box::new(
            WorkflowTaskStartedEvent {
                task_id: "t1".to_string(),
                label: None,
                role: request.role.clone(),
                profile: request.profile.clone(),
                model: None,
                strength: None,
                thinking: request.thinking.clone(),
                // The #4039 reasoning fields carry the same requested →
                // effective pair the receipt records, so the event and its
                // receipt cannot disagree about what the child ran at.
                requested_reasoning: Some(receipt.requested_reasoning.clone()),
                effective_reasoning: Some(receipt.effective_reasoning.clone()),
                resolved_role: None,
                resolved_profile: None,
                resolved_provider: "zai".to_string(),
                resolved_model: "glm-5".to_string(),
                route_source: "fleet".to_string(),
                child_route: None,
                worktree: false,
                workspace: None,
                git_branch: None,
                parent_task_id: None,
                depth: 0,
                workflow_run_id: None,
                workflow_phase_id: None,
                workflow_task_label: None,
                workflow_child_index: None,
                fleet_receipt: Some(receipt.clone()),
            },
        )));
        let payload = serde_json::to_value(&event).expect("serialize");
        let rendered = payload.to_string();
        for expected in [
            "fleet_receipt",
            "\"selection_source\":\"fleet_router\"",
            "\"provider_effective_reasoning\"",
            "\"requested_reasoning\":\"auto\"",
            "gpt-5.6-luna",
            "\"service_kind\":\"reasoning_router\"",
        ] {
            assert!(
                rendered.contains(expected),
                "{expected} missing: {rendered}"
            );
        }
        // No absolute paths, secrets, or task text on a durable event.
        for forbidden in ["/Users/", "/home/", ".toml", "api_key", "land the fix"] {
            assert!(!rendered.contains(forbidden), "{forbidden} in {rendered}");
        }

        // The visible one-line form names every side of the decision.
        let line = receipt.line();
        for expected in [
            "requested=auto",
            "effective=max",
            "source=fleet_router",
            "reasoning_router:workspace/luna-low",
            "router_call_requested=low",
        ] {
            assert!(line.contains(expected), "{expected} missing from {line}");
        }
    }

    #[test]
    fn exact_fleet_rejects_an_unknown_member() {
        let operation = exact_workflow(EXACT_GLM_FLEET);
        let mut request = exact_task_request("wizard");

        let err = bind_exact_fleet_task_request(&operation, exact_session(), &mut request)
            .expect_err("unknown member");
        let message = format!("{err:?}");
        assert!(message.contains("wizard"), "{message}");
        assert!(message.contains("implementer"), "{message}");

        // The Reasoning Router is never dispatchable as a worker.
        let mut router_request = exact_task_request("luna-low");
        assert!(
            bind_exact_fleet_task_request(&operation, exact_session(), &mut router_request)
                .is_err(),
            "the reasoning router must not be launchable as a worker"
        );
    }

    /// One saved Router profile, referenced by two different Fleets.
    #[tokio::test]
    async fn one_reasoning_router_profile_serves_two_fleets() {
        let first = exact_workflow(EXACT_GLM_FLEET);
        let second = {
            let text = EXACT_GLM_FLEET.replace("name = \"glm-pair\"", "name = \"glm-solo\"");
            let document =
                codewhale_workflow::FleetDocument::parse(&text).expect("second fleet parses");
            crate::fleet::exact::ExactFleetWorkflow::for_tests(
                &document,
                codewhale_workflow::QualifiedFleetId {
                    name: "glm-solo".to_string(),
                    origin: "workspace".to_string(),
                },
                Some(crate::fleet::exact::StaticFleetRouter::new(
                    r#"{"reasoning":"low"}"#,
                )),
            )
        };

        assert_eq!(
            first.snapshot().router(),
            second.snapshot().router(),
            "both fleets reference the identical captured router service"
        );
        assert_ne!(
            first.snapshot().fleet().qualified(),
            second.snapshot().fleet().qualified()
        );

        // Both actually route through it, and both receipts name it.
        for (operation, expected) in [(&first, "max"), (&second, "low")] {
            let mut request = exact_write_task_request("builder");
            let binding = bind_exact_fleet_task_request(operation, exact_session(), &mut request)
                .expect("bind");
            let receipt = route_admitted_exact_task(operation, &binding, &mut request)
                .await
                .expect("routing");
            assert_eq!(receipt.effective_reasoning, expected);
            assert_eq!(
                receipt.router.as_ref().expect("router").qualified(),
                "workspace/luna-low"
            );
        }
    }

    /// Editing the saved Fleet mid-run must not move the running Workflow's
    /// routes. The snapshot owns copies; only the next Workflow sees the edit.
    #[tokio::test]
    async fn editing_the_fleet_file_after_start_does_not_move_a_running_route() {
        let tmp = tempfile::tempdir().expect("tmp");
        let fleets = tmp.path().join("fleets");
        std::fs::create_dir_all(&fleets).expect("fleets dir");
        let path = fleets.join("glm-pair.toml");
        std::fs::write(&path, EXACT_GLM_FLEET).expect("write fleet");

        let roots = vec![codewhale_workflow::FleetSearchRoot::new(
            "workspace",
            tmp.path(),
        )];
        let (document, id) =
            codewhale_workflow::FleetDocument::load_by_name("glm-pair", &roots).expect("load");
        let operation = crate::fleet::exact::ExactFleetWorkflow::for_tests(
            &document,
            id,
            Some(crate::fleet::exact::StaticFleetRouter::new(
                r#"{"reasoning":"max"}"#,
            )),
        );
        let started_hash = operation.snapshot().content_hash().to_string();

        // The operator rewrites the saved Fleet mid-run.
        std::fs::write(
            &path,
            EXACT_GLM_FLEET
                .replace(
                    "model = \"glm-5\"\nreasoning = \"auto\"",
                    "model = \"glm-4\"\nreasoning = \"off\"",
                )
                .replace("permissions = \"read_write\"", "permissions = \"full\""),
        )
        .expect("rewrite fleet");

        let mut request = exact_write_task_request("builder");
        let binding = bind_exact_fleet_task_request(&operation, exact_session(), &mut request)
            .expect("bind after the edit");
        route_admitted_exact_task(&operation, &binding, &mut request)
            .await
            .expect("launch after the edit");

        let member = operation.roster().get("implementer").expect("roster");
        assert_eq!(
            member.profile.model.as_deref(),
            Some("glm-5"),
            "the in-flight snapshot must keep the model it started with"
        );
        assert_eq!(request.thinking.as_deref(), Some("max"));
        assert_eq!(
            request.write_authority.as_deref(),
            Some("workspace_write"),
            "the edit must not widen the running ceiling to `full`"
        );
        assert_eq!(operation.snapshot().content_hash(), started_hash);

        // A fresh Workflow does see the edit.
        let (reloaded, reloaded_id) =
            codewhale_workflow::FleetDocument::load_by_name("glm-pair", &roots).expect("reload");
        let next = crate::fleet::exact::ExactFleetWorkflow::for_tests(
            &reloaded,
            reloaded_id,
            Some(crate::fleet::exact::StaticFleetRouter::new(
                r#"{"reasoning":"max"}"#,
            )),
        );
        assert_eq!(
            next.roster()
                .get("implementer")
                .expect("roster")
                .profile
                .model
                .as_deref(),
            Some("glm-4")
        );
        assert_ne!(next.snapshot().content_hash(), started_hash);
    }

    #[test]
    fn named_fleet_rejects_unknown_workflow_role_before_spawn() {
        let fleet = FleetRoleMap::from_pairs([("scout", "scout")]).expect("fleet");
        let mut request = TaskRequest {
            description: "fix it".to_string(),
            subagent_type: None,
            role: Some("wizard".to_string()),
            profile: None,
            model: None,
            model_strength: None,
            thinking: None,
            cwd: None,
            worktree: false,
            write_authority: Some("read_only".to_string()),
            write_roots: Vec::new(),
            exact_files: Vec::new(),
            coordination_contracts: Vec::new(),
            dependencies: Vec::new(),
            acceptance: Vec::new(),
            allowed_tools: None,
            disallowed_tools: Vec::new(),
            max_depth: None,
            token_budget: None,
            max_steps: None,
            wall_time_secs: None,
            response_schema: None,
            label: None,
            phase: None,
        };

        let err = apply_named_fleet_to_task_request(Some(&fleet), &mut request)
            .expect_err("unknown role should fail");
        assert!(
            err.to_string().contains("unknown fleet role `wizard`"),
            "{err}"
        );
    }

    #[test]
    fn declarative_leaf_budget_reaches_task_runtime_options() {
        let source = r#"
workflow({
  "goal": "bound one child",
  "nodes": [{
    "agent": {
      "id": "bounded",
      "prompt": "Inspect bounded evidence.",
      "budget": { "max_tokens": 5000, "max_steps": 4, "timeout_secs": 90 }
    }
  }]
});
"#;

        let adapted = adapt_workflow_source(source, None).expect("lower bounded leaf");
        assert!(
            adapted.source.contains("tokenBudget: 5000"),
            "{}",
            adapted.source
        );
        assert!(adapted.source.contains("maxSteps: 4"), "{}", adapted.source);
        assert!(
            adapted.source.contains("wallTimeSecs: 90"),
            "{}",
            adapted.source
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn declarative_max_steps_zero_stops_before_provider_call() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls) = fake_chat_client("must not be called").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let tool = WorkflowTool::new(manager, runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": r#"
                    workflow({
                      "goal": "prove the child step cap reaches runtime",
                      "nodes": [{
                        "agent": {
                          "id": "zero-step",
                          "prompt": "Do not start a model turn.",
                          "budget": { "max_steps": 0, "timeout_secs": 90 }
                        }
                      }]
                    });
                    "#
                }),
                &ctx,
            )
            .await
            .expect("failed workflow still returns its terminal receipt");
        let payload: Value = serde_json::from_str(&result.content).expect("workflow JSON");

        assert_eq!(
            calls.load(Ordering::SeqCst),
            0,
            "provider must not be called"
        );
        assert_eq!(payload["status"], "failed", "{payload}");
        assert_eq!(
            payload["execution"]["leaf_results"][0]["status"], "failed",
            "{payload}"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn role_only_leaf_omits_type_and_resolves_through_named_fleet() {
        let _retry_guard = workflow_test_retry_guard();
        let _env_lock = crate::test_support::lock_test_env();
        let tmp = tempfile::tempdir().expect("tempdir");
        let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path());
        let fleet_dir = tmp.path().join("fleets");
        std::fs::create_dir_all(&fleet_dir).expect("fleet dir");
        std::fs::write(
            fleet_dir.join("role-only-test.toml"),
            r#"
name = "role-only-test"

[roles]
scout = "scout"
reviewer = "reviewer"
"#,
        )
        .expect("role-only fleet");
        let source = r#"
export default workflow({
  "goal": "resolve a role-only child",
  "nodes": [
    {
      "agent": {
        "id": "scout-source",
        "prompt": "Inspect the source without editing.",
        "role": "scout",
        "mode": "read_only"
      }
    }
  ]
});
"#;

        let adapted = adapt_workflow_source(source, None).expect("lower role-only workflow");
        assert!(adapted.source.contains("role: \"scout\""));
        assert!(
            !adapted.source.contains("type:"),
            "Fleet-addressed leaves must defer runtime type to the roster:\n{}",
            adapted.source
        );
        let non_role = adapt_workflow_source(
            r#"workflow({
              "goal": "default non-role child",
              "nodes": [{ "agent": { "id": "audit", "prompt": "Audit only." } }]
            });"#,
            None,
        )
        .expect("lower non-role workflow");
        assert!(
            non_role.source.contains("type: \"review\""),
            "non-role read-only leaves retain the review default:\n{}",
            non_role.source
        );
        let explicit_type_source = r#"
workflow({
  "goal": "preserve an authored role type",
  "nodes": [{
    "agent": {
      "id": "review-source",
      "prompt": "Review the source without editing.",
      "agent_type": "review",
      "role": "reviewer",
      "mode": "read_only"
    }
  }]
});
"#;
        let explicit_type = adapt_workflow_source(explicit_type_source, None)
            .expect("lower explicitly typed Fleet role");
        assert!(
            explicit_type.source.contains("type: \"review\""),
            "an authored non-General type must remain a validated override:\n{}",
            explicit_type.source
        );

        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls) = fake_chat_client("scout evidence").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);
        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": source,
                    "fleet": "role-only-test"
                }),
                &ctx,
            )
            .await
            .expect("role-only workflow should resolve through its named Fleet");
        let payload: Value = serde_json::from_str(&result.content).expect("workflow JSON");

        assert_eq!(payload["status"], "completed", "{payload}");
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        let started = payload["events"]
            .as_array()
            .expect("typed events")
            .iter()
            .find(|event| event["type"] == "task_started")
            .expect("task_started receipt");
        assert_eq!(started["role"], "scout");
        assert_eq!(started["profile"], "scout");
        assert_eq!(started["resolved_profile"], "scout");

        let explicit_result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": explicit_type_source,
                    "fleet": "role-only-test"
                }),
                &ctx,
            )
            .await
            .expect("matching explicit role type should remain valid");
        let explicit_payload: Value =
            serde_json::from_str(&explicit_result.content).expect("workflow JSON");
        assert_eq!(
            explicit_payload["status"], "completed",
            "{explicit_payload}"
        );
        assert_eq!(calls.load(Ordering::SeqCst), 2);

        let conflicting_result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": r#"workflow({
                      "goal": "reject a conflicting authored type",
                      "nodes": [{ "agent": {
                        "id": "bad-scout",
                        "prompt": "Review as a scout.",
                        "agent_type": "review",
                        "role": "scout",
                        "mode": "read_only"
                      } }]
                    });"#,
                    "fleet": "role-only-test"
                }),
                &ctx,
            )
            .await
            .expect("conflicting type returns a terminal workflow record");
        let conflicting_payload: Value =
            serde_json::from_str(&conflicting_result.content).expect("workflow JSON");
        assert_eq!(
            conflicting_payload["status"], "failed",
            "{conflicting_payload}"
        );
        assert!(
            conflicting_payload["error"]
                .as_str()
                .is_some_and(|error| error
                    .contains("Fleet role conflicts with the explicit legacy agent type")),
            "{conflicting_payload}"
        );
        assert_eq!(
            calls.load(Ordering::SeqCst),
            2,
            "conflicting explicit type must fail before the provider"
        );
    }

    #[test]
    fn parallel_write_children_default_to_worktree_isolation() {
        // #4120: write-capable parallel leaves get worktree: true by default.
        let source = r#"
export default workflow({
  "goal": "parallel write isolation default",
  "nodes": [
    {
      "branch": {
        "id": "implement",
        "parallel": true,
        "children": [
          {
            "agent": {
              "id": "left",
              "prompt": "Patch left lane",
              "agent_type": "implementer",
              "mode": "read_write",
              "file_scope": ["src/left.rs"]
            }
          },
          {
            "agent": {
              "id": "right",
              "prompt": "Patch right lane",
              "agent_type": "implementer",
              "mode": "read_write",
              "file_scope": ["src/right.rs"]
            }
          }
        ]
      }
    }
  ]
});
"#;
        let adapted = adapt_workflow_source(source, None).expect("lower parallel write workflow");
        let spec = adapted.spec.expect("declarative spec");
        let WorkflowNode::BranchSet(branch) = &spec.nodes[0] else {
            panic!("expected branch_set");
        };
        assert!(branch.parallel);
        for child in &branch.children {
            let WorkflowNode::Leaf(leaf) = child else {
                panic!("expected leaf");
            };
            assert!(leaf_is_write_capable(leaf));
            assert!(
                leaf_wants_worktree(leaf, true),
                "parallel write leaf {} should default to worktree",
                leaf.id
            );
            assert_eq!(leaf.isolation, IsolationMode::Auto);
        }
        assert!(
            adapted.source.contains("worktree: true"),
            "lowered JS should request worktree isolation:\n{}",
            adapted.source
        );
        // Both parallel children should carry the worktree flag.
        assert_eq!(
            adapted.source.matches("worktree: true").count(),
            2,
            "each parallel write child should get worktree: true:\n{}",
            adapted.source
        );
        assert_eq!(
            adapted
                .source
                .matches("writeAuthority: \"worktree_write\"")
                .count(),
            2,
            "each isolated writer should carry enforced worktree authority:\n{}",
            adapted.source
        );
        assert!(adapted.source.contains("writeRoots: [\"src/left.rs\"]"));
        assert!(adapted.source.contains("writeRoots: [\"src/right.rs\"]"));
    }

    #[test]
    fn parallel_write_same_worktree_requires_explicit_shared_isolation() {
        // #4120: isolation: shared is the approved same-worktree override.
        let source = r#"
export default workflow({
  "goal": "parallel write same-worktree override",
  "nodes": [
    {
      "branch": {
        "id": "implement",
        "parallel": true,
        "children": [
          {
            "agent": {
              "id": "shared-writer",
              "prompt": "Patch in the parent checkout",
              "agent_type": "implementer",
              "mode": "read_write",
              "isolation": "shared",
              "file_scope": ["src/shared.rs"]
            }
          },
          {
            "agent": {
              "id": "isolated-writer",
              "prompt": "Patch in a worktree",
              "agent_type": "implementer",
              "mode": "read_write",
              "isolation": "worktree",
              "file_scope": ["src/isolated.rs"]
            }
          }
        ]
      }
    }
  ]
});
"#;
        let adapted =
            adapt_workflow_source(source, None).expect("lower same-worktree override workflow");
        let spec = adapted.spec.expect("declarative spec");
        let WorkflowNode::BranchSet(branch) = &spec.nodes[0] else {
            panic!("expected branch_set");
        };
        let leaves: Vec<&LeafSpec> = branch
            .children
            .iter()
            .map(|child| match child {
                WorkflowNode::Leaf(leaf) => leaf,
                _ => panic!("expected leaf"),
            })
            .collect();
        assert_eq!(leaves[0].isolation, IsolationMode::Shared);
        assert!(
            !leaf_wants_worktree(leaves[0], true),
            "explicit shared should keep same-worktree"
        );
        assert_eq!(leaves[1].isolation, IsolationMode::Worktree);
        assert!(leaf_wants_worktree(leaves[1], true));

        // Only the explicit worktree child should emit worktree: true.
        assert_eq!(
            adapted.source.matches("worktree: true").count(),
            1,
            "same-worktree override must not force worktree on shared leaf:\n{}",
            adapted.source
        );
        assert!(
            adapted.source.contains("shared-writer") && adapted.source.contains("isolated-writer"),
            "both children should still be lowered:\n{}",
            adapted.source
        );
        assert!(
            adapted
                .source
                .contains("writeAuthority: \"workspace_write\"")
        );
        assert!(
            adapted
                .source
                .contains("writeAuthority: \"worktree_write\"")
        );
    }

    #[test]
    fn parallel_read_only_children_do_not_default_to_worktree() {
        let source = r#"
export default workflow({
  "goal": "parallel read-only stays shared",
  "nodes": [
    {
      "branch": {
        "id": "audit",
        "parallel": true,
        "children": [
          {
            "agent": {
              "id": "review-a",
              "prompt": "Review A",
              "agent_type": "review",
              "mode": "read_only"
            }
          },
          {
            "agent": {
              "id": "review-b",
              "prompt": "Review B",
              "agent_type": "verifier",
              "mode": "read_only"
            }
          }
        ]
      }
    }
  ]
});
"#;
        let adapted = adapt_workflow_source(source, None).expect("lower parallel read-only");
        assert!(
            !adapted.source.contains("worktree: true"),
            "read-only parallel children should not get worktree isolation:\n{}",
            adapted.source
        );
        assert_eq!(
            adapted
                .source
                .matches("writeAuthority: \"read_only\"")
                .count(),
            2,
            "read-only mode must reach the task authority contract:\n{}",
            adapted.source
        );
    }

    #[test]
    fn sequential_write_children_do_not_default_to_worktree() {
        let source = r#"
export default workflow({
  "goal": "sequential write stays shared by default",
  "nodes": [
    {
      "sequence": {
        "id": "implement",
        "children": [
          {
            "agent": {
              "id": "writer",
              "prompt": "Patch sequentially",
              "agent_type": "implementer",
              "mode": "read_write",
              "file_scope": ["src/main.rs"]
            }
          }
        ]
      }
    }
  ]
});
"#;
        let adapted = adapt_workflow_source(source, None).expect("lower sequential write");
        assert!(
            !adapted.source.contains("worktree: true"),
            "sequential writes should not default to worktree:\n{}",
            adapted.source
        );
        assert!(
            adapted
                .source
                .contains("writeAuthority: \"workspace_write\"")
        );
        assert!(adapted.source.contains("writeRoots: [\"src/main.rs\"]"));
    }

    #[test]
    fn write_scope_suffix_globs_lower_to_enforceable_roots() {
        let source = r#"workflow({
          "goal": "bounded auth patch",
          "nodes": [{ "agent": {
            "id": "writer",
            "prompt": "Patch auth",
            "agent_type": "implementer",
            "mode": "read_write",
            "file_scope": ["./src/auth/**"]
          }}]
        });"#;
        let adapted = adapt_workflow_source(source, None).expect("lower trailing glob scope");
        assert!(
            adapted.source.contains("writeRoots: [\"src/auth\"]"),
            "runtime claim must contain src/auth/login.rs:\n{}",
            adapted.source
        );

        let unsupported = r#"workflow({
          "goal": "reject ambiguous glob",
          "nodes": [{ "agent": {
            "id": "writer",
            "prompt": "Patch auth",
            "agent_type": "implementer",
            "mode": "read_write",
            "file_scope": ["src/*/auth"]
          }}]
        });"#;
        let error = match adapt_workflow_source(unsupported, None) {
            Ok(_) => panic!("internal globs cannot become literal runtime roots"),
            Err(error) => error.to_string(),
        };
        assert!(error.contains("unsupported file_scope"), "{error}");
    }

    #[test]
    fn write_leaves_require_scope_and_reduce_stays_read_only() {
        let unscoped_writer = r#"workflow({
          "goal": "reject an unbounded writer",
          "nodes": [{ "agent": {
            "id": "writer",
            "prompt": "Patch it",
            "agent_type": "implementer",
            "mode": "read_write"
          }}]
        });"#;
        let error = match adapt_workflow_source(unscoped_writer, None) {
            Ok(_) => panic!("write-capable leaves must declare file_scope"),
            Err(error) => error.to_string(),
        };
        assert!(error.contains("declares no file_scope"), "{error}");

        let reduce = r#"workflow({
          "goal": "reduce read-only evidence",
          "nodes": [{ "reduce": {
            "id": "summary",
            "inputs": [],
            "prompt": "Summarize the evidence"
          }}]
        });"#;
        let adapted = adapt_workflow_source(reduce, None).expect("lower reduce");
        assert!(adapted.source.contains("type: \"plan\""));
        assert!(adapted.source.contains("writeAuthority: \"read_only\""));
    }

    #[test]
    fn inline_script_and_source_path_are_mutually_exclusive() {
        let ctx = ToolContext::new(".");
        let err = workflow_source(
            &json!({
                "script": "return 1;",
                "source_path": "workflow.js"
            }),
            &ctx,
        )
        .unwrap_err();
        assert!(
            err.to_string()
                .contains("exactly one of script, source_path, or plan"),
            "{err}"
        );
    }

    #[test]
    fn structured_plan_lowers_to_parallel_not_promise_all() {
        // #4124: planner plan → JS with parallel() partial-success semantics.
        let ctx = ToolContext::new(".");
        let source = workflow_source(
            &json!({
                "plan": {
                    "goal": "audit two independent scopes",
                    "risk": "read_only",
                    "max_children": 8,
                    "token_budget": 120000,
                    "phases": [{
                        "id": "scout",
                        "title": "Scout",
                        "children": [
                            {
                                "id": "left",
                                "label": "left-lane",
                                "prompt": "Inspect crates/left",
                                "type": "explore"
                            },
                            {
                                "id": "right",
                                "prompt": "Inspect crates/right",
                                "type": "explore"
                            }
                        ]
                    }]
                }
            }),
            &ctx,
        )
        .expect("structured plan should lower");

        assert!(
            source.source.contains("await parallel(["),
            "lowered JS must use parallel():\n{}",
            source.source
        );
        assert!(
            !source.source.contains("Promise.all"),
            "lowered JS must not use raw Promise.all:\n{}",
            source.source
        );
        assert!(
            source.source.contains("() => task("),
            "parallel slots should be thunks:\n{}",
            source.source
        );
        let spec = source.spec.expect("plan should produce WorkflowSpec");
        assert_eq!(spec.goal, "audit two independent scopes");
        assert_eq!(spec.budget.max_tokens, Some(120000));
        assert_eq!(spec.nodes.len(), 1);
        let WorkflowNode::BranchSet(branch) = &spec.nodes[0] else {
            panic!("expected parallel branch for multi-child phase");
        };
        assert!(branch.parallel);
        assert_eq!(branch.children.len(), 2);
    }

    #[test]
    fn structured_plan_validation_errors_are_typed() {
        let ctx = ToolContext::new(".");
        let missing_goal = workflow_source(
            &json!({
                "plan": {
                    "goal": "   ",
                    "children": [{ "prompt": "do work" }]
                }
            }),
            &ctx,
        )
        .unwrap_err();
        assert!(missing_goal.to_string().contains("goal"), "{missing_goal}");

        let over_limit = workflow_source(
            &json!({
                "plan": {
                    "goal": "too many children",
                    "max_children": 1,
                    "children": [
                        { "id": "a", "prompt": "one" },
                        { "id": "b", "prompt": "two" }
                    ]
                }
            }),
            &ctx,
        )
        .unwrap_err();
        assert!(
            over_limit.to_string().contains("max_children"),
            "{over_limit}"
        );

        let bad_type = workflow_source(
            &json!({
                "plan": {
                    "goal": "bad type",
                    "children": [{ "prompt": "x", "type": "wizard" }]
                }
            }),
            &ctx,
        )
        .unwrap_err();
        assert!(
            bad_type
                .to_string()
                .contains("Invalid sub-agent type 'wizard'"),
            "{bad_type}"
        );

        let exclusive = workflow_source(
            &json!({
                "script": "return 1;",
                "plan": { "goal": "x", "children": [{ "prompt": "y" }] }
            }),
            &ctx,
        )
        .unwrap_err();
        assert!(
            exclusive
                .to_string()
                .contains("exactly one of script, source_path, or plan"),
            "{exclusive}"
        );
    }

    #[test]
    fn plan_child_type_shares_the_agent_tool_option_vocabulary() {
        // #5035: type values accepted by direct Agent dispatch must not be
        // rejected by Workflow plan authoring; aliases normalize onto the IR.
        for (alias, expected) in [
            ("worker", AgentType::General),
            ("delegate", AgentType::General),
            ("scout", AgentType::Explore),
            ("Explorer", AgentType::Explore),
            ("planner", AgentType::Plan),
            ("awaiter", AgentType::Plan),
            ("reviewer", AgentType::Review),
            ("consultant", AgentType::Review),
            ("oracle", AgentType::Review),
            ("advisor", AgentType::Review),
            ("builder", AgentType::Implementer),
            ("verifier", AgentType::Verifier),
        ] {
            assert_eq!(
                parse_plan_agent_type(Some(alias))
                    .unwrap_or_else(|err| panic!("{alias} rejected: {err}")),
                expected,
                "{alias}"
            );
        }

        // Typos fail with the Agent tool's error contract and the full set.
        let typo = parse_plan_agent_type(Some("wizard"))
            .unwrap_err()
            .to_string();
        assert!(typo.contains("Invalid sub-agent type 'wizard'"), "{typo}");
        assert!(
            typo.contains("worker, scout, planner, reviewer, builder"),
            "{typo}"
        );
        assert!(
            typo.contains("consultant/oracle/advisor"),
            "accepted advisory aliases must remain visible in the guidance: {typo}"
        );

        // `custom` is Agent-only; the rejection says why and what to use.
        let custom = parse_plan_agent_type(Some("custom"))
            .unwrap_err()
            .to_string();
        assert!(
            custom.contains("Invalid sub-agent type 'custom'"),
            "{custom}"
        );
        assert!(custom.contains("allowed_tools"), "{custom}");
    }

    #[test]
    fn declarative_parallel_branch_uses_parallel_helper() {
        let source = r#"
export default workflow({
  "goal": "partial success fan-out",
  "nodes": [
    {
      "branch": {
        "id": "fan",
        "parallel": true,
        "children": [
          { "agent": { "id": "a", "prompt": "A", "agent_type": "explore", "mode": "read_only" } },
          { "agent": { "id": "b", "prompt": "B", "agent_type": "explore", "mode": "read_only" } }
        ]
      }
    }
  ]
});
"#;
        let adapted = adapt_workflow_source(source, None).expect("lower declarative");
        assert!(
            adapted.source.contains("await parallel(["),
            "declarative parallel must lower via parallel():\n{}",
            adapted.source
        );
        assert!(
            !adapted.source.contains("Promise.all"),
            "must not emit raw Promise.all:\n{}",
            adapted.source
        );
    }

    #[test]
    fn source_path_must_stay_inside_workspace_without_trust_mode() {
        let workspace = tempfile::tempdir().expect("workspace tempdir");
        let outside = tempfile::tempdir().expect("outside tempdir");
        let outside_path = outside.path().join("outside.workflow.js");
        std::fs::write(&outside_path, "return 1;").expect("outside workflow source");
        let ctx = ToolContext::new(workspace.path().to_path_buf());

        let err = workflow_source(
            &json!({
                "source_path": outside_path
            }),
            &ctx,
        )
        .expect_err("outside source_path should be denied");

        assert!(
            err.to_string().contains("must stay inside the workspace"),
            "{err}"
        );
    }

    #[test]
    fn subagent_tool_surface_registers_workflow_and_agent() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let runtime = SubAgentRuntime::new(
            stub_client(),
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let registry = ToolRegistryBuilder::new()
            .with_subagent_tools(manager, runtime)
            .build(ctx);

        assert!(registry.contains("workflow"));
        assert!(registry.contains("agent"));
        assert!(registry.contains("agents/list"));
        assert!(registry.contains("agents/message"));
        assert!(registry.contains("agents/followup"));
        assert!(registry.contains("agents/interrupt"));
        assert!(registry.contains("agents/wait"));
        assert!(
            registry
                .to_api_tools()
                .iter()
                .any(|tool| tool.name == "workflow")
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn workflow_run_dispatches_task_through_subagent_manager() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls) = fake_chat_client("child done").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let tool = WorkflowTool::new(manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": "phase('dispatch'); log('starting child'); const out = await task({ description: 'say done', allowedTools: [], label: 'inspect-child', model: 'deepseek-v4-flash', modelStrength: 'same', thinking: 'low' }); return { out };"
                }),
                &ctx,
            )
            .await
            .expect("workflow run should complete");
        let payload: Value = serde_json::from_str(&result.content).expect("json result");

        assert_eq!(payload["status"], "completed", "{payload}");
        assert_eq!(payload["result"]["out"], "child done");
        assert_eq!(payload["child_ids"].as_array().unwrap().len(), 1);
        assert_eq!(calls.load(Ordering::SeqCst), 1);

        let child_id = payload["child_ids"][0].as_str().unwrap();
        let events = payload["events"].as_array().expect("events array");
        assert!(
            events
                .iter()
                .any(|event| event["type"] == "phase_started" && event["title"] == "dispatch"),
            "{events:#?}"
        );
        assert!(
            events
                .iter()
                .any(|event| event["type"] == "log" && event["message"] == "starting child"),
            "{events:#?}"
        );
        assert!(
            events.iter().any(|event| event["type"] == "budget_updated"),
            "{events:#?}"
        );
        let task_started = events
            .iter()
            .find(|event| event["type"] == "task_started")
            .expect("task_started event");
        assert_eq!(task_started["task_id"], child_id);
        assert_eq!(task_started["label"], "inspect-child");
        assert!(task_started["profile"].is_null());
        assert_eq!(task_started["model"], "deepseek-v4-flash");
        assert_eq!(task_started["strength"], "same");
        assert_eq!(task_started["thinking"], "low");
        assert_eq!(task_started["requested_reasoning"], "low");
        assert!(
            task_started["effective_reasoning"]
                .as_str()
                .is_some_and(|value| !value.is_empty()),
            "{task_started}"
        );
        assert_eq!(task_started["resolved_provider"], "deepseek");
        assert_eq!(task_started["resolved_model"], "deepseek-v4-flash");
        assert_eq!(task_started["route_source"], "task.model");
        assert_eq!(task_started["worktree"], false);
        assert!(task_started["parent_task_id"].is_null());
        assert_eq!(task_started["depth"], 1);
        // #4119: workflow identity on spawn / task_started metadata.
        assert_eq!(
            task_started["workflow_run_id"].as_str(),
            payload["run_id"].as_str()
        );
        assert_eq!(task_started["workflow_phase_id"], "dispatch");
        assert_eq!(task_started["workflow_task_label"], "inspect-child");
        assert_eq!(task_started["workflow_child_index"], 0);
        assert!(
            events.iter().any(|event| event["type"] == "task_completed"
                && event["task_id"] == child_id
                && event["status"] == "succeeded"),
            "{events:#?}"
        );
        let child = manager
            .read()
            .await
            .get_result(child_id)
            .expect("child result");
        assert_eq!(child.status, SubAgentStatus::Completed);
        assert_eq!(child.result.as_deref(), Some("child done"));

        // Full receipt chain: the spawn-minted event survives the JSONL
        // journal reload, hydrates the live projection, and round-trips into
        // history without following a later route or inventing missing usage.
        let reloaded = WorkflowWorkspaceState::open(tmp.path());
        let persisted = reloaded
            .runs
            .lock()
            .expect("reloaded workflow runs")
            .get(payload["run_id"].as_str().expect("run id"))
            .cloned()
            .expect("persisted run");
        let persisted_json = serde_json::to_value(&persisted).expect("persisted run JSON");
        let persisted_started = persisted_json["events"]
            .as_array()
            .and_then(|events| events.iter().find(|event| event["type"] == "task_started"))
            .expect("persisted task_started receipt");
        assert_eq!(persisted_started["requested_reasoning"], "low");
        assert_eq!(
            persisted_started["effective_reasoning"],
            task_started["effective_reasoning"]
        );
        assert_eq!(persisted_started["resolved_provider"], "deepseek");
        assert_eq!(persisted_started["resolved_model"], "deepseek-v4-flash");
        assert_eq!(persisted_started["route_source"], "task.model");

        let mut panel =
            crate::tui::widgets::workflow_panel::WorkflowPanel::from_run_json(&persisted_json)
                .expect("journal should hydrate workflow panel");
        let original_receipt = panel
            .phases
            .iter()
            .flat_map(|phase| phase.rows.iter())
            .find(|row| row.task_id == child_id)
            .map(crate::tui::widgets::workflow_panel::row_receipt_text)
            .expect("spawned child receipt");
        assert!(original_receipt.contains("deepseek/deepseek-v4-flash"));
        assert!(original_receipt.contains("reasoning low→"));
        assert!(original_receipt.contains("via task.model"));

        panel.apply_json_event(&json!({
            "type": "task_started",
            "at_ms": 9_000,
            "task_id": "later-route",
            "label": "later-route",
            "resolved_role": "consultant",
            "resolved_provider": "moonshot",
            "resolved_model": "kimi-k3",
            "requested_reasoning": "auto",
            "effective_reasoning": "medium",
            "route_source": "agent_profile.model",
            "worktree": false,
        }));
        panel.apply_json_event(&json!({
            "type": "task_completed",
            "at_ms": 9_100,
            "task_id": "later-route",
            "status": "succeeded"
        }));
        let unchanged = panel
            .phases
            .iter()
            .flat_map(|phase| phase.rows.iter())
            .find(|row| row.task_id == child_id)
            .map(crate::tui::widgets::workflow_panel::row_receipt_text)
            .expect("original child after later route");
        assert_eq!(unchanged, original_receipt);

        let history =
            crate::tui::widgets::workflow_panel::WorkflowPanel::from_run_json(&panel.to_run_json())
                .expect("history receipt round trip");
        let later_receipt = history
            .phases
            .iter()
            .flat_map(|phase| phase.rows.iter())
            .find(|row| row.task_id == "later-route")
            .map(crate::tui::widgets::workflow_panel::row_receipt_text)
            .expect("later route history receipt");
        assert!(later_receipt.contains("moonshot/kimi-k3"));
        assert!(later_receipt.contains("reasoning auto→medium"));
        assert!(later_receipt.contains("tokens unknown"));
        assert!(!later_receipt.contains("tokens 0"));
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn named_fleet_run_emits_role_resolved_receipt_and_rejects_unknown_before_provider() {
        let _retry_guard = workflow_test_retry_guard();
        let _env_lock = crate::test_support::lock_test_env();
        let tmp = tempfile::tempdir().expect("tempdir");
        let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path());
        std::fs::create_dir_all(tmp.path().join("fleets")).expect("fleets dir");
        std::fs::write(
            tmp.path().join("fleets/offline.toml"),
            r#"
name = "offline"
[roles]
reviewer = "reviewer"
"#,
        )
        .expect("named fleet fixture");

        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls) = fake_chat_client("role-resolved child").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let tool = WorkflowTool::new(manager, runtime);

        let completed = tool
            .execute(
                json!({
                    "action": "run",
                    "fleet": "offline",
                    "script": "return await task({ description: 'review it', type: 'review', role: 'reviewer', label: 'offline-review' });"
                }),
                &ctx,
            )
            .await
            .expect("named fleet workflow");
        let payload: Value = serde_json::from_str(&completed.content).expect("workflow JSON");
        assert_eq!(payload["status"], "completed", "{payload}");
        assert_eq!(payload["result"], "role-resolved child");
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        let started = payload["events"]
            .as_array()
            .and_then(|events| events.iter().find(|event| event["type"] == "task_started"))
            .expect("task_started receipt");
        assert_eq!(started["role"], "reviewer");
        assert_eq!(started["profile"], "reviewer");
        assert_eq!(started["resolved_role"], "reviewer");
        assert_eq!(started["resolved_profile"], "reviewer");
        assert_eq!(started["resolved_provider"], "deepseek");
        assert_eq!(started["resolved_model"], "deepseek-v4-flash");
        assert_eq!(started["route_source"], "run.model");
        assert!(
            payload["events"]
                .as_array()
                .is_some_and(|events| events.iter().any(|event| event["type"] == "task_completed"))
        );

        let rejected = tool
            .execute(
                json!({
                    "action": "run",
                    "fleet": "offline",
                    "script": "return await task({ description: 'must not launch', type: 'review', role: 'wizard' });"
                }),
                &ctx,
            )
            .await
            .expect("rejected workflow still returns its terminal record");
        let rejected: Value = serde_json::from_str(&rejected.content).expect("rejected JSON");
        assert_eq!(rejected["status"], "failed", "{rejected}");
        assert!(
            rejected["error"]
                .as_str()
                .is_some_and(|error| error.contains("unknown fleet role `wizard`")),
            "{rejected}"
        );
        assert_eq!(
            calls.load(Ordering::SeqCst),
            1,
            "unknown role must fail before a second provider call"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn workflow_spawn_records_carry_child_index_and_phase_metadata() {
        // #4119: sequential children get monotonic workflow_child_index and
        // inherit the active phase when task options omit `phase`.
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 4);
        let (client, calls) = fake_chat_client("ok").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let tool = WorkflowTool::new(manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": "phase('alpha'); await task({ description: 'first', type: 'explore', allowedTools: [], label: 'one' }); phase('beta'); await task({ description: 'second', type: 'explore', allowedTools: [], label: 'two', phase: 'beta-explicit' }); return { ok: true };"
                }),
                &ctx,
            )
            .await
            .expect("workflow run should complete");
        let payload: Value = serde_json::from_str(&result.content).expect("json result");
        assert_eq!(payload["status"], "completed", "{payload}");
        assert_eq!(payload["child_ids"].as_array().unwrap().len(), 2);
        assert_eq!(calls.load(Ordering::SeqCst), 2);

        let mut started: Vec<&Value> = payload["events"]
            .as_array()
            .expect("events")
            .iter()
            .filter(|event| event["type"] == "task_started")
            .collect();
        started.sort_by_key(|event| event["workflow_child_index"].as_u64().unwrap_or(u64::MAX));
        assert_eq!(started.len(), 2, "{started:#?}");

        assert_eq!(started[0]["workflow_run_id"], payload["run_id"]);
        assert_eq!(started[0]["workflow_phase_id"], "alpha");
        assert_eq!(started[0]["workflow_task_label"], "one");
        assert_eq!(started[0]["workflow_child_index"], 0);
        assert_eq!(started[0]["label"], "one");

        assert_eq!(started[1]["workflow_run_id"], payload["run_id"]);
        // Explicit task phase wins over the driver's current phase.
        assert_eq!(started[1]["workflow_phase_id"], "beta-explicit");
        assert_eq!(started[1]["workflow_task_label"], "two");
        assert_eq!(started[1]["workflow_child_index"], 1);
        assert_eq!(started[1]["label"], "two");
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn declarative_parallel_spawn_failure_nulls_slot_and_continues() {
        // #4124: parallel() is all-settled — a rejected spawn becomes a null slot
        // (with a breadcrumb) instead of aborting the rest of the script the way
        // raw Promise.all would. Downstream reduce still runs on partial results.
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls) = fake_chat_client("reduce-with-partial").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": r#"export default workflow({
                        "goal": "partial success fan-out",
                        "nodes": [
                            {
                                "branch": {
                                    "id": "parallel",
                                    "parallel": true,
                                    "children": [
                                        {
                                            "agent": {
                                                "id": "bad-profile",
                                                "prompt": "This child should be rejected before model execution.",
                                                "profile": "missing-profile"
                                            }
                                        }
                                    ]
                                }
                            },
                            {
                                "reduce": {
                                    "id": "summary",
                                    "inputs": ["bad-profile"],
                                    "prompt": "Summarize whatever survived the parallel fan-out."
                                }
                            }
                        ]
                    });"#
                }),
                &ctx,
            )
            .await
            .expect("partial-success workflow still returns run record");
        let payload: Value = serde_json::from_str(&result.content).expect("json result");

        // Receipt honesty (morning-report issue #2): the run keeps its output
        // and the reduce still runs, but a dropped slot means the status is
        // degraded, never a plain completed.
        assert_eq!(payload["status"], "degraded", "{payload}");
        let degradation = payload["error"].as_str().expect("degradation surfaced");
        assert!(
            degradation.contains("result may be partial"),
            "{degradation}"
        );
        assert!(
            payload["result"]["bad-profile"].is_null(),
            "failed parallel slot should be null: {}",
            payload["result"]
        );
        assert_eq!(payload["result"]["summary"], "reduce-with-partial");
        let progress = payload["progress"]
            .as_array()
            .expect("progress array")
            .iter()
            .filter_map(|v| v.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(
            progress.contains("missing-profile") && progress.contains("dropped a failed slot"),
            "breadcrumb should surface the spawn rejection:\n{progress}"
        );
        // #5035: partial success is explicit — the rejected slot lands in the
        // run record as a structured dispatch failure, not only a log line.
        let failures = payload["dispatch_failures"]
            .as_array()
            .expect("dispatch failures surfaced on the run record");
        assert_eq!(failures.len(), 1, "{payload}");
        assert!(
            failures[0]["message"]
                .as_str()
                .unwrap_or_default()
                .contains("missing-profile"),
            "{failures:?}"
        );
        assert_eq!(
            result.metadata.as_ref().expect("metadata")["dispatch_failure_count"],
            1
        );
        assert!(
            calls.load(Ordering::SeqCst) >= 1,
            "reduce should still run after a null parallel slot"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn parallel_slots_rejected_by_the_vm_cannot_report_plain_success() {
        // Morning-report issue #2: options that fail VM validation throw
        // before the driver ever sees a dispatch, and parallel() collapses
        // those throws into null slots. The run must classify against the
        // slot ledger instead of reporting completed with [null, ...].
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls) = fake_chat_client("unused").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": "return await parallel([() => task({ description: 'bad a', type: 'explore', allowedTools: [], cwd: '/absolute/a' }), () => task({ description: 'bad b', type: 'explore', allowedTools: [], cwd: '/absolute/b' })]);"
                }),
                &ctx,
            )
            .await
            .expect("vm-rejected fan-out still returns the run record");
        let payload: Value = serde_json::from_str(&result.content).expect("json result");

        assert_eq!(payload["status"], "failed", "{payload}");
        let error = payload["error"].as_str().expect("error surfaced");
        assert!(
            error.contains("all 2 task dispatch(es) were rejected"),
            "error should name the total rejection: {error}"
        );
        let failures = payload["dispatch_failures"]
            .as_array()
            .expect("collected dispatch failures");
        assert_eq!(failures.len(), 2, "{payload}");
        for failure in failures {
            let message = failure["message"].as_str().expect("failure message");
            assert!(message.contains("bounded repo-relative paths"), "{message}");
        }
        assert_eq!(
            calls.load(Ordering::SeqCst),
            0,
            "no provider call should be spent on vm-rejected slots"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn partially_dropped_parallel_slots_degrade_the_run() {
        // One slot completes, one is rejected before dispatch: the run keeps
        // its output but must report degraded, not completed.
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls) = fake_chat_client("child done").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": "return await parallel([() => task({ description: 'say done', type: 'explore', allowedTools: [] }), () => task({ description: 'bad slot', type: 'explore', allowedTools: [], cwd: '/absolute/path' })]);"
                }),
                &ctx,
            )
            .await
            .expect("partially dropped fan-out still returns the run record");
        let payload: Value = serde_json::from_str(&result.content).expect("json result");

        assert_eq!(payload["status"], "degraded", "{payload}");
        let error = payload["error"].as_str().expect("degradation surfaced");
        assert!(
            error.contains("1 dispatch(es) were rejected"),
            "error should count the dropped slot: {error}"
        );
        assert!(
            error.contains("result may be partial"),
            "error should warn the result is partial: {error}"
        );
        let results = payload["result"].as_array().expect("run kept its output");
        assert_eq!(results.len(), 2, "{payload}");
        assert!(results[1].is_null(), "the rejected slot stays null");
        assert!(
            calls.load(Ordering::SeqCst) >= 1,
            "the healthy slot still ran"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn parallel_fan_out_with_every_dispatch_rejected_fails_the_run() {
        // #5035: when every parallel slot is rejected before dispatch, the run
        // must not report overall success that ran nothing — the collected
        // per-slot failures surface and the run fails loudly.
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls) = fake_chat_client("unused").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": r#"export default workflow({
                        "goal": "total dispatch failure fan-out",
                        "nodes": [
                            {
                                "branch": {
                                    "id": "parallel",
                                    "parallel": true,
                                    "children": [
                                        {
                                            "agent": {
                                                "id": "bad-one",
                                                "prompt": "Rejected before model execution.",
                                                "profile": "missing-profile"
                                            }
                                        },
                                        {
                                            "agent": {
                                                "id": "bad-two",
                                                "prompt": "Also rejected before model execution.",
                                                "profile": "missing-profile"
                                            }
                                        }
                                    ]
                                }
                            }
                        ]
                    });"#
                }),
                &ctx,
            )
            .await
            .expect("total dispatch failure still returns the run record");
        let payload: Value = serde_json::from_str(&result.content).expect("json result");

        assert_eq!(payload["status"], "failed", "{payload}");
        let error = payload["error"].as_str().expect("error surfaced");
        assert!(
            error.contains("all 2 task dispatch(es) were rejected"),
            "error should name the total dispatch failure: {error}"
        );
        let failures = payload["dispatch_failures"]
            .as_array()
            .expect("collected dispatch failures");
        assert_eq!(failures.len(), 2, "{payload}");
        for failure in failures {
            let message = failure["message"].as_str().expect("failure message");
            assert!(message.contains("missing-profile"), "{message}");
        }
        assert_eq!(payload["child_ids"].as_array().unwrap().len(), 0);
        assert_eq!(
            result.metadata.as_ref().expect("metadata")["dispatch_failure_count"],
            2
        );
        assert_eq!(
            calls.load(Ordering::SeqCst),
            0,
            "no provider call should be spent on an all-rejected fan-out"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn declarative_dependency_results_are_forwarded_to_downstream_prompt() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls, bodies) = fake_chat_client_capturing("upstream-output").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": r#"export default workflow({
                        "goal": "dependency forwarding",
                        "nodes": [
                            {
                                "agent": {
                                    "id": "first",
                                    "prompt": "Produce the upstream finding.",
                                    "agent_type": "review"
                                }
                            },
                            {
                                "agent": {
                                    "id": "second",
                                    "prompt": "Use the upstream finding.",
                                    "agent_type": "review",
                                    "depends_on_results": ["first"]
                                }
                            }
                        ]
                    });"#
                }),
                &ctx,
            )
            .await
            .expect("dependency workflow should complete");
        let payload: Value = serde_json::from_str(&result.content).expect("json result");

        assert_eq!(payload["status"], "completed", "{payload}");
        assert_eq!(payload["execution"]["status"], "succeeded");
        assert_eq!(
            payload["execution"]["leaf_results"][0]["output"],
            "upstream-output"
        );
        assert_eq!(
            payload["execution"]["leaf_results"][1]["output"],
            "upstream-output"
        );
        assert_eq!(calls.load(Ordering::SeqCst), 2);
        let bodies = bodies.lock().expect("captured bodies");
        let second_body = bodies.get(1).expect("second provider call").to_string();
        assert!(second_body.contains("--- first ---"), "{second_body}");
        assert!(second_body.contains("upstream-output"), "{second_body}");
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn workflow_runtime_gates_promote_handoff_and_block_downstream_role() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let runtime = SubAgentRuntime::new(
            stub_client(),
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let state = WorkflowWorkspaceState::open(tmp.path());
        let run_id = "workflow_gate".to_string();
        let gates = vec![GateSpec {
            id: "scout-findings".to_string(),
            role: "scout".to_string(),
            on: GateOn::RoleComplete,
            gate: GateKind::Approve,
            on_fail: codewhale_workflow::GateOnFail::Block,
            blocks_role: Some("implementer".to_string()),
            max_retries: 0,
            artifact_kind: Some("findings".to_string()),
            require_explicit_verdict: false,
        }];
        let spec = WorkflowSpec {
            id: Some("gate-fixture".to_string()),
            goal: "gate fixture".to_string(),
            description: None,
            budget: BudgetSpec::default(),
            permissions: Default::default(),
            model_policy: Default::default(),
            promotion_policy: Default::default(),
            gates: gates.clone(),
            nodes: Vec::new(),
        };
        state.runs.lock().expect("runs").insert(
            run_id.clone(),
            WorkflowRunRecord::new(run_id.clone(), None, None, Some(&spec)),
        );
        let driver = SubAgentWorkflowDriver::new(
            run_id.clone(),
            manager,
            runtime,
            state.clone(),
            None,
            WorkflowFleetBinding::None,
            gates,
        );

        driver.evaluate_gates_for_completed_role(&RuntimeTaskRecord {
            agent_id: "scout-agent".to_string(),
            label: Some("scout".to_string()),
            role: Some("scout".to_string()),
            status: IrWorkflowRunStatus::Succeeded,
            output: Some("findings: inspect tui exit path".to_string()),
            schema_error: None,
            usage: None,
        });

        let mut implementer = TaskRequest {
            description: "Use the findings.".to_string(),
            subagent_type: Some("implementer".to_string()),
            role: Some("implementer".to_string()),
            profile: None,
            model: None,
            model_strength: None,
            thinking: None,
            cwd: None,
            worktree: false,
            write_authority: Some("workspace_write".to_string()),
            write_roots: vec!["src".to_string()],
            exact_files: Vec::new(),
            coordination_contracts: vec!["test-contract".to_string()],
            dependencies: Vec::new(),
            acceptance: Vec::new(),
            allowed_tools: Some(Vec::new()),
            disallowed_tools: Vec::new(),
            max_depth: None,
            token_budget: None,
            max_steps: None,
            wall_time_secs: None,
            response_schema: None,
            label: Some("fix".to_string()),
            phase: None,
        };
        let handoffs = driver
            .prepare_request_for_gates(&mut implementer)
            .expect("passed gate should admit implementer");
        assert_eq!(handoffs.len(), 1, "{handoffs:?}");
        assert_eq!(handoffs[0].kind, "findings");
        assert_eq!(handoffs[0].from_role, "scout");
        assert_eq!(handoffs[0].to_role, "implementer");
        assert!(
            implementer
                .description
                .contains("Workflow handoff artifacts available"),
            "{}",
            implementer.description
        );
        assert!(
            implementer.description.contains("inspect tui exit path"),
            "{}",
            implementer.description
        );

        driver.evaluate_gates_for_completed_role(&RuntimeTaskRecord {
            agent_id: "scout-agent-2".to_string(),
            label: Some("scout".to_string()),
            role: Some("scout".to_string()),
            status: IrWorkflowRunStatus::Failed,
            output: Some("scout incomplete".to_string()),
            schema_error: None,
            usage: None,
        });
        let mut blocked = TaskRequest {
            description: "Try after block.".to_string(),
            role: Some("implementer".to_string()),
            ..implementer.clone()
        };
        let err = driver
            .prepare_request_for_gates(&mut blocked)
            .expect_err("blocked gate should reject downstream role");
        assert!(err.to_string().contains("scout incomplete"), "{err}");

        let run = state
            .runs
            .lock()
            .expect("runs")
            .get(&run_id)
            .cloned()
            .expect("run");
        assert!(
            run.gate_status
                .iter()
                .any(|line| line.gate_id == "scout-findings"
                    && line.state == "blocked"
                    && line.blocked_reason.as_deref() == Some("scout incomplete")),
            "{:?}",
            run.gate_status
        );
        assert!(
            run.events
                .iter()
                .any(|event| event.event_type() == "gate_updated"),
            "{:?}",
            run.events
        );
        assert_eq!(
            run.events
                .iter()
                .filter(|event| event.event_type() == "handoff_promoted")
                .count(),
            1,
            "a later blocked gate must not publish another handoff: {:?}",
            run.events
        );
        assert!(
            run.events
                .iter()
                .all(|event| event.event_type() != "handoff_consumed"),
            "request preparation alone must not claim consumption: {:?}",
            run.events
        );
    }

    #[tokio::test]
    async fn workflow_handoff_is_delivered_to_exactly_one_task() {
        // LaneGateBoard.artifacts used to be append-only: every same-role
        // task re-received up to 4 prior handoff payloads while
        // HandoffConsumed receipts fired as if they were spent.
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let runtime = SubAgentRuntime::new(
            stub_client(),
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let state = WorkflowWorkspaceState::open(tmp.path());
        let run_id = "workflow_handoff_once".to_string();
        let gates = vec![GateSpec {
            id: "scout-findings".to_string(),
            role: "scout".to_string(),
            on: GateOn::RoleComplete,
            gate: GateKind::Approve,
            on_fail: codewhale_workflow::GateOnFail::Block,
            blocks_role: Some("implementer".to_string()),
            max_retries: 0,
            artifact_kind: Some("findings".to_string()),
            require_explicit_verdict: false,
        }];
        let spec = WorkflowSpec {
            id: Some("handoff-once-fixture".to_string()),
            goal: "handoff delivered once".to_string(),
            description: None,
            budget: BudgetSpec::default(),
            permissions: Default::default(),
            model_policy: Default::default(),
            promotion_policy: Default::default(),
            gates: gates.clone(),
            nodes: Vec::new(),
        };
        state.runs.lock().expect("runs").insert(
            run_id.clone(),
            WorkflowRunRecord::new(run_id.clone(), None, None, Some(&spec)),
        );
        let driver = SubAgentWorkflowDriver::new(
            run_id.clone(),
            manager,
            runtime,
            state.clone(),
            None,
            WorkflowFleetBinding::None,
            gates,
        );

        driver.evaluate_gates_for_completed_role(&RuntimeTaskRecord {
            agent_id: "scout-agent".to_string(),
            label: Some("scout".to_string()),
            role: Some("scout".to_string()),
            status: IrWorkflowRunStatus::Succeeded,
            output: Some("findings: exactly once".to_string()),
            schema_error: None,
            usage: None,
        });

        let implementer = TaskRequest {
            description: "Use the findings.".to_string(),
            subagent_type: Some("implementer".to_string()),
            role: Some("implementer".to_string()),
            profile: None,
            model: None,
            model_strength: None,
            thinking: None,
            cwd: None,
            worktree: false,
            write_authority: Some("workspace_write".to_string()),
            write_roots: vec!["src".to_string()],
            exact_files: Vec::new(),
            coordination_contracts: Vec::new(),
            dependencies: Vec::new(),
            acceptance: Vec::new(),
            allowed_tools: Some(Vec::new()),
            disallowed_tools: Vec::new(),
            max_depth: None,
            token_budget: None,
            max_steps: None,
            wall_time_secs: None,
            response_schema: None,
            label: Some("fix".to_string()),
            phase: None,
        };

        let mut first = implementer.clone();
        let handoffs = driver
            .prepare_request_for_gates(&mut first)
            .expect("passed gate should admit first implementer");
        assert_eq!(handoffs.len(), 1, "{handoffs:?}");
        assert!(first.description.contains("exactly once"));

        // A second same-role task must not re-receive the spent handoff.
        let mut second = TaskRequest {
            description: "Second implementer task.".to_string(),
            ..implementer
        };
        let handoffs = driver
            .prepare_request_for_gates(&mut second)
            .expect("passed gate should admit second implementer");
        assert!(
            handoffs.is_empty(),
            "handoff already consumed must not re-deliver: {handoffs:?}"
        );
        assert!(
            !second
                .description
                .contains("Workflow handoff artifacts available"),
            "{}",
            second.description
        );
    }

    #[tokio::test]
    async fn workflow_gate_evaluation_error_persists_blocked_and_denies_target_role() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let runtime = SubAgentRuntime::new(
            stub_client(),
            "deepseek-v4-flash".to_string(),
            ctx,
            true,
            None,
            manager.clone(),
        );
        let state = WorkflowWorkspaceState::open(tmp.path());
        let run_id = "workflow_malformed_gate".to_string();
        let gates = vec![GateSpec {
            id: String::new(),
            role: "scout".to_string(),
            on: GateOn::RoleComplete,
            gate: GateKind::Approve,
            on_fail: codewhale_workflow::GateOnFail::Block,
            blocks_role: Some("implementer".to_string()),
            max_retries: 0,
            artifact_kind: Some("findings".to_string()),
            require_explicit_verdict: false,
        }];
        let spec = WorkflowSpec {
            id: Some("malformed-gate-fixture".to_string()),
            goal: "malformed gate must fail closed".to_string(),
            description: None,
            budget: BudgetSpec::default(),
            permissions: Default::default(),
            model_policy: Default::default(),
            promotion_policy: Default::default(),
            gates: gates.clone(),
            nodes: Vec::new(),
        };
        state.runs.lock().expect("runs").insert(
            run_id.clone(),
            WorkflowRunRecord::new(run_id.clone(), None, None, Some(&spec)),
        );
        let driver = SubAgentWorkflowDriver::new(
            run_id.clone(),
            manager,
            runtime,
            state.clone(),
            None,
            WorkflowFleetBinding::None,
            gates,
        );

        driver.evaluate_gates_for_completed_role(&RuntimeTaskRecord {
            agent_id: "scout-agent".to_string(),
            label: Some("scout".to_string()),
            role: Some("scout".to_string()),
            status: IrWorkflowRunStatus::Succeeded,
            output: Some("findings".to_string()),
            schema_error: None,
            usage: None,
        });

        let mut request = TaskRequest {
            description: "Must not be admitted.".to_string(),
            subagent_type: Some("implementer".to_string()),
            role: Some("implementer".to_string()),
            profile: None,
            model: None,
            model_strength: None,
            thinking: None,
            cwd: None,
            worktree: false,
            write_authority: Some("workspace_write".to_string()),
            write_roots: vec!["src".to_string()],
            exact_files: Vec::new(),
            coordination_contracts: vec!["test-contract".to_string()],
            dependencies: Vec::new(),
            acceptance: Vec::new(),
            allowed_tools: Some(Vec::new()),
            disallowed_tools: Vec::new(),
            max_depth: None,
            token_budget: None,
            max_steps: None,
            wall_time_secs: None,
            response_schema: None,
            label: Some("blocked".to_string()),
            phase: None,
        };
        let error = driver
            .prepare_request_for_gates(&mut request)
            .expect_err("malformed gate must deny its target role");
        assert!(
            error.to_string().contains("gate id must not be empty"),
            "{error}"
        );
        let board = driver.gate_board.lock().expect("gate board");
        assert!(matches!(
            board.gates.get(""),
            Some(GateState::Blocked { reason }) if reason.contains("gate id must not be empty")
        ));
        assert!(board.artifacts.is_empty(), "{:?}", board.artifacts);
        drop(board);
        let run = state
            .runs
            .lock()
            .expect("runs")
            .get(&run_id)
            .cloned()
            .expect("run");
        assert!(run.gate_status.iter().any(|line| {
            line.gate_id.is_empty()
                && line.state == "blocked"
                && line
                    .blocked_reason
                    .as_deref()
                    .is_some_and(|reason| reason.contains("gate id must not be empty"))
        }));
        assert!(
            run.events
                .iter()
                .all(|event| event.event_type() != "handoff_promoted"),
            "{:?}",
            run.events
        );
    }

    #[tokio::test]
    async fn workflow_handoff_record_error_changes_pass_to_blocked() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let runtime = SubAgentRuntime::new(
            stub_client(),
            "deepseek-v4-flash".to_string(),
            ctx,
            true,
            None,
            manager.clone(),
        );
        let state = WorkflowWorkspaceState::open(tmp.path());
        let run_id = "workflow_handoff_record_error".to_string();
        let gates = vec![GateSpec {
            id: "scout-findings".to_string(),
            role: "scout".to_string(),
            on: GateOn::RoleComplete,
            gate: GateKind::Approve,
            on_fail: codewhale_workflow::GateOnFail::Block,
            blocks_role: Some("implementer".to_string()),
            max_retries: 0,
            artifact_kind: Some("findings".to_string()),
            require_explicit_verdict: false,
        }];
        let spec = WorkflowSpec {
            id: Some("handoff-record-error-fixture".to_string()),
            goal: "failed handoff recording must fail closed".to_string(),
            description: None,
            budget: BudgetSpec::default(),
            permissions: Default::default(),
            model_policy: Default::default(),
            promotion_policy: Default::default(),
            gates: gates.clone(),
            nodes: Vec::new(),
        };
        state.runs.lock().expect("runs").insert(
            run_id.clone(),
            WorkflowRunRecord::new(run_id.clone(), None, None, Some(&spec)),
        );
        let driver = SubAgentWorkflowDriver::new(
            run_id.clone(),
            manager,
            runtime,
            state.clone(),
            None,
            WorkflowFleetBinding::None,
            gates,
        );
        driver.gate_board.lock().expect("gate board").lane_id = "wrong-lane".to_string();

        driver.evaluate_gates_for_completed_role(&RuntimeTaskRecord {
            agent_id: "scout-agent".to_string(),
            label: Some("scout".to_string()),
            role: Some("scout".to_string()),
            status: IrWorkflowRunStatus::Succeeded,
            output: Some("findings".to_string()),
            schema_error: None,
            usage: None,
        });

        let mut request = TaskRequest {
            description: "Must not be admitted.".to_string(),
            subagent_type: Some("implementer".to_string()),
            role: Some("implementer".to_string()),
            profile: None,
            model: None,
            model_strength: None,
            thinking: None,
            cwd: None,
            worktree: false,
            write_authority: Some("workspace_write".to_string()),
            write_roots: vec!["src".to_string()],
            exact_files: Vec::new(),
            coordination_contracts: vec!["test-contract".to_string()],
            dependencies: Vec::new(),
            acceptance: Vec::new(),
            allowed_tools: Some(Vec::new()),
            disallowed_tools: Vec::new(),
            max_depth: None,
            token_budget: None,
            max_steps: None,
            wall_time_secs: None,
            response_schema: None,
            label: Some("blocked".to_string()),
            phase: None,
        };
        let error = driver
            .prepare_request_for_gates(&mut request)
            .expect_err("unrecorded handoff must deny its target role");
        assert!(
            error.to_string().contains("handoff could not be recorded"),
            "{error}"
        );
        let board = driver.gate_board.lock().expect("gate board");
        assert!(matches!(
            board.gates.get("scout-findings"),
            Some(GateState::Blocked { reason }) if reason.contains("does not match board lane")
        ));
        assert!(board.artifacts.is_empty(), "{:?}", board.artifacts);
        drop(board);
        let run = state
            .runs
            .lock()
            .expect("runs")
            .get(&run_id)
            .cloned()
            .expect("run");
        assert!(run.events.iter().any(|event| {
            matches!(
                &event.kind,
                WorkflowUiEventKind::GateUpdated {
                    state,
                    blocked_reason: Some(reason),
                    ..
                } if state == "blocked" && reason.contains("handoff could not be recorded")
            )
        }));
        assert!(
            run.events
                .iter()
                .all(|event| event.event_type() != "handoff_promoted"),
            "{:?}",
            run.events
        );
    }

    #[test]
    fn explicit_gate_verdict_only_reads_first_standalone_token() {
        assert_eq!(
            explicit_gate_verdict(Some("\n  APPROVE  \nreview complete")),
            Some(ExplicitGateVerdict::Approve)
        );
        assert_eq!(
            explicit_gate_verdict(Some("PASS\nverification complete")),
            Some(ExplicitGateVerdict::Approve)
        );
        assert_eq!(
            explicit_gate_verdict(Some("BLOCK\nmissing receipt")),
            Some(ExplicitGateVerdict::Reject)
        );
        assert_eq!(
            explicit_gate_verdict(Some("\nFAIL\nmissing receipt")),
            Some(ExplicitGateVerdict::Reject)
        );
        assert_eq!(
            explicit_gate_verdict(Some("Review result: BLOCK")),
            None,
            "prose remains backward-compatible success output"
        );
        assert_eq!(
            explicit_gate_verdict(Some("review notes\nBLOCK")),
            None,
            "later verdict words must not override the first meaningful line"
        );
    }

    #[test]
    fn required_explicit_gate_verdict_fails_closed_when_missing_or_malformed() {
        let mut record = RuntimeTaskRecord {
            agent_id: "reviewer-malformed".to_string(),
            label: Some("reviewer".to_string()),
            role: Some("reviewer".to_string()),
            status: IrWorkflowRunStatus::Succeeded,
            output: Some("Review result: BLOCK".to_string()),
            schema_error: None,
            usage: None,
        };

        match gate_outcome_for_completed_role(&record, true, None) {
            GateOutcome::Fail { reason } => {
                assert!(
                    reason.contains("required first-line gate verdict"),
                    "{reason}"
                );
            }
            outcome => panic!("required malformed verdict must fail closed: {outcome:?}"),
        }
        assert_eq!(
            gate_outcome_for_completed_role(&record, false, None),
            GateOutcome::Pass,
            "legacy gates retain pass-on-success behavior"
        );

        record.output = None;
        assert!(matches!(
            gate_outcome_for_completed_role(&record, true, None),
            GateOutcome::Fail { .. }
        ));
    }

    #[test]
    fn required_gate_artifact_rejects_bare_or_placeholder_approval() {
        let mut record = RuntimeTaskRecord {
            agent_id: "implementer-bare".to_string(),
            label: Some("implementer".to_string()),
            role: Some("implementer".to_string()),
            status: IrWorkflowRunStatus::Succeeded,
            output: Some("APPROVE".to_string()),
            schema_error: None,
            usage: None,
        };

        match gate_outcome_for_completed_role(&record, true, Some("verification_plan")) {
            GateOutcome::Fail { reason } => {
                assert!(
                    reason.contains("verification_plan artifact body"),
                    "{reason}"
                );
            }
            outcome => panic!("bare approval must not promote an empty artifact: {outcome:?}"),
        }

        record.output = Some("APPROVE\nacceptance evidence".to_string());
        match gate_outcome_for_completed_role(&record, true, Some("verification_plan")) {
            GateOutcome::Fail { reason } => {
                assert!(
                    reason.contains("verification_plan artifact body"),
                    "{reason}"
                );
            }
            outcome => {
                panic!("one placeholder line must not count as an artifact: {outcome:?}");
            }
        }

        record.output = Some("APPROVE\nPLAN\n- verify the typed receipt".to_string());
        assert_eq!(
            gate_outcome_for_completed_role(&record, true, Some("verification_plan")),
            GateOutcome::Pass
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn terminal_blocked_gate_fails_workflow_finalization() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls) =
            fake_chat_client("BLOCK\nFINAL RECEIPT\n- missing terminal evidence").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "script": r#"export default workflow({
                        "goal": "fail closed on the terminal release verdict",
                        "gates": [
                            {
                                "id": "terminal-release",
                                "role": "release_lead",
                                "on": "role_complete",
                                "gate": "approve",
                                "on_fail": "block",
                                "max_retries": 0,
                                "artifact_kind": "final_receipt",
                                "require_explicit_verdict": true
                            }
                        ],
                        "nodes": [
                            {
                                "agent": {
                                    "id": "release-receipt",
                                    "prompt": "Return the terminal verdict and receipt.",
                                    "agent_type": "general",
                                    "role": "release_lead",
                                    "mode": "read_only",
                                    "permissions": { "deny_all_tools": true },
                                    "budget": { "max_steps": 1 }
                                }
                            }
                        ]
                    });"#
                }),
                &ctx,
            )
            .await
            .expect("blocked terminal gate should return its failed run record");
        let payload: Value = serde_json::from_str(&result.content).expect("workflow JSON");

        assert_eq!(calls.load(Ordering::SeqCst), 1, "{payload}");
        assert_eq!(payload["status"], "failed", "{payload}");
        assert_eq!(payload["execution"]["status"], "failed", "{payload}");
        assert!(
            payload["error"]
                .as_str()
                .is_some_and(|error| error.contains("terminal-release")
                    && error.contains("ended blocked")
                    && error.contains("missing terminal evidence")),
            "{payload}"
        );
        assert!(payload["gate_status"].as_array().is_some_and(|gates| {
            gates
                .iter()
                .any(|gate| gate["gate_id"] == "terminal-release" && gate["state"] == "blocked")
        }));
        assert!(payload["events"].as_array().is_some_and(|events| {
            events
                .iter()
                .any(|event| event["type"] == "run_completed" && event["status"] == "failed")
        }));
    }

    #[tokio::test]
    async fn workflow_runtime_gate_honors_explicit_reviewer_verdicts() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let runtime = SubAgentRuntime::new(
            stub_client(),
            "deepseek-v4-flash".to_string(),
            ctx,
            true,
            None,
            manager.clone(),
        );
        let state = WorkflowWorkspaceState::open(tmp.path());
        let run_id = "workflow_explicit_verdict".to_string();
        let gates = vec![GateSpec {
            id: "review-findings".to_string(),
            role: "reviewer".to_string(),
            on: GateOn::RoleComplete,
            gate: GateKind::Review,
            on_fail: codewhale_workflow::GateOnFail::Block,
            blocks_role: Some("verifier".to_string()),
            max_retries: 0,
            artifact_kind: Some("review_report".to_string()),
            require_explicit_verdict: true,
        }];
        let spec = WorkflowSpec {
            id: Some("explicit-verdict-fixture".to_string()),
            goal: "honor reviewer verdict".to_string(),
            description: None,
            budget: BudgetSpec::default(),
            permissions: Default::default(),
            model_policy: Default::default(),
            promotion_policy: Default::default(),
            gates: gates.clone(),
            nodes: Vec::new(),
        };
        state.runs.lock().expect("runs").insert(
            run_id.clone(),
            WorkflowRunRecord::new(run_id.clone(), None, None, Some(&spec)),
        );
        let driver = SubAgentWorkflowDriver::new(
            run_id,
            manager,
            runtime,
            state,
            None,
            WorkflowFleetBinding::None,
            gates,
        );

        driver.evaluate_gates_for_completed_role(&RuntimeTaskRecord {
            agent_id: "reviewer-block".to_string(),
            label: Some("reviewer".to_string()),
            role: Some("reviewer".to_string()),
            status: IrWorkflowRunStatus::Succeeded,
            output: Some("\nBLOCK\nmissing terminal receipt".to_string()),
            schema_error: None,
            usage: None,
        });

        let verifier_request = || TaskRequest {
            description: "Verify the accepted review.".to_string(),
            subagent_type: Some("verifier".to_string()),
            role: Some("verifier".to_string()),
            profile: None,
            model: None,
            model_strength: None,
            thinking: None,
            cwd: None,
            worktree: false,
            write_authority: Some("read_only".to_string()),
            write_roots: Vec::new(),
            exact_files: Vec::new(),
            coordination_contracts: Vec::new(),
            dependencies: Vec::new(),
            acceptance: Vec::new(),
            allowed_tools: Some(Vec::new()),
            disallowed_tools: Vec::new(),
            max_depth: None,
            token_budget: None,
            max_steps: None,
            wall_time_secs: None,
            response_schema: None,
            label: Some("verify".to_string()),
            phase: None,
        };
        let mut blocked_verifier = verifier_request();
        let error = driver
            .prepare_request_for_gates(&mut blocked_verifier)
            .expect_err("successful reviewer BLOCK must not admit verifier");
        assert!(error.to_string().contains("BLOCK"), "{error}");
        {
            let board = driver.gate_board.lock().expect("gate board");
            assert!(
                board.artifacts.is_empty(),
                "rejected output must not produce a handoff: {:?}",
                board.artifacts
            );
            assert!(matches!(
                board.gates.get("review-findings"),
                Some(GateState::Blocked { .. })
            ));
        }

        driver.evaluate_gates_for_completed_role(&RuntimeTaskRecord {
            agent_id: "reviewer-approve".to_string(),
            label: Some("reviewer".to_string()),
            role: Some("reviewer".to_string()),
            status: IrWorkflowRunStatus::Succeeded,
            output: Some("APPROVE\nEVIDENCE REVIEW\n- all receipt owners confirmed".to_string()),
            schema_error: None,
            usage: None,
        });

        let mut admitted_verifier = verifier_request();
        driver
            .prepare_request_for_gates(&mut admitted_verifier)
            .expect("explicit reviewer APPROVE should admit verifier");
        assert!(
            admitted_verifier
                .description
                .contains("all receipt owners confirmed"),
            "{}",
            admitted_verifier.description
        );
        let board = driver.gate_board.lock().expect("gate board");
        assert!(
            board.artifacts.is_empty(),
            "the admitted verifier consumed the handoff; spent artifacts leave the board: {:?}",
            board.artifacts
        );
        assert!(matches!(
            board.gates.get("review-findings"),
            Some(GateState::Passed)
        ));
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn workflow_status_lists_compact_typed_receipts() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, _calls) = fake_chat_client("status-output").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);

        let run = tool
            .execute(
                json!({
                    "action": "run",
                    "script": r#"export default workflow({
                        "id": "status-fixture",
                        "goal": "status summary",
                        "nodes": [
                            {
                                "agent": {
                                    "id": "inspect",
                                    "prompt": "Inspect the code.",
                                    "agent_type": "review"
                                }
                            }
                        ]
                    });"#
                }),
                &ctx,
            )
            .await
            .expect("workflow run");
        let run_payload: Value = serde_json::from_str(&run.content).expect("run json");

        let status = tool
            .execute(json!({"action": "status"}), &ctx)
            .await
            .expect("workflow status");
        let status_payload: Value = serde_json::from_str(&status.content).expect("status json");
        let summary = &status_payload["runs"][0];

        assert_eq!(status_payload["count"], 1);
        assert_eq!(summary["run_id"], run_payload["run_id"]);
        assert_eq!(summary["workflow_id"], "status-fixture");
        assert_eq!(summary["workflow_goal"], "status summary");
        assert_eq!(summary["status"], "completed");
        assert_eq!(summary["execution_status"], "succeeded");
        assert_eq!(summary["child_count"], 1);
        assert_eq!(summary["leaf_count"], 1);
        assert_eq!(summary["branch_count"], 0);
        assert_eq!(summary["control_count"], 0);
        assert!(summary["event_count"].as_u64().unwrap_or_default() >= 3);
        assert_eq!(summary["last_event_type"], "run_completed");
        assert!(summary.get("result").is_none());
        assert!(summary.get("execution").is_none());
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn workflow_status_survives_tool_rebuild_via_journal() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, _calls) = fake_chat_client("journal-output").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let tool = WorkflowTool::new(manager.clone(), runtime.clone());

        let run = tool
            .execute(
                json!({
                    "action": "run",
                    "script": "return { ok: true };"
                }),
                &ctx,
            )
            .await
            .expect("workflow run");
        let run_payload: Value = serde_json::from_str(&run.content).expect("run json");
        let run_id = run_payload["run_id"].as_str().expect("run id");

        let journal_path = tmp.path().join(".codewhale/workflow-runs.jsonl");
        assert!(
            journal_path.exists(),
            "journal should be created under workspace"
        );

        let rebuilt = WorkflowTool::new(
            manager.clone(),
            SubAgentRuntime::new(
                stub_client(),
                "deepseek-v4-flash".to_string(),
                ctx.clone(),
                true,
                None,
                manager,
            ),
        );
        let status = rebuilt
            .execute(json!({"action": "status", "run_id": run_id}), &ctx)
            .await
            .expect("workflow status after rebuild");
        let status_payload: Value = serde_json::from_str(&status.content).expect("status json");
        assert_eq!(status_payload["run_id"], run_id);
        assert_eq!(status_payload["status"], "completed");
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn workflow_status_surfaces_schema_failure_instead_of_null_success() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, _calls) = fake_chat_client(r#"{"refuted":"yes"}"#).await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let tool = WorkflowTool::new(manager, runtime);

        let run = tool
            .execute(
                json!({
                    "action": "run",
                    "script": r#"
                    return await parallel([
                        () => task({
                            description: "Return the schema fixture.",
                            responseSchema: {
                                type: "object",
                                properties: { refuted: { type: "boolean" } },
                                required: ["refuted"],
                            },
                        }),
                    ]);
                    "#
                }),
                &ctx,
            )
            .await
            .expect("workflow run returns a record");
        let run_payload: Value = serde_json::from_str(&run.content).expect("run json");

        assert_eq!(run_payload["status"], "failed");
        assert!(run_payload["result"].is_null());
        assert!(
            run_payload["error"]
                .as_str()
                .unwrap()
                .contains("responseSchema validation")
        );
        assert!(
            run_payload["progress"]
                .as_array()
                .unwrap()
                .iter()
                .any(|message| message
                    .as_str()
                    .is_some_and(|message| message.contains("schema validation failed"))),
            "schema validation error should be visible in the run receipt: {run_payload}"
        );
        assert!(
            run_payload["events"]
                .as_array()
                .unwrap()
                .iter()
                .any(|event| event["type"] == "task_schema_validation_failed"
                    && event["message"]
                        .as_str()
                        .is_some_and(|message| message.contains("responseSchema validation"))),
            "schema validation event should be visible in the typed receipt: {run_payload}"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn declarative_issue_audit_fixture_runs_through_subagent_driver() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let workflow_dir = tmp.path().join("workflows");
        std::fs::create_dir_all(&workflow_dir).expect("workflow dir");
        let fixture = std::fs::read_to_string(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../../workflows/issue_audit.workflow.js"),
        )
        .expect("issue audit fixture");
        std::fs::write(workflow_dir.join("issue_audit.workflow.js"), fixture)
            .expect("write fixture into workspace");

        let mut ctx = ToolContext::new(tmp.path().to_path_buf());
        ctx.runtime.work = Some(crate::work_graph::new_shared_work_runtime(
            crate::tools::todo::new_shared_todo_list(),
            crate::tools::plan::new_shared_plan_state(),
        ));
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 4);
        let (client, calls) = fake_chat_client("audited").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "source_path": "workflows/issue_audit.workflow.js"
                }),
                &ctx,
            )
            .await
            .expect("declarative workflow should complete");
        let payload: Value = serde_json::from_str(&result.content).expect("json result");

        assert_eq!(payload["status"], "completed", "{payload}");
        assert_eq!(payload["result"]["code-audit"], "audited");
        assert_eq!(payload["result"]["test-audit"], "audited");
        assert_eq!(payload["result"]["docs-audit"], "audited");
        assert_eq!(payload["result"]["synthesize-release-risk"], "audited");
        assert_eq!(payload["execution"]["status"], "succeeded");
        assert_eq!(
            payload["execution"]["leaf_results"]
                .as_array()
                .expect("leaf results")
                .len(),
            3
        );
        assert_eq!(
            payload["execution"]["branch_results"][0]["branch_id"],
            "parallel-audit"
        );
        assert!(
            payload["execution"]["control_node_results"]
                .as_array()
                .expect("control results")
                .iter()
                .any(|result| result["node_id"] == "synthesize-release-risk"
                    && result["kind"] == "reduce"
                    && result["status"] == "succeeded")
        );
        assert_eq!(payload["child_ids"].as_array().unwrap().len(), 4);
        assert_eq!(calls.load(Ordering::SeqCst), 4);
        assert!(
            payload["progress"]
                .as_array()
                .unwrap()
                .iter()
                .any(|message| message == "phase: parallel-audit")
        );

        // Operate projects Workflow fan-out/fan-in and its children through
        // the same canonical Work Graph. The Workflow remains the accountable
        // operation identity while the worker bindings stay inspectable; no
        // second plan/strategy lifecycle is created for the reduce step.
        let work = ctx.runtime.work.as_ref().expect("work runtime");
        let graph = work
            .capture(Some(&ctx.state_namespace))
            .expect("capture workflow work")
            .expect("workflow graph")
            .graph;
        let workflow_external = format!(
            "workflow:{}",
            payload["run_id"].as_str().expect("workflow run id")
        );
        let workflow_operations = graph
            .nodes
            .iter()
            .filter(|node| {
                node.binding
                    .as_ref()
                    .is_some_and(|binding| binding.external == workflow_external)
            })
            .collect::<Vec<_>>();
        assert_eq!(
            workflow_operations.len(),
            1,
            "one accountable Workflow operation: {graph:#?}"
        );
        assert_eq!(
            workflow_operations[0].state,
            crate::work_graph::NodeState::Completed
        );
        for child_id in payload["child_ids"].as_array().expect("workflow child ids") {
            let worker_external = format!(
                "worker:{}",
                child_id.as_str().expect("workflow child id string")
            );
            assert!(
                graph.nodes.iter().any(|node| {
                    node.binding
                        .as_ref()
                        .is_some_and(|binding| binding.external == worker_external)
                }),
                "Workflow worker {worker_external} must remain inspectable in the same graph: {graph:#?}"
            );
        }
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn stopship_acceptance_fixture_emits_role_gate_and_terminal_receipts() {
        let _retry_guard = workflow_test_retry_guard();
        let _env_lock = crate::test_support::lock_test_env();
        let tmp = tempfile::tempdir().expect("tempdir");
        let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path());
        let workflow_dir = tmp.path().join("workflows");
        let fleet_dir = tmp.path().join("fleets");
        std::fs::create_dir_all(&workflow_dir).expect("workflow dir");
        std::fs::create_dir_all(&fleet_dir).expect("fleet dir");
        let repo_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
        std::fs::copy(
            repo_root.join("workflows/stopship.workflow.js"),
            workflow_dir.join("stopship.workflow.js"),
        )
        .expect("copy stopship acceptance fixture");
        std::fs::copy(
            repo_root.join("fleets/stopship.toml"),
            fleet_dir.join("stopship.toml"),
        )
        .expect("copy stopship fleet");

        let source = std::fs::read_to_string(workflow_dir.join("stopship.workflow.js"))
            .expect("read stopship acceptance fixture");
        let compiled =
            codewhale_workflow::compile_javascript_workflow("stopship.workflow.js", &source)
                .expect("compile stopship acceptance fixture");
        let codewhale_workflow::WorkflowNode::Sequence(sequence) = &compiled.nodes[0] else {
            panic!("stopship fixture should be one ordered role chain");
        };
        for (index, node) in sequence.children.iter().enumerate() {
            let codewhale_workflow::WorkflowNode::Leaf(leaf) = node else {
                panic!("stopship role chain must contain only leaves");
            };
            let tools = leaf_allowed_tools(leaf).expect("lower stopship child tools");
            if index == 0 {
                assert!(tools.as_ref().is_some_and(|tools| !tools.is_empty()));
            } else {
                assert_eq!(
                    tools,
                    Some(Vec::<String>::new()),
                    "downstream handoff consumer {} must receive no tools",
                    leaf.id
                );
            }
        }

        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 8);
        let responses = [
            r#"APPROVE
SOURCE EVIDENCE
- crates/cli/src/lib.rs: load_named_fleet
- crates/workflow/src/role_resolve.rs: resolve_workflow_agent
- crates/cli/src/lib.rs: start_lane
- crates/tui/src/tools/workflow.rs: record_task_started
- crates/tui/src/tools/workflow.rs: WorkflowUiEventKind::GateUpdated
- crates/tui/src/tools/workflow.rs: WorkflowUiEventKind::RunCompleted -> terminal_completed_receipt
- crates/lane/src/runtime.rs: process_exit_receipt -> lane_reconciled"#,
            r#"APPROVE
PLAN
- fleets/stopship.toml: name = "stopship" -> named Fleet loading
- crates/workflow/src/role_resolve.rs: resolve_workflow_agent -> role resolution
- crates/cli/src/lib.rs: start_lane -> tmux Lane launch
- crates/tui/src/tools/workflow.rs: record_task_started -> typed task_started
- crates/tui/src/tools/workflow.rs: WorkflowUiEventKind::GateUpdated -> gate promotion
- crates/tui/src/tools/workflow.rs: WorkflowUiEventKind::RunCompleted -> terminal_completed_receipt
- crates/lane/src/runtime.rs: process_exit_receipt -> tmux Lane reconciliation"#,
            r#"APPROVE
EVIDENCE REVIEW
- fleets/stopship.toml: name = "stopship"
- crates/workflow/src/role_resolve.rs: resolve_workflow_agent
- crates/cli/src/lib.rs: start_lane
- crates/tui/src/tools/workflow.rs: record_task_started
- crates/tui/src/tools/workflow.rs: WorkflowUiEventKind::GateUpdated
- crates/tui/src/tools/workflow.rs: WorkflowUiEventKind::RunCompleted -> terminal_completed_receipt
- crates/lane/src/runtime.rs: process_exit_receipt -> lane_reconciled"#,
            r#"APPROVE
EVIDENCE MATRIX
- fleet_load: fleets/stopship.toml: name = "stopship"
- role_resolution: crates/workflow/src/role_resolve.rs: resolve_workflow_agent
- lane_launch: crates/cli/src/lib.rs: start_lane
- task_started: crates/tui/src/tools/workflow.rs: record_task_started
- gate_updated: crates/tui/src/tools/workflow.rs: WorkflowUiEventKind::GateUpdated
- run_completed: crates/tui/src/tools/workflow.rs: WorkflowUiEventKind::RunCompleted -> terminal_completed_receipt
- lane_exit: crates/lane/src/runtime.rs: process_exit_receipt -> lane_reconciled"#,
            r#"APPROVE
FINAL RECEIPT
- fleet_load: fleets/stopship.toml: name = "stopship"
- role_resolution: crates/workflow/src/role_resolve.rs: resolve_workflow_agent
- lane_launch: crates/cli/src/lib.rs: start_lane
- task_started: crates/tui/src/tools/workflow.rs: record_task_started
- gate_updated: crates/tui/src/tools/workflow.rs: WorkflowUiEventKind::GateUpdated
- run_completed: crates/tui/src/tools/workflow.rs: WorkflowUiEventKind::RunCompleted -> terminal_completed_receipt
- lane_exit: crates/lane/src/runtime.rs: process_exit_receipt -> lane_reconciled"#,
        ];
        let (client, calls) = fake_chat_client_responses(&responses).await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "source_path": "workflows/stopship.workflow.js",
                    "fleet": "stopship",
                    "token_budget": 60_000
                }),
                &ctx,
            )
            .await
            .expect("stopship acceptance workflow returns a terminal record");
        let payload: Value = serde_json::from_str(&result.content).expect("workflow JSON");

        assert_eq!(payload["status"], "completed", "{payload}");
        assert_eq!(payload["execution"]["status"], "succeeded", "{payload}");
        assert_eq!(calls.load(Ordering::SeqCst), 5, "one child per Fleet role");
        let approval = &payload["plan_approval"];
        assert_eq!(approval["decision"], "auto_read_only", "{approval}");
        assert_eq!(approval["token_budget"], 60_000, "{approval}");
        assert_eq!(approval["writes"], false, "{approval}");
        assert_eq!(approval["shell"], false, "{approval}");
        assert_eq!(approval["network"], false, "{approval}");
        assert_eq!(approval["high_budget"], false, "{approval}");
        assert_eq!(approval["elevated"], false, "{approval}");
        assert!(
            approval["reasons"].as_array().is_some_and(Vec::is_empty),
            "{approval}"
        );

        let events = payload["events"].as_array().expect("typed events");
        let started = events
            .iter()
            .filter(|event| event["type"] == "task_started")
            .collect::<Vec<_>>();
        let expected_roles = [
            ("scout", "scout"),
            ("implementer", "builder"),
            ("reviewer", "reviewer"),
            ("verifier", "verifier"),
            ("release_lead", "manager"),
        ];
        assert_eq!(started.len(), expected_roles.len(), "{started:#?}");
        for (event, (role, profile)) in started.iter().zip(expected_roles) {
            assert_eq!(event["role"], role);
            assert_eq!(event["profile"], profile);
            assert_eq!(event["resolved_profile"], profile);
            assert_eq!(event["workflow_run_id"], payload["run_id"]);
        }

        let gates = events
            .iter()
            .filter(|event| event["type"] == "gate_updated")
            .collect::<Vec<_>>();
        assert_eq!(gates.len(), 5, "{gates:#?}");
        assert!(gates.iter().all(|event| event["state"] == "passed"));
        assert_eq!(gates[0]["role"], "scout");
        assert_eq!(gates[0]["blocked_role"], "implementer");
        assert_eq!(gates[3]["role"], "verifier");
        assert_eq!(gates[3]["blocked_role"], "release_lead");
        assert_eq!(gates[4]["role"], "release_lead");
        assert!(gates[4]["blocked_role"].is_null());

        let promoted = events
            .iter()
            .filter(|event| event["type"] == "handoff_promoted")
            .collect::<Vec<_>>();
        let consumed = events
            .iter()
            .filter(|event| event["type"] == "handoff_consumed")
            .collect::<Vec<_>>();
        let expected_handoffs = [
            ("scout", "implementer", "source_evidence"),
            ("implementer", "reviewer", "verification_plan"),
            ("reviewer", "verifier", "review_report"),
            ("verifier", "release_lead", "verification_report"),
        ];
        assert_eq!(promoted.len(), expected_handoffs.len(), "{promoted:#?}");
        assert_eq!(consumed.len(), expected_handoffs.len(), "{consumed:#?}");
        let artifact_ids = promoted
            .iter()
            .map(|event| {
                event["artifact_id"]
                    .as_str()
                    .filter(|id| id.starts_with("handoff_") && id.len() > "handoff_".len())
                    .expect("opaque non-empty handoff artifact id")
            })
            .collect::<std::collections::HashSet<_>>();
        assert_eq!(
            artifact_ids.len(),
            promoted.len(),
            "every promotion must have a unique artifact id: {promoted:#?}"
        );
        for (index, (from_role, to_role, kind)) in expected_handoffs.into_iter().enumerate() {
            assert_eq!(promoted[index]["from_role"], from_role);
            assert_eq!(promoted[index]["to_role"], to_role);
            assert_eq!(promoted[index]["kind"], kind);
            assert_eq!(promoted[index]["gate_id"], gates[index]["gate_id"]);
            assert_eq!(
                promoted[index]["producer_task_id"],
                started[index]["task_id"]
            );
            assert!(
                promoted[index].get("payload").is_none(),
                "{:#?}",
                promoted[index]
            );

            assert_eq!(
                consumed[index]["artifact_id"],
                promoted[index]["artifact_id"]
            );
            assert_eq!(consumed[index]["from_role"], from_role);
            assert_eq!(consumed[index]["to_role"], to_role);
            assert_eq!(consumed[index]["kind"], kind);
            assert_eq!(
                consumed[index]["consumer_task_id"],
                started[index + 1]["task_id"]
            );
            assert!(
                consumed[index].get("payload").is_none(),
                "{:#?}",
                consumed[index]
            );

            let producer_task_id = promoted[index]["producer_task_id"]
                .as_str()
                .expect("producer task id");
            let consumer_task_id = consumed[index]["consumer_task_id"]
                .as_str()
                .expect("consumer task id");
            let gate_id = promoted[index]["gate_id"].as_str().expect("gate id");
            let artifact_id = promoted[index]["artifact_id"]
                .as_str()
                .expect("artifact id");
            let task_completed_index = events
                .iter()
                .position(|event| {
                    event["type"] == "task_completed" && event["task_id"] == producer_task_id
                })
                .expect("producer completion receipt");
            let gate_updated_index = events
                .iter()
                .position(|event| event["type"] == "gate_updated" && event["gate_id"] == gate_id)
                .expect("gate update receipt");
            let promoted_index = events
                .iter()
                .position(|event| {
                    event["type"] == "handoff_promoted" && event["artifact_id"] == artifact_id
                })
                .expect("handoff promotion receipt");
            let consumer_started_index = events
                .iter()
                .position(|event| {
                    event["type"] == "task_started" && event["task_id"] == consumer_task_id
                })
                .expect("consumer start receipt");
            let consumed_index = events
                .iter()
                .position(|event| {
                    event["type"] == "handoff_consumed" && event["artifact_id"] == artifact_id
                })
                .expect("handoff consumption receipt");
            assert!(
                task_completed_index < gate_updated_index
                    && gate_updated_index < promoted_index
                    && promoted_index < consumer_started_index
                    && consumer_started_index < consumed_index,
                "causal receipt order must be task_completed -> gate_updated -> handoff_promoted -> task_started -> handoff_consumed: {events:#?}"
            );
        }
        let terminal_completed_receipt = events
            .iter()
            .any(|event| event["type"] == "run_completed" && event["status"] == "completed");
        assert!(terminal_completed_receipt, "{events:#?}");
    }

    #[tokio::test]
    async fn completion_from_manager_fails_closed_when_status_stays_running() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);

        let (completion, usage) =
            completion_from_manager(manager, "missing_agent", "fallback".to_string()).await;
        assert!(usage.is_none(), "fail-closed path carries no telemetry");
        match completion {
            TaskCompletion::Failed { message } => {
                assert!(
                    message.contains("did not report a terminal status"),
                    "{message}"
                );
            }
            other => panic!("expected timeout failure, got {other:?}"),
        }
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn task_completed_and_run_completed_carry_usage_telemetry() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, calls) = fake_chat_client("telemetry-output").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager,
        );
        let tool = WorkflowTool::new(runtime.manager.clone(), runtime);

        let run = tool
            .execute(
                json!({
                    "action": "run",
                    "script": r#"export default workflow({
                        "id": "telemetry-fixture",
                        "goal": "usage telemetry",
                        "nodes": [
                            {
                                "agent": {
                                    "id": "inspect",
                                    "prompt": "Inspect the code.",
                                    "agent_type": "review"
                                }
                            }
                        ]
                    });"#
                }),
                &ctx,
            )
            .await
            .expect("workflow run");
        let payload: Value = serde_json::from_str(&run.content).expect("run json");
        assert_eq!(payload["status"], "completed", "{payload}");
        assert_eq!(calls.load(Ordering::SeqCst), 1, "{payload}");

        let events = payload["events"].as_array().expect("typed events");
        let task_completed = events
            .iter()
            .find(|event| event["type"] == "task_completed")
            .expect("task_completed event");
        let usage = &task_completed["usage"];
        let input = usage["input_tokens"].as_u64().expect("worker input tokens");
        let output = usage["output_tokens"]
            .as_u64()
            .expect("worker output tokens");
        let total = usage["total_tokens"].as_u64().expect("worker total tokens");
        assert!(total >= input + output, "{task_completed}");
        assert!(
            usage["tool_calls"].as_u64().unwrap_or_default() >= 1,
            "{task_completed}"
        );
        assert!(usage["duration_ms"].is_u64(), "{task_completed}");
        // #4039: a row may only label tokens as provider-reported when the
        // worker ledger actually received them.
        assert_eq!(
            usage["token_source"], "provider_reported",
            "{task_completed}"
        );
        assert!(
            usage["result_ref"]
                .as_str()
                .is_some_and(|target| target.starts_with("agent:")),
            "{task_completed}"
        );

        // Run totals reconcile exactly with the per-task telemetry.
        let run_completed = events
            .iter()
            .find(|event| event["type"] == "run_completed")
            .expect("run_completed event");
        let run_usage = &run_completed["usage"];
        assert_eq!(run_usage["total_tokens"], total, "{run_completed}");
        assert_eq!(run_usage["input_tokens"], input, "{run_completed}");
        assert_eq!(run_usage["output_tokens"], output, "{run_completed}");
        assert_eq!(
            run_usage["tool_calls"], usage["tool_calls"],
            "{run_completed}"
        );
        assert_eq!(run_usage["tasks_reported"], 1, "{run_completed}");

        // Totals also land on the persisted record and execution receipt.
        assert_eq!(payload["usage"]["total_tokens"], total, "{payload}");
        assert_eq!(
            payload["execution"]["usage"]["input_tokens"], input,
            "{payload}"
        );
        assert_eq!(
            payload["execution"]["leaf_results"][0]["usage"]["input_tokens"], input,
            "{payload}"
        );
    }

    #[test]
    fn provider_usage_presence_preserves_a_real_zero_receipt() {
        assert!(!provider_usage_was_reported(None, None, None));
        assert!(provider_usage_was_reported(Some(0), Some(0), Some(0)));
        assert!(provider_usage_was_reported(None, Some(0), None));
    }

    #[test]
    fn run_usage_totals_reconcile_task_telemetry() {
        let task_usage = |total: u64, calls: u32| WorkflowTaskUsage {
            input_tokens: Some(total / 2),
            output_tokens: Some(total - total / 2),
            total_tokens: Some(total),
            cost_microusd: Some(total),
            tool_calls: Some(calls),
            duration_ms: Some(7),
            result_ref: None,
            token_source: Some(WorkflowTokenSource::ProviderReported),
        };
        let record = |agent_id: &str, usage: Option<WorkflowTaskUsage>| RuntimeTaskRecord {
            agent_id: agent_id.to_string(),
            label: None,
            role: None,
            status: IrWorkflowRunStatus::Succeeded,
            output: None,
            schema_error: None,
            usage,
        };
        let records = vec![
            record("a", Some(task_usage(100, 2))),
            record("b", Some(task_usage(60, 1))),
            record("c", None),
        ];
        let totals = run_usage_totals(&records).expect("totals");
        assert_eq!(totals.total_tokens, Some(160));
        assert_eq!(totals.cost_microusd, Some(160));
        assert_eq!(totals.input_tokens, Some(80));
        assert_eq!(totals.output_tokens, Some(80));
        assert_eq!(totals.tool_calls, Some(3));
        assert_eq!(totals.tasks_reported, 2);

        assert!(run_usage_totals(&[]).is_none());
        assert!(run_usage_totals(&[record("d", None)]).is_none());
    }

    #[test]
    fn run_and_ir_usage_keep_unknown_distinct_from_reported_zero() {
        let record = |agent_id: &str, usage: WorkflowTaskUsage| RuntimeTaskRecord {
            agent_id: agent_id.to_string(),
            label: Some(agent_id.to_string()),
            role: None,
            status: IrWorkflowRunStatus::Succeeded,
            output: None,
            schema_error: None,
            usage: Some(usage),
        };
        let unknown = WorkflowTaskUsage {
            tool_calls: Some(1),
            duration_ms: Some(4),
            ..WorkflowTaskUsage::default()
        };
        let reported_zero = WorkflowTaskUsage {
            input_tokens: Some(0),
            output_tokens: Some(0),
            total_tokens: Some(0),
            cost_microusd: Some(0),
            tool_calls: Some(0),
            duration_ms: Some(0),
            token_source: Some(WorkflowTokenSource::ProviderReported),
            ..WorkflowTaskUsage::default()
        };

        let unknown_totals = run_usage_totals(&[record("unknown", unknown.clone())])
            .expect("tool/duration receipt still creates run usage");
        assert_eq!(unknown_totals.input_tokens, None);
        assert_eq!(unknown_totals.output_tokens, None);
        assert_eq!(unknown_totals.total_tokens, None);
        assert_eq!(unknown_totals.tool_calls, Some(1));

        let zero_totals = run_usage_totals(&[record("zero", reported_zero.clone())])
            .expect("reported zero receipt");
        assert_eq!(zero_totals.input_tokens, Some(0));
        assert_eq!(zero_totals.output_tokens, Some(0));
        assert_eq!(zero_totals.total_tokens, Some(0));
        assert_eq!(zero_totals.cost_microusd, Some(0));
        assert_eq!(zero_totals.tool_calls, Some(0));

        let unknown_ir = workflow_usage_from_task(&unknown);
        assert_eq!(unknown_ir.input_tokens, None);
        assert_eq!(unknown_ir.output_tokens, None);
        assert_eq!(unknown_ir.cost_microusd, None);
        let zero_ir = workflow_usage_from_task(&reported_zero);
        assert_eq!(zero_ir.input_tokens, Some(0));
        assert_eq!(zero_ir.output_tokens, Some(0));
        assert_eq!(zero_ir.cost_microusd, Some(0));

        let mixed = run_usage_totals(&[record("zero", reported_zero), record("unknown", unknown)])
            .expect("mixed receipts");
        assert_eq!(
            mixed.total_tokens,
            Some(0),
            "a missing contributor keeps the observed subtotal"
        );
        assert_eq!(mixed.input_tokens, Some(0));
        assert_eq!(mixed.output_tokens, Some(0));
        assert_eq!(mixed.cost_microusd, Some(0));
        assert_eq!(mixed.tool_calls, Some(1));
    }

    #[test]
    fn workflow_ui_event_usage_telemetry_serde_round_trip() {
        let event = WorkflowUiEvent::at(
            7,
            WorkflowUiEventKind::TaskCompleted {
                task_id: "child-1".to_string(),
                status: IrWorkflowRunStatus::Succeeded,
                usage: Some(WorkflowTaskUsage {
                    input_tokens: Some(128),
                    output_tokens: Some(32),
                    total_tokens: Some(160),
                    cost_microusd: Some(42),
                    tool_calls: Some(2),
                    duration_ms: Some(42),
                    result_ref: Some("agent:child-1".to_string()),
                    token_source: Some(WorkflowTokenSource::ProviderReported),
                }),
            },
        );
        let json = serde_json::to_value(&event).expect("serialize");
        assert_eq!(json["usage"]["total_tokens"], 160);
        let parsed: WorkflowUiEvent = serde_json::from_value(json).expect("deserialize round trip");
        match parsed.kind {
            WorkflowUiEventKind::TaskCompleted {
                usage: Some(usage), ..
            } => {
                assert_eq!(usage.total_tokens, Some(160));
                assert_eq!(usage.cost_microusd, Some(42));
                assert_eq!(usage.tool_calls, Some(2));
                assert_eq!(usage.duration_ms, Some(42));
            }
            other => panic!("expected task_completed with usage, got {other:?}"),
        }

        // Journals written before #2974 carry no usage fields; they must
        // still parse with `usage == None`.
        let legacy_task: WorkflowUiEvent = serde_json::from_str(
            r#"{"at_ms":5,"type":"task_completed","task_id":"child-1","status":"succeeded"}"#,
        )
        .expect("legacy task_completed parses");
        match legacy_task.kind {
            WorkflowUiEventKind::TaskCompleted { usage: None, .. } => {}
            other => panic!("expected legacy task_completed without usage, got {other:?}"),
        }
        let legacy_run: WorkflowUiEvent = serde_json::from_str(
            r#"{"at_ms":6,"type":"run_completed","status":"completed","error":null}"#,
        )
        .expect("legacy run_completed parses");
        match legacy_run.kind {
            WorkflowUiEventKind::RunCompleted { usage: None, .. } => {}
            other => panic!("expected legacy run_completed without usage, got {other:?}"),
        }

        // A telemetry-less event serializes without a `usage` key, so old
        // consumers see a byte-compatible shape.
        let plain = serde_json::to_value(WorkflowUiEvent::at(
            8,
            WorkflowUiEventKind::RunCompleted {
                status: WorkflowRunStatus::Completed,
                error: None,
                usage: None,
            },
        ))
        .expect("serialize plain run_completed");
        assert!(plain.get("usage").is_none(), "{plain}");
    }

    #[test]
    fn run_record_event_retention_is_bounded() {
        let mut record = WorkflowRunRecord::new("workflow_tail".to_string(), None, None, None);
        for index in 0..(WORKFLOW_RUN_EVENTS_MAX_RETAINED + 5) {
            record.push_event(WorkflowUiEvent::at(
                index as u64,
                WorkflowUiEventKind::Log {
                    message: format!("log {index}"),
                },
            ));
        }
        assert_eq!(record.events.len(), WORKFLOW_RUN_EVENTS_MAX_RETAINED);
        assert_eq!(record.events_dropped, 5);
        assert_eq!(
            record.events_total,
            (WORKFLOW_RUN_EVENTS_MAX_RETAINED + 5) as u64
        );
        // The retained window is the newest tail.
        let first = &record.events[0];
        assert_eq!(first.at_ms, 5);
        // Summaries report the truthful total, not the retained tail length.
        let summary = record.summary();
        assert_eq!(summary.event_count, WORKFLOW_RUN_EVENTS_MAX_RETAINED + 5);
        assert_eq!(summary.events_dropped, 5);
        assert_eq!(summary.last_event_type.as_deref(), Some("log"));
    }

    #[test]
    fn workflow_status_payload_bounds_oversized_run_records() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let state = WorkflowWorkspaceState::open(tmp.path());
        let run_id = "workflow_big_run".to_string();
        let mut record = WorkflowRunRecord::new(run_id.clone(), None, None, None);
        record.status = WorkflowRunStatus::Completed;
        // A high-fan-out run: far more events/progress than the model needs.
        for index in 0..200u64 {
            record.push_event(WorkflowUiEvent::at(
                index,
                WorkflowUiEventKind::Log {
                    message: format!("fan-out event {index}"),
                },
            ));
        }
        for index in 0..60 {
            record.progress.push(format!("progress line {index}"));
        }
        for index in 0..40u64 {
            record.dispatch_failures.push(WorkflowDispatchFailure {
                at_ms: index,
                label: Some(format!("rejected-{index}")),
                phase: Some("fan-out".to_string()),
                message: format!("dispatch rejected {index}: {}", "x".repeat(2_000)),
            });
        }
        record.result = Some(json!({ "blob": "r".repeat(10_000) }));
        record.execution = Some(IrWorkflowExecution {
            status: IrWorkflowRunStatus::Succeeded,
            usage: WorkflowUsage::default(),
            memo_usage: WorkflowMemoUsage::default(),
            leaf_results: vec![LeafResult {
                leaf_id: "inspect".to_string(),
                task_id: "agent_1".to_string(),
                role: None,
                profile: None,
                status: IrWorkflowRunStatus::Succeeded,
                usage: WorkflowUsage::default(),
                memo_usage: WorkflowMemoUsage::default(),
                output: Some("o".repeat(5_000)),
                artifacts: Vec::new(),
                schema_error: None,
            }],
            branch_results: Vec::new(),
            control_node_results: Vec::new(),
        });
        state
            .runs
            .lock()
            .expect("runs")
            .insert(run_id.clone(), record);

        let result = workflow_result_for(&run_id, state).expect("status result");
        assert!(
            result.content.len() < WORKFLOW_RESULT_MAX_CHARS,
            "bounded payload must stay under {WORKFLOW_RESULT_MAX_CHARS} chars, got {}",
            result.content.len()
        );
        let payload: Value = serde_json::from_str(&result.content).expect("payload json");

        let events = payload["events"].as_array().expect("events");
        assert_eq!(events.len(), WORKFLOW_RESULT_EVENTS_TAIL, "{payload}");
        assert!(
            payload["events_note"]
                .as_str()
                .is_some_and(|note| note.contains("workflow-runs.jsonl")),
            "{payload}"
        );
        // The retained window is the newest events.
        assert_eq!(events[0]["at_ms"], 150);

        let progress = payload["progress"].as_array().expect("progress");
        assert_eq!(progress.len(), WORKFLOW_RESULT_PROGRESS_TAIL, "{payload}");
        assert!(payload.get("progress_note").is_some(), "{payload}");

        let dispatch_failures = payload["dispatch_failures"]
            .as_array()
            .expect("dispatch failures");
        assert_eq!(
            dispatch_failures.len(),
            WORKFLOW_RESULT_DISPATCH_FAILURES_TAIL,
            "{payload}"
        );
        assert_eq!(dispatch_failures[0]["at_ms"], 28);
        assert!(
            dispatch_failures.iter().all(|failure| failure["message"]
                .as_str()
                .is_some_and(|message| message.chars().count()
                    <= WORKFLOW_RESULT_DISPATCH_FAILURE_FIELD_MAX_CHARS)),
            "{dispatch_failures:?}"
        );
        assert!(
            payload["dispatch_failures_note"]
                .as_str()
                .is_some_and(|note| note.contains("workflow-runs.jsonl")),
            "{payload}"
        );

        // Oversized VM result collapses to a preview with a journal pointer.
        assert_eq!(payload["result"]["truncated"], true, "{payload}");
        assert!(
            payload["result"]["preview"]
                .as_str()
                .is_some_and(|preview| preview.chars().count() <= WORKFLOW_RESULT_VALUE_MAX_CHARS),
            "{payload}"
        );
        assert!(
            payload["result"]["full_detail"]
                .as_str()
                .is_some_and(|path| path.contains("workflow-runs.jsonl")),
            "{payload}"
        );

        // Leaf outputs carry a bounded preview instead of full child text.
        let leaf_output = payload["execution"]["leaf_results"][0]["output"]
            .as_str()
            .expect("leaf output");
        assert!(
            leaf_output.contains("leaf output truncated"),
            "{leaf_output}"
        );
        assert!(leaf_output.len() < 1_000, "{leaf_output}");

        let metadata = result.metadata.expect("metadata");
        assert_eq!(metadata["events_returned"], WORKFLOW_RESULT_EVENTS_TAIL);
        assert_eq!(metadata["events_omitted"], 150);
        assert_eq!(metadata["event_count"], 200);
        assert_eq!(
            metadata["dispatch_failures_returned"],
            WORKFLOW_RESULT_DISPATCH_FAILURES_TAIL
        );
        assert_eq!(metadata["dispatch_failures_omitted"], 28);
        assert_eq!(metadata["truncated"], true);
        assert!(
            metadata["journal_path"]
                .as_str()
                .is_some_and(|path| path.contains("workflow-runs.jsonl")),
            "{metadata}"
        );
    }

    #[test]
    fn workflow_status_payload_keeps_small_records_intact() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let state = WorkflowWorkspaceState::open(tmp.path());
        let run_id = "workflow_small_run".to_string();
        let mut record = WorkflowRunRecord::new(run_id.clone(), None, None, None);
        record.status = WorkflowRunStatus::Completed;
        record.push_event(WorkflowUiEvent::at(
            1,
            WorkflowUiEventKind::PhaseStarted {
                title: "scan".to_string(),
            },
        ));
        record.result = Some(json!({ "ok": true }));
        state
            .runs
            .lock()
            .expect("runs")
            .insert(run_id.clone(), record);

        let result = workflow_result_for(&run_id, state).expect("status result");
        let payload: Value = serde_json::from_str(&result.content).expect("payload json");
        assert_eq!(payload["events"].as_array().map(Vec::len), Some(1));
        assert_eq!(payload["result"], json!({ "ok": true }));
        assert!(payload.get("events_note").is_none(), "{payload}");
        assert!(payload.get("progress_note").is_none(), "{payload}");
        let metadata = result.metadata.expect("metadata");
        assert_eq!(metadata["truncated"], false);
        assert_eq!(metadata["events_omitted"], 0);
        assert_eq!(metadata["events_returned"], 1);
    }
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn workflow_cancel_interrupts_vm_and_blocks_further_spawns() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 4);
        let (client, calls) = fake_chat_client("child done").await;
        let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(256);
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            Some(event_tx),
            manager.clone(),
        );
        let tool = WorkflowTool::new(manager.clone(), runtime);

        let started = tool
            .execute(
                json!({
                    "action": "start",
                    "script": r#"
                        let n = 0;
                        while (n < 20) {
                            await task({ description: `task ${n}`, type: 'explore', allowedTools: [] });
                            n++;
                        }
                        return n;
                    "#
                }),
                &ctx,
            )
            .await
            .expect("workflow start");
        let run_id = started
            .metadata
            .as_ref()
            .and_then(|metadata| metadata.get("run_id"))
            .and_then(Value::as_str)
            .expect("run_id metadata");

        tokio::time::timeout(std::time::Duration::from_secs(3), async {
            while calls.load(Ordering::SeqCst) == 0 {
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("workflow should spawn at least one child before cancel");
        let calls_before_cancel = calls.load(Ordering::SeqCst);
        assert!(calls_before_cancel >= 1);

        let cancelled = tool
            .execute(json!({"action": "cancel", "run_id": run_id}), &ctx)
            .await
            .expect("workflow cancel");
        let cancelled_payload: Value =
            serde_json::from_str(&cancelled.content).expect("cancel json");
        assert_eq!(cancelled_payload["status"], "cancelled");
        assert!(
            cancelled_payload["events"]
                .as_array()
                .is_some_and(|events| events.iter().any(|event| event["type"] == "run_cancelled")),
            "cancel receipt must include the authoritative terminal event: {cancelled_payload}"
        );
        let mut streamed_cancel = false;
        while let Ok(event) = event_rx.try_recv() {
            if let Event::WorkflowUi { event, .. } = event
                && event["type"] == "run_cancelled"
            {
                streamed_cancel = true;
            }
        }
        assert!(
            streamed_cancel,
            "cancel must stream a terminal UI event after any racing completion"
        );
        let first_event_count = cancelled_payload["events"]
            .as_array()
            .expect("events")
            .len();
        let first_completed_at = cancelled_payload["completed_at_ms"].clone();
        let cancelled_again = tool
            .execute(json!({"action": "cancel", "run_id": run_id}), &ctx)
            .await
            .expect("second workflow cancel is a no-op");
        let cancelled_again_payload: Value =
            serde_json::from_str(&cancelled_again.content).expect("second cancel json");
        assert_eq!(cancelled_again_payload["status"], "cancelled");
        assert_eq!(
            cancelled_again_payload["events"]
                .as_array()
                .expect("events")
                .len(),
            first_event_count,
            "second cancel must not append a duplicate terminal event"
        );
        assert_eq!(
            cancelled_again_payload["completed_at_ms"], first_completed_at,
            "second cancel must preserve the original completion time"
        );

        tokio::time::sleep(std::time::Duration::from_millis(700)).await;
        let calls_after_cancel = calls.load(Ordering::SeqCst);
        assert!(
            calls_after_cancel <= calls_before_cancel + 1,
            "cancelled workflow kept spawning children: before={calls_before_cancel} after={calls_after_cancel}"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn workflow_budget_spent_delegates_to_manager_scope() {
        let _retry_guard = workflow_test_retry_guard();
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (client, _calls) = fake_chat_client("budgeted").await;
        let runtime = SubAgentRuntime::new(
            client,
            "deepseek-v4-flash".to_string(),
            ctx.clone(),
            true,
            None,
            manager.clone(),
        );
        let tool = WorkflowTool::new(manager.clone(), runtime);

        let result = tool
            .execute(
                json!({
                    "action": "run",
                    "token_budget": 1000,
                    "script": r#"
                        await task({ description: 'budgeted work', type: 'explore', allowedTools: [] });
                        return { spent: budget.spent(), total: budget.total, remaining: budget.remaining() };
                    "#
                }),
                &ctx,
            )
            .await
            .expect("budget workflow should complete");
        let payload: Value = serde_json::from_str(&result.content).expect("json result");

        assert_eq!(payload["status"], "completed", "{payload}");
        assert_eq!(payload["result"]["spent"], 2);
        assert_eq!(payload["result"]["total"], 1000);
        assert_eq!(payload["result"]["remaining"], 998);
    }

    #[tokio::test]
    async fn identical_budget_snapshots_emit_a_live_heartbeat_without_journal_duplication() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let ctx = ToolContext::new(tmp.path().to_path_buf());
        let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
        let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(8);
        let runtime = SubAgentRuntime::new(
            stub_client(),
            "deepseek-v4-flash".to_string(),
            ctx,
            true,
            Some(event_tx),
            manager.clone(),
        );
        let state = WorkflowWorkspaceState::open(tmp.path());
        let run_id = "workflow_budget_heartbeat".to_string();
        state.runs.lock().expect("runs").insert(
            run_id.clone(),
            WorkflowRunRecord::new(run_id.clone(), None, None, None),
        );
        let driver = SubAgentWorkflowDriver::new(
            run_id.clone(),
            manager,
            runtime,
            state.clone(),
            Some(1_000),
            WorkflowFleetBinding::None,
            Vec::new(),
        );
        let snapshot = BudgetSnapshot {
            total: Some(1_000),
            spent: 0,
        };

        driver.record_budget_snapshot(snapshot);
        driver.record_budget_snapshot(snapshot);

        let mut streamed = 0;
        while let Ok(Event::WorkflowUi { event, .. }) = event_rx.try_recv() {
            if event["type"] == "budget_updated" {
                streamed += 1;
            }
        }
        assert_eq!(
            streamed, 2,
            "unchanged budget still refreshes the live panel"
        );
        let recorded = state
            .runs
            .lock()
            .expect("runs")
            .get(&run_id)
            .expect("run")
            .events
            .iter()
            .filter(|event| event.event_type() == "budget_updated")
            .count();
        assert_eq!(recorded, 1, "heartbeat must not grow the durable journal");
    }

    fn stub_client() -> DeepSeekClient {
        let _ = rustls::crypto::ring::default_provider().install_default();
        let config = crate::config::Config {
            api_key: Some("test-key".to_string()),
            ..crate::config::Config::default()
        };
        DeepSeekClient::new(&config).expect("stub client should construct")
    }

    async fn fake_chat_client(response_text: &str) -> (DeepSeekClient, Arc<AtomicUsize>) {
        let (client, calls, _) = fake_chat_client_capturing(response_text).await;
        (client, calls)
    }

    async fn fake_chat_client_responses(
        response_texts: &[&str],
    ) -> (DeepSeekClient, Arc<AtomicUsize>) {
        let (client, calls, _) = fake_chat_client_capturing_responses(response_texts).await;
        (client, calls)
    }

    async fn fake_chat_client_capturing(
        response_text: &str,
    ) -> (DeepSeekClient, Arc<AtomicUsize>, Arc<Mutex<Vec<Value>>>) {
        fake_chat_client_capturing_responses(&[response_text]).await
    }

    async fn fake_chat_client_capturing_responses(
        response_texts: &[&str],
    ) -> (DeepSeekClient, Arc<AtomicUsize>, Arc<Mutex<Vec<Value>>>) {
        assert!(
            !response_texts.is_empty(),
            "fake chat client needs at least one response"
        );
        let calls = Arc::new(AtomicUsize::new(0));
        let bodies = Arc::new(Mutex::new(Vec::new()));
        let response_texts = Arc::new(
            response_texts
                .iter()
                .map(|response| (*response).to_string())
                .collect::<Vec<_>>(),
        );
        let app = Router::new().route(
            "/{*path}",
            post({
                let calls = Arc::clone(&calls);
                let bodies = Arc::clone(&bodies);
                let response_texts = Arc::clone(&response_texts);
                move |Json(body): Json<Value>| {
                    let calls = Arc::clone(&calls);
                    let bodies = Arc::clone(&bodies);
                    let response_texts = Arc::clone(&response_texts);
                    async move {
                        bodies.lock().expect("capture body").push(body);
                        let attempt = calls.fetch_add(1, Ordering::SeqCst) + 1;
                        let response_text = if response_texts.len() == 1 {
                            response_texts[0].clone()
                        } else {
                            response_texts
                                .get(attempt - 1)
                                .unwrap_or_else(|| {
                                    panic!(
                                        "fake chat server received call {attempt} but only {} responses were supplied",
                                        response_texts.len()
                                    )
                                })
                                .clone()
                        };
                        Json(json!({
                            "id": format!("chatcmpl-workflow-test-{attempt}"),
                            "model": "deepseek-v4-flash",
                            "choices": [{
                                "index": 0,
                                "message": {
                                    "role": "assistant",
                                    "content": response_text
                                },
                                "finish_reason": "stop"
                            }],
                            "usage": {
                                "prompt_tokens": 1,
                                "completion_tokens": 1,
                                "total_tokens": 2
                            }
                        }))
                    }
                }
            }),
        );

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind fake chat server");
        let addr = listener.local_addr().expect("fake chat server addr");
        tokio::spawn(async move {
            let _ = axum::serve(listener, app).await;
        });

        let config = crate::config::Config {
            api_key: Some("test-key".to_string()),
            base_url: Some(format!("http://{addr}/v1")),
            ..crate::config::Config::default()
        };
        (
            DeepSeekClient::new(&config).expect("fake chat client"),
            calls,
            bodies,
        )
    }

    fn workflow_test_retry_guard() -> std::sync::MutexGuard<'static, ()> {
        let guard = crate::retry_status::test_guard();
        crate::retry_status::clear();
        crate::retry_status::clear_rate_limit();
        guard
    }
}