zeph-orchestration 0.22.3

Task orchestration: DAG execution, failure propagation, and persistence for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Unit tests for the orchestration scheduler tick loop.

use std::time::Duration;

use super::*;
use crate::scheduler::tests::*;
use crate::verifier::ToolCallSummary;

#[test]
fn test_tick_produces_spawn_for_ready() {
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut scheduler = make_scheduler(graph);
    let actions = scheduler.tick();
    let spawns: Vec<_> = actions
        .iter()
        .filter(|a| matches!(a, SchedulerAction::Spawn { .. }))
        .collect();
    assert_eq!(spawns.len(), 2);
}

#[test]
fn test_tick_dispatches_all_regardless_of_max_parallel() {
    // tick() enforces max_parallel as a pre-dispatch cap.
    // With 5 independent tasks and max_parallel=2, only 2 are dispatched per tick.
    let graph = graph_from_nodes(vec![
        make_node(0, &[]),
        make_node(1, &[]),
        make_node(2, &[]),
        make_node(3, &[]),
        make_node(4, &[]),
    ]);
    let mut config = make_config();
    config.max_parallel = 2;
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();
    let actions = scheduler.tick();
    let spawn_count = actions
        .iter()
        .filter(|a| matches!(a, SchedulerAction::Spawn { .. }))
        .count();
    assert_eq!(
        spawn_count, 2,
        "max_parallel=2 caps dispatched tasks per tick"
    );
}

#[test]
fn test_tick_detects_completion() {
    let mut graph = graph_from_nodes(vec![make_node(0, &[])]);
    graph.tasks[0].status = TaskStatus::Completed;
    let config = make_config();
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();
    // Manually set graph to Running since new() validated Created status
    // — but all tasks are terminal. tick() should detect completion.
    let actions = scheduler.tick();
    let has_done = actions.iter().any(|a| {
        matches!(
            a,
            SchedulerAction::Done {
                status: GraphStatus::Completed
            }
        )
    });
    assert!(
        has_done,
        "should emit Done(Completed) when all tasks are terminal"
    );
}

#[test]
fn test_completion_event_marks_deps_ready() {
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[0])]);
    let mut scheduler = make_scheduler(graph);

    // Simulate task 0 running.
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "handle-0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let event = TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "handle-0".to_string(),
        outcome: TaskOutcome::Completed {
            output: "done".to_string(),
            artifacts: vec![],
            tool_trace: None,
        },
    };
    scheduler.buffered_events.push_back(event);

    let actions = scheduler.tick();
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Completed);
    // Task 1 should now be Ready or Spawn action emitted.
    let has_spawn_1 = actions
        .iter()
        .any(|a| matches!(a, SchedulerAction::Spawn { task_id, .. } if *task_id == TaskId(1)));
    assert!(
        has_spawn_1 || scheduler.graph.tasks[1].status == TaskStatus::Ready,
        "task 1 should be spawned or marked Ready"
    );
}

#[test]
fn test_handoff_event_marks_source_completed_and_activates_target() {
    // spec-080 (#6363) integration coverage: dag.rs's try_handoff tests exercise the pure
    // routing function directly, and scheduler_loop.rs's determine_task_outcome tests
    // exercise the zeph-core produce-side seam directly, but neither drives a real
    // TaskOutcome::Handoff through the tick()/process_event loop that connects them
    // (handle_handoff_outcome). This closes that gap: verifies the emitting node becomes
    // terminal Completed, the goto target activates with commanded_from set, the per-graph
    // handoff budget increments, and the target is dispatched/marked Ready in the same tick
    // (mirrors test_completion_event_marks_deps_ready above for the ordinary Completed path).
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "handle-0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    scheduler.buffered_events.push_back(TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "handle-0".to_string(),
        outcome: TaskOutcome::Handoff {
            output: "handing off".to_string(),
            goto: TaskRef::ById(TaskId(1)),
            tool_trace: None,
        },
    });

    let actions = scheduler.tick();

    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Completed);
    assert_eq!(
        scheduler.graph.tasks[0]
            .result
            .as_ref()
            .map(|r| r.output.as_str()),
        Some("handing off"),
        "the source node's own output must be preserved on the Handoff outcome"
    );
    assert_eq!(scheduler.graph.tasks[1].commanded_from, Some(TaskId(0)));
    assert_eq!(scheduler.graph.handoff_count, 1);
    assert!(
        scheduler.graph.tasks[0].handoff_rejected.is_none(),
        "a successful handoff must not set the rejection signal"
    );
    let has_spawn_1 = actions
        .iter()
        .any(|a| matches!(a, SchedulerAction::Spawn { task_id, .. } if *task_id == TaskId(1)));
    assert!(
        has_spawn_1 || scheduler.graph.tasks[1].status == TaskStatus::Ready,
        "handoff target should be spawned or marked Ready in the same tick"
    );
}

#[test]
fn test_handoff_event_rejection_leaves_source_completed_not_failed() {
    // spec-080 FR-B-006: a try_handoff rejection (forward-only violation, unsatisfied
    // deps, live route_to reservation, exhausted budget) must not escalate the emitting
    // node's own outcome to Failed -- it stays Completed with its real output preserved,
    // only the extra routing fails to activate. Exercised here via the full tick loop
    // (not dag::try_handoff in isolation) so the actual event-handling call site is
    // proven to honor this, not just the pure function.
    let mut graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    graph.tasks[1].status = TaskStatus::Completed; // forward-only rejection target
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "handle-0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    scheduler.buffered_events.push_back(TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "handle-0".to_string(),
        outcome: TaskOutcome::Handoff {
            output: "handing off".to_string(),
            goto: TaskRef::ById(TaskId(1)),
            tool_trace: None,
        },
    });

    let actions = scheduler.tick();

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Completed,
        "a rejected handoff must not escalate the source node to Failed"
    );
    assert_eq!(
        scheduler.graph.handoff_count, 0,
        "a rejected handoff must not consume the budget"
    );
    assert!(
        scheduler.graph.tasks[0].handoff_rejected.is_some(),
        "critic finding C1: a rejected handoff must be recorded as a graph-visible, \
         persisted signal, not just a log line"
    );
    // Tester Gap 2 (2026-07-17): the CheckToolOutcome/Verify action-emission block runs
    // unconditionally after the try_handoff match (both Ok and Err arms fall through to
    // the same trailing code, tick/mod.rs) -- prove that on the actual returned actions,
    // not just by code inspection, so a rejected handoff still gets the same completeness
    // treatment as an accepted one.
    assert!(
        actions.iter().any(|a| matches!(
            a,
            SchedulerAction::CheckToolOutcome { task_id, .. } if *task_id == TaskId(0)
        )),
        "CheckToolOutcome must still be emitted for a rejected handoff's own task_id: \
         {actions:?}"
    );
}

#[test]
fn test_handoff_event_emits_check_tool_outcome_action() {
    // #6394: a Handoff outcome must get the same deterministic tool-outcome check an
    // ordinary Completed outcome gets — unconditionally, not gated on verify_completeness.
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "handle-0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    scheduler.buffered_events.push_back(TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "handle-0".to_string(),
        outcome: TaskOutcome::Handoff {
            output: "handing off".to_string(),
            goto: TaskRef::ById(TaskId(1)),
            tool_trace: None,
        },
    });

    let actions = scheduler.tick();

    let has_check = actions.iter().any(|a| {
        matches!(
            a,
            SchedulerAction::CheckToolOutcome { task_id, .. } if *task_id == TaskId(0)
        )
    });
    assert!(
        has_check,
        "a Handoff outcome must emit CheckToolOutcome for its own task_id (#6394)"
    );
    // Tester Gap 1 (2026-07-17): `make_scheduler`/`make_config` default
    // `verify_completeness` to `false` — prove the flag actually suppresses `Verify` for
    // the Handoff outcome too, not just that the enabled case (separately tested below)
    // emits it.
    assert!(
        !actions
            .iter()
            .any(|a| matches!(a, SchedulerAction::Verify { .. })),
        "Verify must NOT be emitted when verify_completeness is disabled (#6394): {actions:?}"
    );
}

#[test]
fn test_handoff_event_emits_verify_action_when_verify_completeness_enabled() {
    // #6394: with verify_completeness enabled, a Handoff outcome must also emit Verify,
    // mirroring handle_completed_outcome, carrying the handoff node's own output.
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut config = make_config();
    config.verify_completeness = true;
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "handle-0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    scheduler.buffered_events.push_back(TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "handle-0".to_string(),
        outcome: TaskOutcome::Handoff {
            output: "handing off".to_string(),
            goto: TaskRef::ById(TaskId(1)),
            tool_trace: None,
        },
    });

    let actions = scheduler.tick();

    let verify_output = actions.iter().find_map(|a| match a {
        SchedulerAction::Verify {
            task_id, output, ..
        } if *task_id == TaskId(0) => Some(output.clone()),
        _ => None,
    });
    assert_eq!(
        verify_output.as_deref(),
        Some("handing off"),
        "Verify must be emitted for the handoff node and carry its own output (#6394)"
    );
}

#[test]
fn test_handoff_event_all_tools_failed_marks_task_failed_not_handoff() {
    // #6394/#6380/#6397 parity: a Command-handoff node whose synchronously-known
    // (RunInline) tool trace shows every call failed or was policy-blocked must not be
    // allowed to route anywhere — the "I'm done, go to X" claim is bogus, so it is routed
    // to handle_failed_outcome before any Handoff side effect (cascade record,
    // try_handoff activation) runs, mirroring handle_completed_outcome's early branch.
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "handle-0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    scheduler.buffered_events.push_back(TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "handle-0".to_string(),
        outcome: TaskOutcome::Handoff {
            output: "claiming completion".to_string(),
            goto: TaskRef::ById(TaskId(1)),
            tool_trace: Some(vec![ToolCallSummary {
                tool: "write".to_string(),
                args_summary: None,
                ok: false,
                is_read_only: false,
            }]),
        },
    });

    scheduler.tick();

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Failed,
        "a Handoff outcome with an all-failed tool trace must be Failed, not Completed"
    );
    assert!(
        scheduler.graph.tasks[1].commanded_from.is_none(),
        "try_handoff must never run when the handoff node itself is corrected to Failed"
    );
    assert_eq!(
        scheduler.graph.handoff_count, 0,
        "no handoff budget must be consumed when the outcome is corrected to Failed"
    );
    assert!(
        scheduler.graph.tasks[0].handoff_rejected.is_none(),
        "handoff_rejected is a try_handoff-rejection signal, not used for the \
         all-tool-calls-failed short-circuit"
    );
}

#[cfg(feature = "llm-planning")]
#[test]
fn test_plan_with_verify_criteria_and_predicate_disabled_reaches_completed() {
    // End-to-end regression for #5403: a planner response where a task has a
    // verify_criteria acceptance check and a downstream dependent, converted with
    // verify_predicate_enabled = false (the reported bug's default config), must
    // dispatch the dependent once the parent completes and drive the graph to
    // GraphStatus::Completed instead of a false scheduler deadlock.
    use crate::graph::PlanSlug;
    use crate::planner::{PlannedTask, PlannerResponse, convert_response_pub};

    let response = PlannerResponse {
        tasks: vec![
            PlannedTask {
                task_id: PlanSlug::from("parent"),
                title: "Parent".to_string(),
                description: "do parent work".to_string(),
                agent_hint: None,
                depends_on: vec![],
                failure_strategy: None,
                execution_mode: None,
                verify_criteria: Some("output must be valid JSON".to_string()),
                tool_allowlist: None,
            },
            PlannedTask {
                task_id: PlanSlug::from("child"),
                title: "Child".to_string(),
                description: "do child work".to_string(),
                agent_hint: None,
                depends_on: vec![PlanSlug::from("parent")],
                failure_strategy: None,
                execution_mode: None,
                verify_criteria: None,
                tool_allowlist: None,
            },
        ],
    };
    let graph = convert_response_pub(response, "goal", &[make_def("worker")], 20, false).unwrap();
    assert!(
        graph.tasks[0].verify_predicate.is_none(),
        "verify_predicate must be dropped when verify_predicate_enabled is false"
    );

    let mut scheduler = make_scheduler(graph);

    // Tick 1: parent has no dependencies, should be dispatched.
    let actions = scheduler.tick();
    assert!(
        actions
            .iter()
            .any(|a| matches!(a, SchedulerAction::Spawn { task_id, .. } if *task_id == TaskId(0)))
    );
    scheduler.record_spawn(
        TaskId(0),
        "handle-parent".to_string(),
        "worker".to_string(),
        None,
    );
    scheduler.buffered_events.push_back(TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "handle-parent".to_string(),
        outcome: TaskOutcome::Completed {
            output: "parent done".to_string(),
            artifacts: vec![],
            tool_trace: None,
        },
    });

    // Tick 2: parent completion processed; child must be dispatched, not blocked by a
    // dangling verify_predicate gate.
    let actions = scheduler.tick();
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Completed);
    assert!(
        actions
            .iter()
            .any(|a| matches!(a, SchedulerAction::Spawn { task_id, .. } if *task_id == TaskId(1))),
        "child must be dispatched once its only dependency completes"
    );
    scheduler.record_spawn(
        TaskId(1),
        "handle-child".to_string(),
        "worker".to_string(),
        None,
    );
    scheduler.buffered_events.push_back(TaskEvent {
        task_id: TaskId(1),
        agent_handle_id: "handle-child".to_string(),
        outcome: TaskOutcome::Completed {
            output: "child done".to_string(),
            artifacts: vec![],
            tool_trace: None,
        },
    });

    // Tick 3: graph must reach Completed, not a false deadlock/Failed.
    let actions = scheduler.tick();
    assert!(
        actions.iter().any(|a| matches!(
            a,
            SchedulerAction::Done {
                status: GraphStatus::Completed
            }
        )),
        "graph should complete successfully, not deadlock"
    );
    assert_eq!(scheduler.graph.status, GraphStatus::Completed);
}

#[test]
fn test_failure_abort_cancels_running() {
    let graph = graph_from_nodes(vec![
        make_node(0, &[]),
        make_node(1, &[]),
        make_node(2, &[0, 1]),
    ]);
    let mut scheduler = make_scheduler(graph);

    // Simulate tasks 0 and 1 running.
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );
    scheduler.graph.tasks[1].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(1),
        RunningTask {
            agent_handle_id: "h1".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    // Task 0 fails with default Abort strategy.
    let event = TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "h0".to_string(),
        outcome: TaskOutcome::Failed {
            error: "boom".to_string(),
        },
    };
    scheduler.buffered_events.push_back(event);

    let actions = scheduler.tick();
    assert_eq!(scheduler.graph.status, GraphStatus::Failed);
    let cancel_ids: Vec<_> = actions
        .iter()
        .filter_map(|a| {
            if let SchedulerAction::Cancel { agent_handle_id } = a {
                Some(agent_handle_id.as_str())
            } else {
                None
            }
        })
        .collect();
    assert!(cancel_ids.contains(&"h1"), "task 1 should be canceled");
    assert!(
        actions
            .iter()
            .any(|a| matches!(a, SchedulerAction::Done { .. }))
    );
}

#[test]
fn test_failure_skip_propagates() {
    use crate::graph::FailureStrategy;

    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[0])]);
    let mut scheduler = make_scheduler(graph);

    // Set failure strategy to Skip on task 0.
    scheduler.graph.tasks[0].failure_strategy = Some(FailureStrategy::Skip);
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let event = TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "h0".to_string(),
        outcome: TaskOutcome::Failed {
            error: "skip me".to_string(),
        },
    };
    scheduler.buffered_events.push_back(event);
    scheduler.tick();

    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Skipped);
    assert_eq!(scheduler.graph.tasks[1].status, TaskStatus::Skipped);
}

#[test]
fn test_failure_retry_reschedules() {
    use crate::graph::FailureStrategy;

    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].failure_strategy = Some(FailureStrategy::Retry);
    scheduler.graph.tasks[0].max_retries = Some(3);
    scheduler.graph.tasks[0].retry_count = 0;
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let event = TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "h0".to_string(),
        outcome: TaskOutcome::Failed {
            error: "transient".to_string(),
        },
    };
    scheduler.buffered_events.push_back(event);
    let actions = scheduler.tick();

    // Task should be rescheduled (Ready) and a Spawn action emitted.
    let has_spawn = actions
        .iter()
        .any(|a| matches!(a, SchedulerAction::Spawn { task_id, .. } if *task_id == TaskId(0)));
    assert!(
        has_spawn || scheduler.graph.tasks[0].status == TaskStatus::Ready,
        "retry should produce spawn or Ready status"
    );
    // retry_count incremented
    assert_eq!(scheduler.graph.tasks[0].retry_count, 1);
}

#[test]
fn test_process_event_failed_retry() {
    use crate::graph::FailureStrategy;

    // End-to-end: send Failed event, verify retry path produces Ready -> Spawn.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].failure_strategy = Some(FailureStrategy::Retry);
    scheduler.graph.tasks[0].max_retries = Some(2);
    scheduler.graph.tasks[0].retry_count = 0;
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let event = TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "h0".to_string(),
        outcome: TaskOutcome::Failed {
            error: "first failure".to_string(),
        },
    };
    scheduler.buffered_events.push_back(event);
    let actions = scheduler.tick();

    // After retry: retry_count = 1, status = Ready or Spawn emitted.
    assert_eq!(scheduler.graph.tasks[0].retry_count, 1);
    let spawned = actions
        .iter()
        .any(|a| matches!(a, SchedulerAction::Spawn { task_id, .. } if *task_id == TaskId(0)));
    assert!(
        spawned || scheduler.graph.tasks[0].status == TaskStatus::Ready,
        "retry should emit Spawn or set Ready"
    );
    // Graph must still be Running.
    assert_eq!(scheduler.graph.status, GraphStatus::Running);
}

/// spec-075 §6 success criterion: "a node with `recovery` configured whose failure also trips
/// a cascade-abort threshold ends the graph `Failed`, not recovered" — the cascade check in
/// `handle_failed_outcome()` runs *before* `propagate_failure()` (where `try_recover` lives),
/// so cascade-abort must structurally preempt recovery. Uses the linear-chain cascade path
/// (`cascade_chain_threshold`), which needs no `CascadeDetector` setup: A(0) -> B(1) -> C(2),
/// A and B fail with `Retry` (not exhausted, so their own failures don't independently abort
/// the graph), C fails with `recovery` configured. C's failure is the 3rd consecutive Failed
/// entry in the chain, tripping the default `cascade_chain_threshold = 3` — the graph must
/// abort via `abort_dag_with_lineage()` before `try_recover()` for C is ever reached.
#[test]
fn test_cascade_chain_threshold_preempts_recovery() {
    let graph = graph_from_nodes(vec![
        make_node(0, &[]),
        make_node(1, &[0]),
        make_node(2, &[1]),
    ]);
    let mut config = make_config();
    config.cascade_chain_threshold = 3;
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    // A and B: Retry with retries available, so their own failures reset them to Ready
    // rather than independently aborting the graph (which would confound the test — we want
    // the cascade *chain* check to be the thing that aborts, not an ordinary per-task Abort).
    scheduler.graph.tasks[0].failure_strategy = Some(crate::graph::FailureStrategy::Retry);
    scheduler.graph.tasks[0].max_retries = Some(5);
    scheduler.graph.tasks[1].failure_strategy = Some(crate::graph::FailureStrategy::Retry);
    scheduler.graph.tasks[1].max_retries = Some(5);
    // C: recovery configured. If recovery fired, this would end Completed with the injected
    // output — the assertion below proves it never gets the chance to.
    scheduler.graph.tasks[2].recovery = Some(crate::graph::RecoveryAction {
        state_injection: Some("should never be applied".to_string()),
        route_to: None,
    });

    for (id, handle) in [(TaskId(0), "h0"), (TaskId(1), "h1"), (TaskId(2), "h2")] {
        scheduler.graph.tasks[id.index()].status = TaskStatus::Running;
        scheduler.running.insert(
            id,
            RunningTask {
                agent_handle_id: handle.to_string(),
                agent_def_name: "worker".to_string(),
                started_at: std::time::Instant::now(),
                admission_permit: None,
                last_progress_at: None,
            },
        );
    }

    // Failures processed in dependency order within a single tick() — each handle_failed_outcome
    // call records its lineage entry into self.lineage_chains before the next event is drained.
    for (id, handle) in [(TaskId(0), "h0"), (TaskId(1), "h1"), (TaskId(2), "h2")] {
        scheduler.buffered_events.push_back(TaskEvent {
            task_id: id,
            agent_handle_id: handle.to_string(),
            outcome: TaskOutcome::Failed {
                error: "boom".to_string(),
            },
        });
    }
    scheduler.tick();

    assert_eq!(
        scheduler.graph.status,
        GraphStatus::Failed,
        "cascade chain threshold must abort the graph"
    );
    assert_eq!(
        scheduler.graph.tasks[2].status,
        TaskStatus::Failed,
        "the recovery-configured node must NOT be recovered — cascade-abort preempts \
         propagate_failure() (and thus try_recover()) entirely"
    );
    assert_eq!(
        scheduler.graph.tasks[2]
            .result
            .as_ref()
            .map(|r| r.output.as_str()),
        Some("boom"),
        "result must hold the plain failure error, not a Mode-1 recovery substitution \
         (agent_id/agent_def would also be set to the recovery marker if try_recover had run)"
    );
    assert_eq!(
        scheduler.graph.tasks[2]
            .result
            .as_ref()
            .and_then(|r| r.agent_def.as_deref()),
        None,
        "no synthetic recovery TaskResult (with its recovery marker agent_def) should ever \
         have been set"
    );
}

#[test]
fn test_timeout_cancels_stalled() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 1; // 1 second timeout
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    // Simulate a running task that started just over 1 second ago.
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now()
                .checked_sub(Duration::from_secs(2))
                .unwrap(), // already timed out
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let actions = scheduler.tick();
    let has_cancel = actions.iter().any(
        |a| matches!(a, SchedulerAction::Cancel { agent_handle_id } if agent_handle_id == "h0"),
    );
    assert!(has_cancel, "timed-out task should emit Cancel action");
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Failed);
}

#[test]
fn test_per_task_timeout_override_fires_before_global_default() {
    // Two running tasks: task 0 has a short per-task override (already exceeded),
    // task 1 has no override and relies on the (much longer) global default.
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 300; // long global default
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    // Use Skip (not the graph default Abort) for the overridden task so a genuine
    // timeout on task 0 doesn't cascade-abort and collaterally cancel unrelated task 1
    // — isolates the per-task deadline filter this test targets from cascade semantics.
    scheduler.graph.tasks[0].failure_strategy = Some(zeph_config::FailureStrategy::Skip);
    scheduler.graph.tasks[0].timeout = Some(crate::graph::TimeoutPolicy {
        run_timeout_secs: Some(1),
        idle_timeout_secs: None,
    });
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.graph.tasks[1].status = TaskStatus::Running;

    let started_2s_ago = std::time::Instant::now()
        .checked_sub(Duration::from_secs(2))
        .unwrap();
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: started_2s_ago,
            admission_permit: None,
            last_progress_at: None,
        },
    );
    scheduler.running.insert(
        TaskId(1),
        RunningTask {
            agent_handle_id: "h1".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: started_2s_ago,
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let actions = scheduler.tick();
    let canceled: Vec<&str> = actions
        .iter()
        .filter_map(|a| match a {
            SchedulerAction::Cancel { agent_handle_id } => Some(agent_handle_id.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(
        canceled,
        vec!["h0"],
        "only the overridden task should time out; the other respects the longer global default"
    );
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Skipped);
    assert_eq!(scheduler.graph.tasks[1].status, TaskStatus::Running);
}

#[test]
fn test_no_overrides_timing_matches_pre_feature_behavior() {
    // Regression: no per-task overrides anywhere → identical timing to pre-feature code.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 1;
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now()
                .checked_sub(Duration::from_secs(2))
                .unwrap(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let actions = scheduler.tick();
    let has_cancel = actions.iter().any(
        |a| matches!(a, SchedulerAction::Cancel { agent_handle_id } if agent_handle_id == "h0"),
    );
    assert!(
        has_cancel,
        "global timeout must still fire with no override"
    );
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Failed);
}

// --- idle_timeout_secs enforcement (issue #6245, Alt-A progress-signal plumbing) ---

/// A heartbeat recording the current instant, as if the sub-agent loop just wrote to it.
///
/// To simulate a *stale* heartbeat, record one and then let real time pass
/// (`std::thread::sleep`) before checking — subtracting an offset from `monotonic_millis()`
/// to fake staleness would underflow (`saturating_sub` clamps to 0) whenever the process,
/// and therefore its `PROCESS_START` origin, is young — which it always is at the start of
/// an isolated test binary.
fn progress_handle_now() -> std::sync::Arc<std::sync::atomic::AtomicU64> {
    std::sync::Arc::new(std::sync::atomic::AtomicU64::new(
        zeph_common::monotonic_millis(),
    ))
}

/// spec-075 §6 (FR-005, activated by #6245): a task with a short `idle_timeout_secs` and a
/// stale progress heartbeat (no turn boundary reached within the window) must be killed
/// with `TimeoutCause::Idle`, distinguishable via the synthetic `TaskResult.output` (F5).
#[test]
fn test_idle_timeout_fires_on_stale_progress() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 300; // long global run_timeout — must not be what fires
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    scheduler.graph.tasks[0].timeout = Some(crate::graph::TimeoutPolicy {
        run_timeout_secs: None,
        idle_timeout_secs: Some(1), // short — we sleep past it below
    });
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(), // recent — run_timeout nowhere close
            admission_permit: None,
            last_progress_at: Some(progress_handle_now()),
        },
    );
    std::thread::sleep(Duration::from_millis(1_100)); // let the 1s idle_timeout actually elapse

    let actions = scheduler.tick();
    let has_cancel = actions
        .iter()
        .any(|a| matches!(a, SchedulerAction::Cancel { .. }));
    assert!(
        has_cancel,
        "stale progress heartbeat must fire idle timeout"
    );
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Failed);
    let output = scheduler.graph.tasks[0]
        .result
        .as_ref()
        .expect("timeout must populate TaskResult")
        .output
        .clone();
    assert!(
        output.contains("idle timeout"),
        "TaskResult.output must name the idle cause, got: {output}"
    );
}

/// Mirror of the fire test: a task with the same short `idle_timeout_secs` but a heartbeat
/// that was just refreshed must NOT be killed — idle enforcement tracks real progress, not
/// just task age.
#[test]
fn test_idle_timeout_does_not_fire_while_progress_continues() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 300;
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    scheduler.graph.tasks[0].timeout = Some(crate::graph::TimeoutPolicy {
        run_timeout_secs: None,
        idle_timeout_secs: Some(60), // generous relative to the fresh heartbeat below
    });
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: Some(progress_handle_now()),
        },
    );

    let actions = scheduler.tick();
    let has_cancel = actions
        .iter()
        .any(|a| matches!(a, SchedulerAction::Cancel { .. }));
    assert!(
        !has_cancel,
        "a task with a fresh heartbeat must not be idle-killed"
    );
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Running);
}

/// F2 regression: a task with `last_progress_at: None` (the `RunInline` exemption — see
/// `RunningTask::last_progress_at` doc and the `record_spawn` call site in
/// `scheduler_loop.rs::handle_run_inline_action`) must never be idle-killed, even with an
/// idle timeout configured and a task age far past it. This is the `DagScheduler`-level half
/// of the guarantee; the exemption holds regardless of how stale `started_at` is because the
/// idle branch short-circuits on `last_progress_at.is_none()` before ever comparing durations.
#[test]
fn test_idle_timeout_exempt_without_progress_handle() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 300; // long — run_timeout must not be what's tested here
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    scheduler.graph.tasks[0].timeout = Some(crate::graph::TimeoutPolicy {
        run_timeout_secs: None,
        idle_timeout_secs: Some(1), // short — would fire immediately if last_progress_at were Some
    });
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now()
                .checked_sub(Duration::from_secs(5))
                .unwrap(),
            admission_permit: None,
            last_progress_at: None, // RunInline-style exemption
        },
    );

    let actions = scheduler.tick();
    let has_cancel = actions
        .iter()
        .any(|a| matches!(a, SchedulerAction::Cancel { .. }));
    assert!(
        !has_cancel,
        "a task with no progress handle must never be idle-killed, regardless of age"
    );
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Running);
}

/// Multi-task isolation: two independently-running tasks each carry their own
/// `Arc<AtomicU64>` heartbeat. A stale heartbeat on one task must not affect the other —
/// every idle-timeout test above uses a single-task graph, which cannot by itself rule out
/// a bug that reads/writes the wrong task's handle (e.g. an accidental shared `Arc`, or a
/// `check_timeouts` loop that mixes up per-task state).
#[test]
fn test_idle_timeout_multi_task_heartbeats_are_independent() {
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 300; // long — isolate idle-timeout behavior from run-timeout
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    let short_idle = crate::graph::TimeoutPolicy {
        run_timeout_secs: None,
        idle_timeout_secs: Some(1),
    };
    scheduler.graph.tasks[0].timeout = Some(short_idle.clone());
    scheduler.graph.tasks[1].timeout = Some(short_idle);
    // Use Skip (not the graph default Abort) on task 0 so its idle-timeout kill doesn't
    // cascade-abort the whole graph and collaterally cancel unrelated task 1 (mirrors
    // test_per_task_timeout_override_fires_before_global_default's rationale) — isolates
    // per-task heartbeat independence from unrelated Abort cascade semantics.
    scheduler.graph.tasks[0].failure_strategy = Some(zeph_config::FailureStrategy::Skip);
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.graph.tasks[1].status = TaskStatus::Running;

    // Task 0's heartbeat is recorded first, then we sleep past the 1s idle window, then
    // task 1's heartbeat is recorded fresh — so task 0's Arc is genuinely stale relative to
    // the idle window while task 1's is not, and each task holds a distinct Arc.
    let handle0 = progress_handle_now();
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: Some(handle0),
        },
    );
    std::thread::sleep(Duration::from_millis(1_100));
    let handle1 = progress_handle_now();
    scheduler.running.insert(
        TaskId(1),
        RunningTask {
            agent_handle_id: "h1".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: Some(handle1),
        },
    );

    let actions = scheduler.tick();
    let canceled: Vec<&str> = actions
        .iter()
        .filter_map(|a| match a {
            SchedulerAction::Cancel { agent_handle_id } => Some(agent_handle_id.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(
        canceled,
        vec!["h0"],
        "only the task with the stale heartbeat should be idle-killed"
    );
    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Skipped,
        "task 0 (stale heartbeat) must be killed — Skip strategy turns the timeout-Failed \
         status into Skipped via propagate_failure, same as the existing per-task-timeout test"
    );
    assert_eq!(
        scheduler.graph.tasks[1].status,
        TaskStatus::Running,
        "task 1's own fresh heartbeat must keep it alive, unaffected by task 0's staleness"
    );
}

/// F4: when both run-timeout and idle-timeout are exceeded on the same tick, run must win
/// — it is the hard wall-clock cap, idle the softer liveness signal. Verified indirectly via
/// the synthetic `TaskResult.output` cause string (the `TimeoutCause` enum itself is private).
#[test]
fn test_run_timeout_wins_precedence_over_idle_on_same_tick() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 1; // both run and idle will be exceeded
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    scheduler.graph.tasks[0].timeout = Some(crate::graph::TimeoutPolicy {
        run_timeout_secs: None,
        idle_timeout_secs: Some(1),
    });
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now()
                .checked_sub(Duration::from_secs(10))
                .unwrap(),
            admission_permit: None,
            // Value irrelevant to this test: run-timeout is checked first and already
            // exceeded via started_at above, so the idle branch is never reached regardless
            // of heartbeat freshness.
            last_progress_at: Some(progress_handle_now()),
        },
    );

    scheduler.tick();
    let output = scheduler.graph.tasks[0]
        .result
        .as_ref()
        .expect("timeout must populate TaskResult")
        .output
        .clone();
    assert!(
        output.contains("run timeout"),
        "run timeout must win precedence on a same-tick tie, got: {output}"
    );
    assert!(
        !output.contains("idle timeout"),
        "only one cause must be reported per NFR-OB-01, got: {output}"
    );
}

/// F5: a run-timeout kill (no idle policy configured at all) must also populate
/// `TaskResult.output` with a cause — this was a latent bug (timeout kills previously left
/// `result: None`, showing no reason anywhere in the TUI/CLI).
#[test]
fn test_run_timeout_populates_task_result_cause() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 1;
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now()
                .checked_sub(Duration::from_secs(2))
                .unwrap(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    scheduler.tick();
    let result = scheduler.graph.tasks[0]
        .result
        .as_ref()
        .expect("run-timeout kill must populate TaskResult (F5 fix)");
    assert!(result.output.contains("run timeout"));
    assert_eq!(result.agent_id.as_deref(), Some("h0"));
    assert_eq!(result.agent_def.as_deref(), Some("worker"));
}

#[test]
fn test_effective_run_timeout_falls_back_to_global_default() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 300;
    let defs = vec![make_def("worker")];
    let scheduler = DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    assert_eq!(
        scheduler.effective_run_timeout(TaskId(0)),
        Duration::from_mins(5)
    );
}

#[test]
fn test_effective_run_timeout_uses_per_task_override() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut config = make_config();
    config.task_timeout_secs = 300;
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();
    scheduler.graph.tasks[0].timeout = Some(crate::graph::TimeoutPolicy {
        run_timeout_secs: Some(45),
        idle_timeout_secs: None,
    });

    assert_eq!(
        scheduler.effective_run_timeout(TaskId(0)),
        Duration::from_secs(45)
    );
}

#[test]
fn test_effective_idle_timeout_none_when_unset_anywhere() {
    // Unlike effective_run_timeout, idle is opt-in — with no per-task override and no
    // global default configured, the effective value must be None (disabled), never a
    // sentinel Duration.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let defs = vec![make_def("worker")];
    let scheduler =
        DagScheduler::new(graph, &make_config(), Box::new(FirstRouter), defs, None).unwrap();
    assert_eq!(scheduler.effective_idle_timeout(TaskId(0)), None);
}

#[test]
fn test_effective_idle_timeout_falls_back_to_global_default() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = zeph_config::OrchestrationConfig {
        default_idle_timeout_secs: Some(30),
        ..make_config()
    };
    let defs = vec![make_def("worker")];
    let scheduler = DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    assert_eq!(
        scheduler.effective_idle_timeout(TaskId(0)),
        Some(Duration::from_secs(30))
    );
}

#[test]
fn test_effective_idle_timeout_uses_per_task_override_over_global_default() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = zeph_config::OrchestrationConfig {
        default_idle_timeout_secs: Some(30),
        ..make_config()
    };
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();
    scheduler.graph.tasks[0].timeout = Some(crate::graph::TimeoutPolicy {
        run_timeout_secs: None,
        idle_timeout_secs: Some(5),
    });

    assert_eq!(
        scheduler.effective_idle_timeout(TaskId(0)),
        Some(Duration::from_secs(5)),
        "per-task override must win over the global default (30s), not merge with it"
    );
}

#[test]
fn test_cancel_all() {
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );
    scheduler.graph.tasks[1].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(1),
        RunningTask {
            agent_handle_id: "h1".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let actions = scheduler.cancel_all();

    assert_eq!(scheduler.graph.status, GraphStatus::Canceled);
    assert!(scheduler.running.is_empty());
    let cancel_count = actions
        .iter()
        .filter(|a| matches!(a, SchedulerAction::Cancel { .. }))
        .count();
    assert_eq!(cancel_count, 2);
    assert!(actions.iter().any(|a| matches!(
        a,
        SchedulerAction::Done {
            status: GraphStatus::Canceled
        }
    )));
}

#[test]
fn test_record_spawn_failure() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);

    // Simulate task marked Running (by tick) but spawn failed.
    scheduler.graph.tasks[0].status = TaskStatus::Running;

    let error = SubAgentError::Spawn("spawn error".to_string());
    let actions = scheduler.record_spawn_failure(TaskId(0), &error);
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Failed);
    // With Abort strategy and no other running tasks, graph should be Failed.
    assert_eq!(scheduler.graph.status, GraphStatus::Failed);
    assert!(
        actions
            .iter()
            .any(|a| matches!(a, SchedulerAction::Done { .. }))
    );
}

#[test]
fn test_record_spawn_failure_concurrency_limit_reverts_to_ready() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);

    // Simulate tick() optimistically marking the task Running before spawn.
    scheduler.graph.tasks[0].status = TaskStatus::Running;

    // Concurrency limit hit — transient, should not fail the task.
    let error = SubAgentError::ConcurrencyLimit { active: 4, max: 4 };
    let actions = scheduler.record_spawn_failure(TaskId(0), &error);
    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Ready,
        "task must revert to Ready so the next tick can retry"
    );
    assert_eq!(
        scheduler.graph.status,
        GraphStatus::Running,
        "graph must stay Running, not transition to Failed"
    );
    assert!(
        actions.is_empty(),
        "no cancel or done actions expected for a transient deferral"
    );
}

#[test]
fn test_record_spawn_failure_concurrency_limit_variant_spawn_for_task() {
    // Both spawn() and resume() now return SubAgentError::ConcurrencyLimit — verify handling.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].status = TaskStatus::Running;

    let error = SubAgentError::ConcurrencyLimit { active: 1, max: 1 };
    let actions = scheduler.record_spawn_failure(TaskId(0), &error);
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Ready);
    assert!(actions.is_empty());
}

#[test]
fn test_concurrency_deferral_does_not_affect_running_task() {
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut scheduler = make_scheduler(graph);

    // Simulate both tasks optimistically marked Running by tick().
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );
    scheduler.graph.tasks[1].status = TaskStatus::Running;

    // Task 1 spawn fails with concurrency limit.
    let error = SubAgentError::ConcurrencyLimit { active: 1, max: 1 };
    let actions = scheduler.record_spawn_failure(TaskId(1), &error);

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Running,
        "task 0 must remain Running"
    );
    assert_eq!(
        scheduler.graph.tasks[1].status,
        TaskStatus::Ready,
        "task 1 must revert to Ready"
    );
    assert_eq!(
        scheduler.graph.status,
        GraphStatus::Running,
        "graph must stay Running"
    );
    assert!(actions.is_empty(), "no cancel or done actions expected");
}

#[test]
fn test_max_concurrent_zero_no_infinite_loop() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = zeph_config::OrchestrationConfig {
        max_parallel: 0,
        ..make_config()
    };
    let mut scheduler = DagScheduler::new(
        graph,
        &config,
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();

    let actions1 = scheduler.tick();
    assert!(
        actions1
            .iter()
            .all(|a| !matches!(a, SchedulerAction::Spawn { .. })),
        "no Spawn expected when max_parallel=0"
    );
    assert!(
        actions1
            .iter()
            .all(|a| !matches!(a, SchedulerAction::Done { .. })),
        "no Done(Failed) expected — ready tasks exist, so no deadlock"
    );
    assert_eq!(scheduler.graph.status, GraphStatus::Running);

    let actions2 = scheduler.tick();
    assert!(
        actions2
            .iter()
            .all(|a| !matches!(a, SchedulerAction::Done { .. })),
        "second tick must not emit Done(Failed) — ready tasks still exist"
    );
    assert_eq!(
        scheduler.graph.status,
        GraphStatus::Running,
        "graph must remain Running"
    );
}

#[test]
fn test_all_tasks_deferred_graph_stays_running() {
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut scheduler = make_scheduler(graph);

    // First tick emits Spawn for both tasks and marks them Running.
    let actions = scheduler.tick();
    assert_eq!(
        actions
            .iter()
            .filter(|a| matches!(a, SchedulerAction::Spawn { .. }))
            .count(),
        2,
        "expected 2 Spawn actions on first tick"
    );
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Running);
    assert_eq!(scheduler.graph.tasks[1].status, TaskStatus::Running);

    // Both spawns fail — both revert to Ready.
    let error = SubAgentError::ConcurrencyLimit { active: 2, max: 2 };
    let r0 = scheduler.record_spawn_failure(TaskId(0), &error);
    let r1 = scheduler.record_spawn_failure(TaskId(1), &error);
    assert!(r0.is_empty() && r1.is_empty(), "no cancel/done on deferral");
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Ready);
    assert_eq!(scheduler.graph.tasks[1].status, TaskStatus::Ready);
    assert_eq!(scheduler.graph.status, GraphStatus::Running);

    // Second tick must retry both deferred tasks.
    let retry_actions = scheduler.tick();
    let spawn_count = retry_actions
        .iter()
        .filter(|a| matches!(a, SchedulerAction::Spawn { .. }))
        .count();
    assert!(
        spawn_count > 0,
        "second tick must re-emit Spawn for deferred tasks"
    );
    assert!(
        retry_actions.iter().all(|a| !matches!(
            a,
            SchedulerAction::Done {
                status: GraphStatus::Failed,
                ..
            }
        )),
        "no Done(Failed) expected"
    );
}

#[test]
fn test_no_agent_routes_inline() {
    // NoneRouter: when no agent matches, task falls back to RunInline.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler_with_router(graph, Box::new(NoneRouter));
    let actions = scheduler.tick();
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Running);
    assert!(
        actions
            .iter()
            .any(|a| matches!(a, SchedulerAction::RunInline { .. }))
    );
}

#[test]
fn test_stale_event_rejected() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);

    // Simulate task running with handle "current-handle".
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "current-handle".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    // Send a completion event from the OLD agent (stale handle).
    let stale_event = TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "old-handle".to_string(),
        outcome: TaskOutcome::Completed {
            output: "stale output".to_string(),
            artifacts: vec![],
            tool_trace: None,
        },
    };
    scheduler.buffered_events.push_back(stale_event);
    let actions = scheduler.tick();

    assert_ne!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Completed,
        "stale event must not complete the task"
    );
    let has_done = actions
        .iter()
        .any(|a| matches!(a, SchedulerAction::Done { .. }));
    assert!(
        !has_done,
        "no Done action should be emitted for a stale event"
    );
    assert!(
        scheduler.running.contains_key(&TaskId(0)),
        "running task must remain after stale event"
    );
}

#[test]
fn test_duration_ms_computed_correctly() {
    // Regression test for C1: duration_ms must be non-zero after completion.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now()
                .checked_sub(Duration::from_millis(50))
                .unwrap(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let event = TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "h0".to_string(),
        outcome: TaskOutcome::Completed {
            output: "result".to_string(),
            artifacts: vec![],
            tool_trace: None,
        },
    };
    scheduler.buffered_events.push_back(event);
    scheduler.tick();

    let result = scheduler.graph.tasks[0].result.as_ref().unwrap();
    assert!(
        result.duration_ms > 0,
        "duration_ms should be > 0, got {}",
        result.duration_ms
    );
}

// --- #1619 regression tests: consecutive_spawn_failures + exponential backoff ---

#[test]
fn test_consecutive_spawn_failures_increments_on_concurrency_limit() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].status = TaskStatus::Running;

    assert_eq!(scheduler.consecutive_spawn_failures, 0, "starts at zero");

    let error = SubAgentError::ConcurrencyLimit { active: 4, max: 4 };
    scheduler.record_spawn_failure(TaskId(0), &error);
    scheduler.record_batch_backoff(false, true);
    assert_eq!(
        scheduler.consecutive_spawn_failures, 1,
        "first deferral tick: consecutive_spawn_failures must be 1"
    );

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.record_spawn_failure(TaskId(0), &error);
    scheduler.record_batch_backoff(false, true);
    assert_eq!(
        scheduler.consecutive_spawn_failures, 2,
        "second deferral tick: consecutive_spawn_failures must be 2"
    );

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.record_spawn_failure(TaskId(0), &error);
    scheduler.record_batch_backoff(false, true);
    assert_eq!(
        scheduler.consecutive_spawn_failures, 3,
        "third deferral tick: consecutive_spawn_failures must be 3"
    );
}

#[test]
fn test_consecutive_spawn_failures_resets_on_success() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].status = TaskStatus::Running;

    let error = SubAgentError::ConcurrencyLimit { active: 1, max: 1 };
    scheduler.record_spawn_failure(TaskId(0), &error);
    scheduler.record_batch_backoff(false, true);
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.record_spawn_failure(TaskId(0), &error);
    scheduler.record_batch_backoff(false, true);
    assert_eq!(scheduler.consecutive_spawn_failures, 2);

    scheduler.record_spawn(
        TaskId(0),
        "handle-0".to_string(),
        "worker".to_string(),
        None,
    );
    assert_eq!(
        scheduler.consecutive_spawn_failures, 0,
        "record_spawn must reset consecutive_spawn_failures to 0"
    );
}

#[tokio::test]
async fn test_exponential_backoff_duration() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = zeph_config::OrchestrationConfig {
        deferral_backoff_ms: 50,
        ..make_config()
    };
    let mut scheduler = DagScheduler::new(
        graph,
        &config,
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();

    // consecutive_spawn_failures=0 → sleep ≈ 50ms (base).
    assert_eq!(scheduler.consecutive_spawn_failures, 0);
    let start = tokio::time::Instant::now();
    scheduler.wait_event().await;
    let elapsed0 = start.elapsed();
    assert!(
        elapsed0.as_millis() >= 50,
        "backoff with 0 deferrals must be >= base (50ms), got {}ms",
        elapsed0.as_millis()
    );

    // Simulate 3 consecutive deferrals: multiplier = 2^3 = 8 → 400ms, capped at 5000ms.
    scheduler.consecutive_spawn_failures = 3;
    let start = tokio::time::Instant::now();
    scheduler.wait_event().await;
    let elapsed3 = start.elapsed();
    assert!(
        elapsed3.as_millis() >= 400,
        "backoff with 3 deferrals must be >= 400ms (50 * 8), got {}ms",
        elapsed3.as_millis()
    );

    // Simulate 20 consecutive deferrals: exponent capped at 10 → 50 * 1024 = 51200 → capped at 5000ms.
    scheduler.consecutive_spawn_failures = 20;
    let start = tokio::time::Instant::now();
    scheduler.wait_event().await;
    let elapsed_capped = start.elapsed();
    assert!(
        elapsed_capped.as_millis() >= 5000,
        "backoff must be capped at 5000ms with high deferrals, got {}ms",
        elapsed_capped.as_millis()
    );
}

#[tokio::test]
async fn test_wait_event_nearest_deadline_reflects_per_task_override() {
    // task 0 has a short per-task override that has already nearly elapsed; task 1 has
    // no override and relies on a very long global default. wait_event()'s computed
    // wait must reflect the nearer (task 0's) deadline, not the uniform global one.
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let config = zeph_config::OrchestrationConfig {
        task_timeout_secs: 300,
        ..make_config()
    };
    let mut scheduler = DagScheduler::new(
        graph,
        &config,
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();

    scheduler.graph.tasks[0].timeout = Some(crate::graph::TimeoutPolicy {
        run_timeout_secs: Some(1),
        idle_timeout_secs: None,
    });
    let now = std::time::Instant::now();
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: now.checked_sub(Duration::from_millis(950)).unwrap(),
            admission_permit: None,
            last_progress_at: None,
        },
    );
    scheduler.running.insert(
        TaskId(1),
        RunningTask {
            agent_handle_id: "h1".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: now,
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let start = tokio::time::Instant::now();
    scheduler.wait_event().await;
    let elapsed = start.elapsed();
    assert!(
        elapsed.as_millis() < 5000,
        "wait_event must return promptly based on task 0's near-elapsed override, \
         not the 300s global default; got {}ms",
        elapsed.as_millis()
    );
}

#[tokio::test]
async fn test_wait_event_sleeps_deferral_backoff_when_running_empty() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = zeph_config::OrchestrationConfig {
        deferral_backoff_ms: 50,
        ..make_config()
    };
    let mut scheduler = DagScheduler::new(
        graph,
        &config,
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();

    assert!(scheduler.running.is_empty());

    let start = tokio::time::Instant::now();
    scheduler.wait_event().await;
    let elapsed = start.elapsed();

    assert!(
        elapsed.as_millis() >= 50,
        "wait_event must sleep at least deferral_backoff (50ms) when running is empty, but only slept {}ms",
        elapsed.as_millis()
    );
}

#[test]
fn test_current_deferral_backoff_exponential_growth() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = zeph_config::OrchestrationConfig {
        deferral_backoff_ms: 250,
        ..make_config()
    };
    let mut scheduler = DagScheduler::new(
        graph,
        &config,
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();

    assert_eq!(
        scheduler.current_deferral_backoff(),
        Duration::from_millis(250)
    );

    scheduler.consecutive_spawn_failures = 1;
    assert_eq!(
        scheduler.current_deferral_backoff(),
        Duration::from_millis(500)
    );

    scheduler.consecutive_spawn_failures = 2;
    assert_eq!(scheduler.current_deferral_backoff(), Duration::from_secs(1));

    scheduler.consecutive_spawn_failures = 3;
    assert_eq!(scheduler.current_deferral_backoff(), Duration::from_secs(2));

    scheduler.consecutive_spawn_failures = 4;
    assert_eq!(scheduler.current_deferral_backoff(), Duration::from_secs(4));

    // Cap at 5 seconds.
    scheduler.consecutive_spawn_failures = 5;
    assert_eq!(scheduler.current_deferral_backoff(), Duration::from_secs(5));

    scheduler.consecutive_spawn_failures = 100;
    assert_eq!(scheduler.current_deferral_backoff(), Duration::from_secs(5));
}

#[test]
fn test_record_spawn_resets_consecutive_failures() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = DagScheduler::new(
        graph,
        &make_config(),
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();

    scheduler.consecutive_spawn_failures = 3;
    let task_id = TaskId(0);
    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.record_spawn(task_id, "handle-1".into(), "worker".into(), None);

    assert_eq!(scheduler.consecutive_spawn_failures, 0);
}

#[test]
fn test_record_spawn_failure_reverts_to_ready_no_counter_change() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = DagScheduler::new(
        graph,
        &make_config(),
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();

    assert_eq!(scheduler.consecutive_spawn_failures, 0);
    let task_id = TaskId(0);
    scheduler.graph.tasks[0].status = TaskStatus::Running;

    let error = SubAgentError::ConcurrencyLimit { active: 1, max: 1 };
    scheduler.record_spawn_failure(task_id, &error);

    assert_eq!(scheduler.consecutive_spawn_failures, 0);
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Ready);
}

#[test]
fn test_parallel_dispatch_all_ready() {
    let nodes: Vec<_> = (0..6).map(|i| make_node(i, &[])).collect();
    let graph = graph_from_nodes(nodes);
    let config = zeph_config::OrchestrationConfig {
        max_parallel: 2,
        ..make_config()
    };
    let mut scheduler = DagScheduler::new(
        graph,
        &config,
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();

    let actions = scheduler.tick();
    let spawn_count = actions
        .iter()
        .filter(|a| matches!(a, SchedulerAction::Spawn { .. }))
        .count();
    assert_eq!(
        spawn_count, 2,
        "only max_parallel=2 tasks dispatched per tick"
    );

    let running_count = scheduler
        .graph
        .tasks
        .iter()
        .filter(|t| t.status == TaskStatus::Running)
        .count();
    assert_eq!(running_count, 2, "only 2 tasks marked Running");
}

#[test]
fn test_batch_backoff_partial_success() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.consecutive_spawn_failures = 3;

    scheduler.record_batch_backoff(true, true);
    assert_eq!(
        scheduler.consecutive_spawn_failures, 0,
        "any success in batch must reset counter"
    );
}

#[test]
fn test_batch_backoff_all_failed() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.consecutive_spawn_failures = 2;

    scheduler.record_batch_backoff(false, true);
    assert_eq!(
        scheduler.consecutive_spawn_failures, 3,
        "all-failure tick must increment counter"
    );
}

#[test]
fn test_batch_backoff_no_spawns() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.consecutive_spawn_failures = 5;

    scheduler.record_batch_backoff(false, false);
    assert_eq!(
        scheduler.consecutive_spawn_failures, 5,
        "no spawns must not change counter"
    );
}

#[test]
fn test_buffer_guard_uses_task_count() {
    let nodes: Vec<_> = (0..10).map(|i| make_node(i, &[])).collect();
    let graph = graph_from_nodes(nodes);
    let config = zeph_config::OrchestrationConfig {
        max_parallel: 2,
        ..make_config()
    };
    let scheduler = DagScheduler::new(
        graph,
        &config,
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();
    assert_eq!(scheduler.graph.tasks.len() * 2, 20);
    assert_eq!(scheduler.max_parallel * 2, 4);
}

#[test]
fn test_batch_mixed_concurrency_and_fatal_failure() {
    use crate::graph::FailureStrategy;

    let mut nodes = vec![make_node(0, &[]), make_node(1, &[])];
    nodes[1].failure_strategy = Some(FailureStrategy::Skip);
    let graph = graph_from_nodes(nodes);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.graph.tasks[1].status = TaskStatus::Running;

    let concurrency_err = SubAgentError::ConcurrencyLimit { active: 1, max: 1 };
    let actions0 = scheduler.record_spawn_failure(TaskId(0), &concurrency_err);
    assert!(
        actions0.is_empty(),
        "ConcurrencyLimit must produce no extra actions"
    );
    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Ready,
        "task 0 must revert to Ready"
    );

    let fatal_err = SubAgentError::Spawn("provider unavailable".to_string());
    let actions1 = scheduler.record_spawn_failure(TaskId(1), &fatal_err);
    assert_eq!(
        scheduler.graph.tasks[1].status,
        TaskStatus::Skipped,
        "task 1: Skip strategy turns Failed into Skipped via propagate_failure"
    );
    assert!(
        actions1
            .iter()
            .all(|a| !matches!(a, SchedulerAction::Done { .. })),
        "no Done action expected: task 0 is still Ready"
    );

    scheduler.consecutive_spawn_failures = 0;
    scheduler.record_batch_backoff(false, true);
    assert_eq!(
        scheduler.consecutive_spawn_failures, 1,
        "batch with only ConcurrencyLimit must increment counter"
    );
}

#[test]
fn test_deadlock_marks_non_terminal_tasks_canceled() {
    let mut nodes = vec![make_node(0, &[]), make_node(1, &[0]), make_node(2, &[0])];
    nodes[0].status = TaskStatus::Failed;
    nodes[1].status = TaskStatus::Pending;
    nodes[2].status = TaskStatus::Pending;

    let mut graph = graph_from_nodes(nodes);
    graph.status = GraphStatus::Failed;

    let mut scheduler = DagScheduler::resume_from(
        graph,
        &make_config(),
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();

    let actions = scheduler.tick();

    assert!(
        actions.iter().any(|a| matches!(
            a,
            SchedulerAction::Done {
                status: GraphStatus::Failed
            }
        )),
        "deadlock must emit Done(Failed); got: {actions:?}"
    );
    assert_eq!(scheduler.graph.status, GraphStatus::Failed);
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Failed);
    assert_eq!(
        scheduler.graph.tasks[1].status,
        TaskStatus::Canceled,
        "Pending task must be Canceled on deadlock"
    );
    assert_eq!(
        scheduler.graph.tasks[2].status,
        TaskStatus::Canceled,
        "Pending task must be Canceled on deadlock"
    );
}

#[test]
fn test_deadlock_not_triggered_when_task_running() {
    let mut nodes = vec![make_node(0, &[]), make_node(1, &[0])];
    nodes[0].status = TaskStatus::Running;
    nodes[0].assigned_agent = Some("handle-1".into());
    nodes[1].status = TaskStatus::Pending;

    let mut graph = graph_from_nodes(nodes);
    graph.status = GraphStatus::Failed;

    let mut scheduler = DagScheduler::resume_from(
        graph,
        &make_config(),
        Box::new(FirstRouter),
        vec![make_def("worker")],
        None,
    )
    .unwrap();

    let actions = scheduler.tick();

    assert!(
        actions
            .iter()
            .all(|a| !matches!(a, SchedulerAction::Done { .. })),
        "no Done action expected when a task is running; got: {actions:?}"
    );
    assert_eq!(scheduler.graph.status, GraphStatus::Running);
}

// ── Admission gate wiring tests ──────────────────────────────────────────────────────────────

fn make_def_with_provider(name: &str, provider: &str) -> zeph_subagent::SubAgentDef {
    let mut d = zeph_subagent::SubAgentDef::for_test(name);
    d.model = Some(zeph_subagent::ModelSpec::Named(provider.to_string()));
    d
}

#[test]
fn admission_gate_saturated_defers_task() {
    // Gate with capacity=1, already at capacity → task must not be spawned.
    let gate = crate::admission::AdmissionGate::new(&[("quality".to_string(), 1usize)]);
    // Exhaust the single permit so the gate is at capacity.
    let _held_permit = gate
        .try_acquire("quality")
        .expect("first permit must succeed");

    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = make_config();
    let defs = vec![make_def_with_provider("worker", "quality")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, Some(gate)).unwrap();

    let actions = scheduler.tick();
    let spawn_count = actions
        .iter()
        .filter(|a| matches!(a, SchedulerAction::Spawn { .. }))
        .count();
    assert_eq!(
        spawn_count, 0,
        "saturated gate must defer task — no Spawn emitted"
    );
    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Ready,
        "deferred task must stay Ready"
    );
}

#[test]
fn admission_gate_permit_transferred_to_running() {
    // After a successful spawn cycle the permit must live in RunningTask, not pending_permits.
    let gate = crate::admission::AdmissionGate::new(&[("quality".to_string(), 2usize)]);

    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = make_config();
    let defs = vec![make_def_with_provider("worker", "quality")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, Some(gate)).unwrap();

    let actions = scheduler.tick();
    let spawned = actions.iter().find_map(|a| {
        if let SchedulerAction::Spawn { task_id, .. } = a {
            Some(*task_id)
        } else {
            None
        }
    });
    let task_id = spawned.expect("task must be spawned");

    // Permit must be in pending_permits before record_spawn.
    assert!(
        scheduler.pending_permits.contains_key(&task_id),
        "permit must be in pending_permits after dispatch"
    );

    scheduler.graph.tasks[task_id.index()].status = TaskStatus::Running;
    scheduler.record_spawn(task_id, "handle-1".into(), "worker".into(), None);

    assert!(
        !scheduler.pending_permits.contains_key(&task_id),
        "pending_permits must be empty after record_spawn"
    );
    assert!(
        scheduler.running[&task_id].admission_permit.is_some(),
        "admission_permit must be set in RunningTask"
    );
}

#[test]
fn admission_gate_bypass_for_ungated_provider() {
    // Agent uses a provider not in the gate → task dispatched normally.
    let gate = crate::admission::AdmissionGate::new(&[("quality".to_string(), 1usize)]);

    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = make_config();
    // Agent maps to "fast" which has no gate entry.
    let defs = vec![make_def_with_provider("worker", "fast")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, Some(gate)).unwrap();

    let actions = scheduler.tick();
    let spawn_count = actions
        .iter()
        .filter(|a| matches!(a, SchedulerAction::Spawn { .. }))
        .count();
    assert_eq!(spawn_count, 1, "ungated provider must not be blocked");
}

#[test]
fn record_spawn_failure_releases_pending_permit() {
    // A fatal spawn failure must remove the pending admission permit (C2 fix).
    let gate = crate::admission::AdmissionGate::new(&[("quality".to_string(), 2usize)]);

    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = make_config();
    let defs = vec![make_def_with_provider("worker", "quality")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, Some(gate)).unwrap();

    // Simulate dispatch: insert a permit manually as tick() would.
    let permit = scheduler
        .admission_gate
        .as_ref()
        .unwrap()
        .try_acquire("quality")
        .expect("permit must be available");
    let task_id = TaskId(0);
    scheduler.pending_permits.insert(task_id, permit);
    scheduler.graph.tasks[0].status = TaskStatus::Running;

    assert!(scheduler.pending_permits.contains_key(&task_id));

    let fatal = zeph_subagent::SubAgentError::Spawn("provider unavailable".to_string());
    scheduler.record_spawn_failure(task_id, &fatal);

    assert!(
        !scheduler.pending_permits.contains_key(&task_id),
        "pending permit must be removed after fatal spawn failure"
    );
}

// --- graph_dirty / take_graph_dirty checkpoint flag tests ---

#[test]
fn graph_dirty_clear_at_construction() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let scheduler = make_scheduler(graph);
    assert!(
        !scheduler.graph_dirty,
        "graph_dirty must be false immediately after construction"
    );
}

#[test]
fn take_graph_dirty_returns_false_when_no_mutations() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    // No tick or mutation — flag must stay false.
    assert!(
        !scheduler.take_graph_dirty(),
        "take_graph_dirty must return false when no mutations occurred"
    );
    // Calling again must still return false (idempotent on clean state).
    assert!(
        !scheduler.take_graph_dirty(),
        "take_graph_dirty must remain false after a second call"
    );
}

#[test]
fn take_graph_dirty_true_after_task_completes() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let event = TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "h0".to_string(),
        outcome: TaskOutcome::Completed {
            output: "done".to_string(),
            artifacts: vec![],
            tool_trace: None,
        },
    };
    scheduler.buffered_events.push_back(event);
    scheduler.tick();

    assert!(
        scheduler.take_graph_dirty(),
        "take_graph_dirty must return true after a task completes"
    );
    // Reset invariant: second call must return false.
    assert!(
        !scheduler.take_graph_dirty(),
        "take_graph_dirty must return false on the second call (reset invariant)"
    );
}

#[test]
fn take_graph_dirty_true_after_task_fails() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    let event = TaskEvent {
        task_id: TaskId(0),
        agent_handle_id: "h0".to_string(),
        outcome: TaskOutcome::Failed {
            error: "boom".to_string(),
        },
    };
    scheduler.buffered_events.push_back(event);
    scheduler.tick();

    assert!(
        scheduler.take_graph_dirty(),
        "take_graph_dirty must return true after a task fails"
    );
    assert!(
        !scheduler.take_graph_dirty(),
        "take_graph_dirty must return false on the second call (reset invariant)"
    );
}

#[test]
fn take_graph_dirty_true_after_fatal_spawn_failure() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].status = TaskStatus::Running;

    let fatal = zeph_subagent::SubAgentError::Spawn("provider gone".to_string());
    scheduler.record_spawn_failure(TaskId(0), &fatal);

    assert!(
        scheduler.take_graph_dirty(),
        "take_graph_dirty must return true after a fatal spawn failure marks task Failed"
    );
    assert!(
        !scheduler.take_graph_dirty(),
        "take_graph_dirty must reset to false on second call"
    );
}

#[test]
fn take_graph_dirty_false_after_transient_concurrency_failure() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].status = TaskStatus::Running;

    // Transient: task reverts to Ready — no terminal state change.
    let transient = zeph_subagent::SubAgentError::ConcurrencyLimit { active: 1, max: 1 };
    scheduler.record_spawn_failure(TaskId(0), &transient);

    assert!(
        !scheduler.take_graph_dirty(),
        "transient concurrency deferral must not set graph_dirty (no terminal mutation)"
    );
}

#[test]
fn take_graph_dirty_true_after_cancel_all() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    scheduler.cancel_all();

    assert!(
        scheduler.take_graph_dirty(),
        "take_graph_dirty must return true after cancel_all"
    );
    assert!(
        !scheduler.take_graph_dirty(),
        "take_graph_dirty must reset to false on second call"
    );
}

#[test]
fn take_graph_dirty_true_after_timeout() {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = zeph_config::OrchestrationConfig {
        task_timeout_secs: 1,
        ..make_config()
    };
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();

    scheduler.graph.tasks[0].status = TaskStatus::Running;
    scheduler.running.insert(
        TaskId(0),
        RunningTask {
            agent_handle_id: "h0".to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now()
                .checked_sub(Duration::from_secs(2))
                .unwrap(),
            admission_permit: None,
            last_progress_at: None,
        },
    );

    scheduler.tick();

    assert!(
        scheduler.take_graph_dirty(),
        "take_graph_dirty must return true after a task times out"
    );
    assert!(
        !scheduler.take_graph_dirty(),
        "take_graph_dirty must reset to false on second call"
    );
}

// ── #6380: total tool-call failure must not leave a task Completed ────────────

fn make_running_task(scheduler: &mut DagScheduler, task_id: TaskId, handle_id: &str) {
    scheduler.graph.tasks[task_id.index()].status = TaskStatus::Running;
    scheduler.running.insert(
        task_id,
        RunningTask {
            agent_handle_id: handle_id.to_string(),
            agent_def_name: "worker".to_string(),
            started_at: std::time::Instant::now(),
            admission_permit: None,
            last_progress_at: None,
        },
    );
}

fn completed_event(
    task_id: TaskId,
    handle_id: &str,
    tool_trace: Option<Vec<ToolCallSummary>>,
) -> TaskEvent {
    TaskEvent {
        task_id,
        agent_handle_id: handle_id.to_string(),
        outcome: TaskOutcome::Completed {
            output: "narration".to_string(),
            artifacts: vec![],
            tool_trace,
        },
    }
}

#[test]
fn handle_completed_outcome_all_tools_failed_marks_task_failed() {
    // Part A (RunInline path): every real tool call in the synchronously-available trace
    // failed (including policy_blocked denials) — the task must not remain Completed.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    make_running_task(&mut scheduler, TaskId(0), "h0");

    scheduler.buffered_events.push_back(completed_event(
        TaskId(0),
        "h0",
        Some(vec![
            ToolCallSummary {
                tool: "create_directory".to_string(),
                args_summary: None,
                ok: false,
                is_read_only: false,
            },
            ToolCallSummary {
                tool: "write".to_string(),
                args_summary: None,
                ok: false,
                is_read_only: false,
            },
        ]),
    ));

    scheduler.tick();

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Failed,
        "a task whose every tool call failed must be marked Failed, not Completed"
    );
}

#[test]
fn handle_completed_outcome_mixed_trace_write_failed_marks_task_failed() {
    // Issue #6397: a mixed trace (successful read + failed/policy-blocked write) is the
    // common real-world shape of #6380 under the `quarantined` trust floor — read-type
    // tools pass through while write-type tools are policy-blocked. The task must be
    // corrected to Failed even though the read call succeeded.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    make_running_task(&mut scheduler, TaskId(0), "h0");

    scheduler.buffered_events.push_back(completed_event(
        TaskId(0),
        "h0",
        Some(vec![
            ToolCallSummary {
                tool: "write".to_string(),
                args_summary: None,
                ok: false,
                is_read_only: false,
            },
            ToolCallSummary {
                tool: "read".to_string(),
                args_summary: None,
                ok: true,
                is_read_only: true,
            },
        ]),
    ));

    scheduler.tick();

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Failed,
        "a mixed trace where every write-type call failed must be corrected to Failed, \
         regardless of a successful read-type call"
    );
}

#[test]
fn handle_completed_outcome_mixed_trace_write_succeeded_preserves_completed() {
    // The inverse of #6397's mixed-trace correction: when the write-type call actually
    // succeeded, a failed read-type call must not drag the task down to Failed — read
    // failures carry no weight in the heuristic once real (write-type) work succeeded.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    make_running_task(&mut scheduler, TaskId(0), "h0");

    scheduler.buffered_events.push_back(completed_event(
        TaskId(0),
        "h0",
        Some(vec![
            ToolCallSummary {
                tool: "write".to_string(),
                args_summary: None,
                ok: true,
                is_read_only: false,
            },
            ToolCallSummary {
                tool: "read".to_string(),
                args_summary: None,
                ok: false,
                is_read_only: true,
            },
        ]),
    ));

    scheduler.tick();

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Completed,
        "a mixed trace where the write-type call succeeded must preserve Completed even if \
         a read-type call failed"
    );
}

#[test]
fn handle_completed_outcome_empty_tool_trace_preserves_completed() {
    // A task that made zero tool calls (pure reasoning/narration) is deliberately not
    // treated as total failure, per `all_tool_calls_failed`'s doc comment.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    make_running_task(&mut scheduler, TaskId(0), "h0");

    scheduler
        .buffered_events
        .push_back(completed_event(TaskId(0), "h0", Some(vec![])));

    scheduler.tick();

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Completed,
        "an empty tool trace (no tool calls made) must preserve Completed"
    );
}

#[test]
fn handle_completed_outcome_none_tool_trace_preserves_completed() {
    // Pre-existing behavior (spawn dispatch path before the CheckToolOutcome correction
    // runs) must not regress: `tool_trace: None` never triggers the Part A check.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    make_running_task(&mut scheduler, TaskId(0), "h0");

    scheduler
        .buffered_events
        .push_back(completed_event(TaskId(0), "h0", None));

    scheduler.tick();

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Completed,
        "tool_trace: None must preserve Completed (no synchronous trace available)"
    );
}

#[test]
fn handle_completed_outcome_all_tools_failed_does_not_double_count_cascade() {
    // Part A branches out via `handle_failed_outcome` *before* any Completed-branch side
    // effect runs, so the task must be recorded in `CascadeDetector::RegionHealth` exactly
    // once (as a failure), never twice (once success, once failure).
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = zeph_config::OrchestrationConfig {
        cascade_routing: true,
        topology_selection: true,
        ..make_config()
    };
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();
    assert!(
        scheduler.cascade_detector.is_some(),
        "test precondition: cascade_detector must be enabled"
    );
    make_running_task(&mut scheduler, TaskId(0), "h0");

    scheduler.buffered_events.push_back(completed_event(
        TaskId(0),
        "h0",
        Some(vec![ToolCallSummary {
            tool: "write".to_string(),
            args_summary: None,
            ok: false,
            is_read_only: false,
        }]),
    ));

    scheduler.tick();

    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Failed);
    let health = scheduler
        .cascade_detector
        .as_ref()
        .unwrap()
        .region_health()
        .get(&TaskId(0))
        .expect("region health must be recorded for this task's region");
    assert_eq!(
        health.total_tasks, 1,
        "task must be recorded exactly once in RegionHealth, not double-counted \
         (success then failure): {health:?}"
    );
    assert_eq!(
        health.failed_tasks, 1,
        "the single recorded outcome must be a failure"
    );
}

// ── DagScheduler::correct_completed_to_failed_if_all_tool_calls_failed ────────

fn scheduler_with_completed_task() -> (DagScheduler, TaskId) {
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    let task_id = TaskId(0);
    scheduler.graph.tasks[task_id.index()].status = TaskStatus::Completed;
    scheduler.graph.tasks[task_id.index()].result = Some(TaskResult {
        output: "original output".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-1".to_string()),
        agent_def: Some("worker".to_string()),
    });
    let _ = scheduler.take_graph_dirty(); // reset dirty flag set by DagScheduler::new()/init
    (scheduler, task_id)
}

#[test]
fn correct_completed_to_failed_noop_on_none_trace() {
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let corrected = scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, None);
    assert!(!corrected);
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Completed
    );
    assert!(!scheduler.take_graph_dirty());
}

#[test]
fn correct_completed_to_failed_noop_on_all_ok_trace() {
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let trace = vec![ToolCallSummary {
        tool: "read".to_string(),
        args_summary: None,
        ok: true,
        is_read_only: true,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(!corrected);
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Completed
    );
    assert!(!scheduler.take_graph_dirty());
}

#[test]
fn correct_completed_to_failed_all_read_only_calls_failed_still_corrects() {
    // The fallback rule (#6380's pre-existing full-failure case) must still fire on a trace
    // with zero write-type calls: every entry is read-type, and every one of them failed.
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let trace = vec![ToolCallSummary {
        tool: "read".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: true,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(
        corrected,
        "a trace with no write-type calls must fall back to the 'every call failed' rule"
    );
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Failed
    );
}

#[test]
fn correct_completed_to_failed_mixed_trace_write_failed_corrects() {
    // Issue #6397: a mixed trace with a successful read and a failed write must still
    // correct to Failed — the direct regression test for the scheduler-level heuristic.
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let trace = vec![
        ToolCallSummary {
            tool: "read".to_string(),
            args_summary: None,
            ok: true,
            is_read_only: true,
        },
        ToolCallSummary {
            tool: "write".to_string(),
            args_summary: None,
            ok: false,
            is_read_only: false,
        },
    ];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(
        corrected,
        "a mixed trace where the only write-type call failed must correct to Failed"
    );
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Failed
    );
}

#[test]
fn correct_completed_to_failed_mixed_trace_write_succeeded_preserves_completed() {
    // Inverse of #6397: a successful write-type call must not be dragged down by a failed
    // read-type call.
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let trace = vec![
        ToolCallSummary {
            tool: "read".to_string(),
            args_summary: None,
            ok: false,
            is_read_only: true,
        },
        ToolCallSummary {
            tool: "write".to_string(),
            args_summary: None,
            ok: true,
            is_read_only: false,
        },
    ];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(
        !corrected,
        "a successful write-type call must preserve Completed even with a failed read"
    );
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Completed
    );
}

#[test]
fn correct_completed_to_failed_partial_write_success_preserves_completed() {
    // Real-world shape not covered by the single-write-call tests above: two write-type
    // calls, one succeeded and one failed, interleaved with a successful read. Partial
    // write success is genuine progress -- `all_tool_calls_failed` requires *every*
    // write-type call to have failed, so this must not be corrected.
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let trace = vec![
        ToolCallSummary {
            tool: "read".to_string(),
            args_summary: None,
            ok: true,
            is_read_only: true,
        },
        ToolCallSummary {
            tool: "write".to_string(),
            args_summary: None,
            ok: true,
            is_read_only: false,
        },
        ToolCallSummary {
            tool: "write".to_string(),
            args_summary: None,
            ok: false,
            is_read_only: false,
        },
    ];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(
        !corrected,
        "partial write success (one write ok, one write failed) must preserve Completed"
    );
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Completed
    );
}

#[test]
fn correct_completed_to_failed_blocked_fetch_alongside_successful_read_corrects() {
    // Critic finding S2 (2026-07-17): `READONLY_TOOLS` and `QUARANTINE_DENIED` are not
    // complementary -- `fetch`, `web_scrape`, `load_skill`, and `invoke_skill` are in BOTH
    // lists (read-only for autonomy-gating purposes, yet denied under quarantine). A naive
    // `!is_read_only` classification would blind-spot a blocked `fetch` here since
    // `fetch.is_read_only == true`. The fix (`counts_toward_completion_heuristic`) must
    // still flag this trace: `read` succeeded but the only quarantine-denied call
    // (`fetch`) was blocked -- exactly the exfiltration/side-channel class quarantine
    // exists to stop, and it must not be masked by an unrelated successful plain read.
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let trace = vec![
        ToolCallSummary {
            tool: "read".to_string(),
            args_summary: None,
            ok: true,
            is_read_only: true,
        },
        ToolCallSummary {
            tool: "fetch".to_string(),
            args_summary: None,
            ok: false,
            is_read_only: true,
        },
    ];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(
        corrected,
        "a blocked fetch (quarantine-denied despite is_read_only == true) alongside a \
         successful plain read must still correct to Failed"
    );
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Failed
    );
}

#[test]
fn correct_completed_to_failed_blocked_invoke_skill_alongside_successful_read_corrects() {
    // Same S2 blind spot as the `fetch` test above, for `invoke_skill` -- also in both
    // `READONLY_TOOLS` and `QUARANTINE_DENIED` (a skill body can perform arbitrary writes,
    // critic finding M2).
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let trace = vec![
        ToolCallSummary {
            tool: "list_directory".to_string(),
            args_summary: None,
            ok: true,
            is_read_only: true,
        },
        ToolCallSummary {
            tool: "invoke_skill".to_string(),
            args_summary: None,
            ok: false,
            is_read_only: true,
        },
    ];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(
        corrected,
        "a blocked invoke_skill alongside a successful list_directory must correct to Failed"
    );
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Failed
    );
}

#[test]
fn correct_completed_to_failed_successful_fetch_alongside_failed_read_preserves_completed() {
    // Inverse of the S2 regression tests above: when the quarantine-denied-but-read-only
    // call actually succeeded, a failed plain read must not drag the task down -- mirrors
    // the existing mixed-trace inverse tests for plain write/read.
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let trace = vec![
        ToolCallSummary {
            tool: "read".to_string(),
            args_summary: None,
            ok: false,
            is_read_only: true,
        },
        ToolCallSummary {
            tool: "fetch".to_string(),
            args_summary: None,
            ok: true,
            is_read_only: true,
        },
    ];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(
        !corrected,
        "a successful fetch (quarantine-denied-class call) must preserve Completed even with \
         a failed plain read"
    );
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Completed
    );
}

#[test]
fn correct_completed_to_failed_plain_read_only_trace_all_failed_still_corrects() {
    // Fallback-rule regression, refined for the S2 fix: a trace with no counting calls at
    // all (every entry both is_read_only == true and NOT quarantine-denied) must still fall
    // back to the "every call failed" rule when every entry failed -- `list_directory` is
    // read-only and not in QUARANTINE_DENIED, unlike `fetch`/`invoke_skill` above.
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let trace = vec![ToolCallSummary {
        tool: "list_directory".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: true,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(
        corrected,
        "a trace with zero counting calls (plain, non-denied reads only) must fall back to \
         the 'every call failed' rule"
    );
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Failed
    );
}

#[test]
fn correct_completed_to_failed_noop_on_empty_trace() {
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&[]));
    assert!(!corrected);
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Completed
    );
}

#[test]
fn correct_completed_to_failed_noop_when_task_not_completed() {
    // Must never clobber a later transition — e.g. a task already Failed by a different
    // path, or still Running.
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    scheduler.graph.tasks[task_id.index()].status = TaskStatus::Failed;
    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(
        !corrected,
        "correction must no-op when the task's current status is not Completed"
    );
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Failed
    );
}

#[test]
fn correct_completed_to_failed_success_flips_status_and_marks_output() {
    let (mut scheduler, task_id) = scheduler_with_completed_task();
    let trace = vec![
        ToolCallSummary {
            tool: "write".to_string(),
            args_summary: None,
            ok: false,
            is_read_only: false,
        },
        ToolCallSummary {
            tool: "bash".to_string(),
            args_summary: None,
            ok: false,
            is_read_only: false,
        },
    ];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(task_id, Some(&trace));
    assert!(corrected);
    assert_eq!(
        scheduler.graph.tasks[task_id.index()].status,
        TaskStatus::Failed
    );
    let output = &scheduler.graph.tasks[task_id.index()]
        .result
        .as_ref()
        .unwrap()
        .output;
    assert!(
        output.starts_with("original output"),
        "correction must append to, not replace, the original output: {output}"
    );
    assert!(
        output.contains("corrected") && output.contains('2'),
        "correction marker must be present and mention the failed call count: {output}"
    );
    assert!(
        scheduler.take_graph_dirty(),
        "a genuine status correction must set graph_dirty"
    );
}

// ── DagScheduler::propagate_corrected_task_failure (#6396) ────────────────────

#[test]
fn propagate_corrected_task_failure_cancels_running_dependent_and_fails_graph() {
    // Two-task graph: task 1 depends on task 0. Task 0 was already corrected
    // Completed -> Failed (mirroring the spawn-path CheckToolOutcome flow); task 1 had
    // already been unblocked and dispatched (Running) before the correction landed. The
    // default failure strategy (Abort, see `make_config`) must cancel task 1 and fail the
    // graph — parity with the RunInline path's `handle_failed_outcome`.
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[0])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "original output".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });
    make_running_task(&mut scheduler, TaskId(1), "h1");
    let _ = scheduler.take_graph_dirty();

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected, "test precondition: task 0 must be corrected");

    let actions = scheduler.propagate_corrected_task_failure(TaskId(0));

    assert!(
        actions.iter().any(
            |a| matches!(a, SchedulerAction::Cancel { agent_handle_id } if agent_handle_id == "h1")
        ),
        "the already-Running dependent must be canceled: {actions:?}"
    );
    assert!(
        actions.iter().any(
            |a| matches!(a, SchedulerAction::Done { status } if *status == GraphStatus::Failed)
        ),
        "GraphStatus leaving Running must emit a Done action: {actions:?}"
    );
    assert_eq!(scheduler.graph.status, GraphStatus::Failed);
    assert!(scheduler.graph.finished_at.is_some());
    assert!(
        !scheduler.running.contains_key(&TaskId(1)),
        "the canceled dependent must be removed from the running map"
    );
}

#[test]
fn propagate_corrected_task_failure_cancels_pending_commanded_from_target() {
    // Finding 1 (code review, 2026-07-17): a Command-handoff target `try_handoff` already
    // activated (linked via `commanded_from`, not `depends_on` -- the whole point of
    // runtime-chosen routing) before a spawn-path source is corrected Completed -> Failed
    // must be cancelled too, or it runs against state its source never legitimately
    // produced. Three-task graph: 0 is the corrected source, 1 is its handoff target (no
    // depends_on edge back to 0), 2 depends on 1 -- proves both the direct target and its
    // own transitive depends_on subtree get skipped (mirrors
    // `resolve_dormant_after_terminal`'s reasoning for an un-triggered route_to fallback).
    let graph = graph_from_nodes(vec![
        make_node(0, &[]),
        make_node(1, &[]),
        make_node(2, &[1]),
    ]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "claimed done, handed off".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });
    // Simulate try_handoff's post-activation state: target 1 is Ready, commanded_from
    // links back to source 0, with no depends_on edge.
    scheduler.graph.tasks[1].status = TaskStatus::Ready;
    scheduler.graph.tasks[1].commanded_from = Some(TaskId(0));

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected, "test precondition: task 0 must be corrected");

    let _ = scheduler.propagate_corrected_task_failure(TaskId(0));

    assert_eq!(
        scheduler.graph.tasks[1].status,
        TaskStatus::Skipped,
        "a Pending/Ready commanded_from target must be cancelled when its source is \
         corrected to Failed post-hoc"
    );
    assert_eq!(
        scheduler.graph.tasks[2].status,
        TaskStatus::Skipped,
        "a depends_on dependent of the cancelled commanded_from target must also be \
         skipped, or it would strand in Pending forever"
    );
}

#[test]
fn propagate_corrected_task_failure_leaves_running_commanded_from_target_untouched() {
    // Deliberate scope boundary (Finding 1's fix): an already-Running commanded_from
    // target is the pre-existing, accepted "already-unblocked work is not unwound"
    // limitation, same as an ordinary Running depends_on dependent -- must not be
    // cancelled/skipped by this fix. Uses a per-task Skip failure strategy on the source
    // (rather than the default Abort) so the assertion isolates this fix's own behavior
    // from Abort's unrelated "cancel every Running task in the graph" global effect.
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].failure_strategy = Some(zeph_config::FailureStrategy::Skip);
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "claimed done, handed off".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });
    scheduler.graph.tasks[1].commanded_from = Some(TaskId(0));
    make_running_task(&mut scheduler, TaskId(1), "h1");

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected, "test precondition: task 0 must be corrected");

    let actions = scheduler.propagate_corrected_task_failure(TaskId(0));

    assert_eq!(
        scheduler.graph.tasks[1].status,
        TaskStatus::Running,
        "an already-Running commanded_from target is out of this fix's scope"
    );
    assert!(
        !actions.iter().any(
            |a| matches!(a, SchedulerAction::Cancel { agent_handle_id } if agent_handle_id == "h1")
        ),
        "a Running commanded_from target must not be cancelled by this fix: {actions:?}"
    );
}

#[test]
fn propagate_corrected_task_failure_does_not_double_count_cascade() {
    // #6396's design note: `dag::propagate_failure` never touches `cascade_detector` —
    // calling it from `propagate_corrected_task_failure` must not change RegionHealth,
    // which was already recorded (as a success) by `handle_completed_outcome` before the
    // correction landed.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let config = zeph_config::OrchestrationConfig {
        cascade_routing: true,
        topology_selection: true,
        ..make_config()
    };
    let defs = vec![make_def("worker")];
    let mut scheduler =
        DagScheduler::new(graph, &config, Box::new(FirstRouter), defs, None).unwrap();
    assert!(
        scheduler.cascade_detector.is_some(),
        "test precondition: cascade_detector must be enabled"
    );
    make_running_task(&mut scheduler, TaskId(0), "h0");

    // Simulate the spawn dispatch path: tool_trace is None at completion time, so
    // handle_completed_outcome's #6380 RunInline branch does not fire and the task
    // completes normally, recording a cascade success.
    scheduler
        .buffered_events
        .push_back(completed_event(TaskId(0), "h0", None));
    scheduler.tick();
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Completed);

    let region_health_before = scheduler
        .cascade_detector
        .as_ref()
        .unwrap()
        .region_health()
        .get(&TaskId(0))
        .expect("region health must be recorded")
        .clone();
    assert_eq!(region_health_before.total_tasks, 1);
    assert_eq!(region_health_before.failed_tasks, 0);

    // Post-hoc correction, as CheckToolOutcome would trigger.
    let trace = vec![
        ToolCallSummary {
            tool: "read".to_string(),
            args_summary: None,
            ok: true,
            is_read_only: true,
        },
        ToolCallSummary {
            tool: "write".to_string(),
            args_summary: None,
            ok: false,
            is_read_only: false,
        },
    ];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected);
    let _ = scheduler.propagate_corrected_task_failure(TaskId(0));

    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Failed);
    let region_health_after = scheduler
        .cascade_detector
        .as_ref()
        .unwrap()
        .region_health()
        .get(&TaskId(0))
        .expect("region health must still be present")
        .clone();
    assert_eq!(
        region_health_after.total_tasks, region_health_before.total_tasks,
        "propagate_corrected_task_failure must not change RegionHealth: {region_health_after:?}"
    );
    assert_eq!(
        region_health_after.failed_tasks, region_health_before.failed_tasks,
        "propagate_corrected_task_failure must not re-record this task as a failure: \
         {region_health_after:?}"
    );
}

#[test]
fn propagate_corrected_task_failure_noop_when_no_dependents_and_graph_stays_running() {
    // Skip strategy on a task with no dependents: propagate_failure marks the task
    // Skipped-subtree (a no-op here since there are no dependents) and does not touch
    // GraphStatus, since other tasks in the graph are still non-terminal.
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].failure_strategy = Some(zeph_config::FailureStrategy::Skip);
    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "original output".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected);

    let actions = scheduler.propagate_corrected_task_failure(TaskId(0));
    assert!(
        actions.is_empty(),
        "Skip strategy with no running dependents and a still-Running graph must emit no \
         actions: {actions:?}"
    );
    assert_eq!(
        scheduler.graph.status,
        GraphStatus::Running,
        "GraphStatus must remain Running while task 1 is still non-terminal"
    );
}

#[test]
fn propagate_corrected_task_failure_retry_strategy_forces_terminal_failure() {
    // Critic finding S1 (2026-07-17): under `FailureStrategy::Retry`, generic
    // `dag::propagate_failure` would resurrect the *same* corrected task back to `Ready` for
    // another attempt -- but this task was already `Completed` (cascade accounting already
    // ran, dependents already unblocked) before the correction landed, so a resurrection
    // would trigger a redundant redispatch and double-count RegionHealth on its second
    // completion. `propagate_corrected_task_failure` must instead force terminal Abort-style
    // behavior for Retry, via `dag::propagate_failure_forced_terminal`: the task stays
    // `Failed` (never resurrected), `retry_count` is untouched, and the graph fails.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].failure_strategy = Some(zeph_config::FailureStrategy::Retry);
    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "original output".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });
    assert_eq!(scheduler.graph.tasks[0].retry_count, 0);

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected, "test precondition: task 0 must be corrected");
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Failed);

    let actions = scheduler.propagate_corrected_task_failure(TaskId(0));

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Failed,
        "Retry must NOT resurrect an already-completed corrected task to Ready -- that would \
         trigger a redundant redispatch and double-count RegionHealth (critic finding S1)"
    );
    assert_eq!(
        scheduler.graph.tasks[0].retry_count, 0,
        "no retry attempt was made, so retry_count must not increment"
    );
    assert_eq!(
        scheduler.graph.status,
        GraphStatus::Failed,
        "Retry is forced to terminal Abort-style behavior for a post-hoc correction"
    );
    assert!(
        actions.iter().any(
            |a| matches!(a, SchedulerAction::Done { status } if *status == GraphStatus::Failed)
        ),
        "GraphStatus leaving Running must emit a Done action: {actions:?}"
    );
}

#[test]
fn propagate_corrected_task_failure_retry_then_tick_emits_no_spawn() {
    // Follow-up to the forced-terminal test above: since the task is never resurrected under
    // Retry, driving an actual `tick()` after the correction must emit zero Spawn actions for
    // it -- the graph is already terminal (Failed), so tick() returns Done immediately.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].failure_strategy = Some(zeph_config::FailureStrategy::Retry);
    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "original output".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected);
    let _ = scheduler.propagate_corrected_task_failure(TaskId(0));
    assert_eq!(scheduler.graph.tasks[0].status, TaskStatus::Failed);
    assert_eq!(scheduler.graph.status, GraphStatus::Failed);

    let actions = scheduler.tick();
    let spawn_count = actions
        .iter()
        .filter(|a| matches!(a, SchedulerAction::Spawn { task_id, .. } if *task_id == TaskId(0)))
        .count();
    assert_eq!(
        spawn_count, 0,
        "a task forced to terminal Failed under Retry must never be redispatched: {actions:?}"
    );
    assert!(
        actions.iter().any(
            |a| matches!(a, SchedulerAction::Done { status } if *status == GraphStatus::Failed)
        ),
        "tick() on an already-terminal graph must return Done: {actions:?}"
    );
}

#[test]
fn propagate_corrected_task_failure_ask_strategy_forces_terminal_failure_instead_of_pause() {
    // Companion to the Retry test: `FailureStrategy::Ask` would normally pause the whole
    // graph (`GraphStatus::Paused`) via generic `dag::propagate_failure` -- but pausing an
    // already-completed-then-corrected task's plan post-hoc is equally unsafe/meaningless
    // here (critic finding S1's `Ask` variant), so it must also force terminal Failed.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].failure_strategy = Some(zeph_config::FailureStrategy::Ask);
    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "original output".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected);

    let actions = scheduler.propagate_corrected_task_failure(TaskId(0));

    assert_eq!(
        scheduler.graph.status,
        GraphStatus::Failed,
        "Ask must not pause the graph for a post-hoc correction -- it is forced to terminal \
         Failed instead (critic finding S1)"
    );
    assert!(
        actions.iter().any(
            |a| matches!(a, SchedulerAction::Done { status } if *status == GraphStatus::Failed)
        ),
        "GraphStatus leaving Running must emit a Done action: {actions:?}"
    );
}

#[test]
fn propagate_corrected_task_failure_retry_with_state_injection_does_not_recover() {
    // Regression for the developer's own design note on `propagate_failure_forced_terminal`
    // (dag.rs): "Considered and rejected including Mode-1 recovery ... `try_recover` would
    // silently flip the just-corrected `Failed` status back to `Completed`". That claim was
    // true by code inspection (the forced-terminal function never calls `try_recover`) but
    // had no test locking it in -- the *generic* `dag::propagate_failure`'s retry-exhausted
    // arm DOES invoke Mode-1 recovery when `recovery.state_injection` is configured (see
    // `test_propagate_failure_retry_exhausted_recovers_with_state_injection` in dag.rs), so
    // this is a real divergence a future refactor could silently reintroduce by routing the
    // forced-terminal case back through the generic function. Configure the task with a
    // `state_injection` fallback that *would* flip it back to Completed under the generic
    // path, and confirm the forced-terminal path leaves it Failed instead.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].failure_strategy = Some(zeph_config::FailureStrategy::Retry);
    scheduler.graph.tasks[0].max_retries = Some(3);
    scheduler.graph.tasks[0].retry_count = 3; // at max -- would be "exhausted" under the generic path
    scheduler.graph.tasks[0].recovery = Some(crate::graph::RecoveryAction {
        state_injection: Some("fallback output".to_string()),
        route_to: None,
    });
    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "original output".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected);

    let _ = scheduler.propagate_corrected_task_failure(TaskId(0));

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Failed,
        "the forced-terminal path must NOT invoke Mode-1 recovery -- a configured \
         state_injection fallback must not silently flip the just-corrected Failed status \
         back to Completed, which no already-unblocked dependent would ever see"
    );
    assert_ne!(
        scheduler.graph.tasks[0]
            .result
            .as_ref()
            .unwrap()
            .agent_def
            .as_deref(),
        Some("__recovery__"),
        "the recovery marker must never appear -- confirms try_recover was not invoked"
    );
    assert_eq!(scheduler.graph.status, GraphStatus::Failed);
}

#[test]
fn propagate_corrected_task_failure_abort_with_state_injection_does_not_recover() {
    // Critic finding S1-residual (2026-07-17): the default `Abort` strategy's arm in
    // `dag::propagate_failure` calls `try_recover` *before* terminal-failing the graph. When
    // `recovery.state_injection` is configured, that would flip this just-corrected task
    // straight back to `Completed` with injected output -- silently undoing the correction
    // exactly like the `Retry`/`Ask` hazard the sibling test above locks in. This is the
    // default-strategy companion to `..._retry_with_state_injection_does_not_recover`: no
    // explicit `failure_strategy` override, relying on `make_config`'s `default_failure_strategy
    // = Abort`.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    assert_eq!(
        scheduler.graph.default_failure_strategy,
        zeph_config::FailureStrategy::Abort,
        "test precondition: default strategy must be Abort (unconfigured failure_strategy)"
    );
    scheduler.graph.tasks[0].recovery = Some(crate::graph::RecoveryAction {
        state_injection: Some("fallback output".to_string()),
        route_to: None,
    });
    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "original output".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected);

    let actions = scheduler.propagate_corrected_task_failure(TaskId(0));

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Failed,
        "default Abort strategy + state_injection must NOT invoke Mode-1 recovery on a \
         post-hoc correction -- the injected fallback would never be seen by dependents that \
         already consumed the original (now-invalidated) output"
    );
    assert_ne!(
        scheduler.graph.tasks[0]
            .result
            .as_ref()
            .unwrap()
            .agent_def
            .as_deref(),
        Some("__recovery__"),
        "the recovery marker must never appear -- confirms try_recover was not invoked"
    );
    assert_eq!(scheduler.graph.status, GraphStatus::Failed);
    assert!(
        actions.iter().any(
            |a| matches!(a, SchedulerAction::Done { status } if *status == GraphStatus::Failed)
        ),
        "GraphStatus leaving Running must emit a Done action: {actions:?}"
    );
}

#[test]
fn propagate_corrected_task_failure_skip_with_state_injection_still_uses_generic_propagate() {
    // Companion negative test: `Skip`'s arm in `dag::propagate_failure` never calls
    // `try_recover` (it goes straight to `skip_subtree`), so a `Skip`-configured task with
    // `state_injection` configured is safe via the *unmodified* generic `propagate_failure`
    // path -- it must NOT be routed through `propagate_failure_forced_terminal`. Distinguishing
    // signal: `Skip`'s arm flips the failed task's own status to `Skipped` (not left `Failed`,
    // unlike the forced-terminal path), which only the generic path does.
    let graph = graph_from_nodes(vec![make_node(0, &[])]);
    let mut scheduler = make_scheduler(graph);
    scheduler.graph.tasks[0].failure_strategy = Some(zeph_config::FailureStrategy::Skip);
    scheduler.graph.tasks[0].recovery = Some(crate::graph::RecoveryAction {
        state_injection: Some("fallback output".to_string()),
        route_to: None,
    });
    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "original output".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected);

    let _ = scheduler.propagate_corrected_task_failure(TaskId(0));

    assert_eq!(
        scheduler.graph.tasks[0].status,
        TaskStatus::Skipped,
        "Skip's arm must run unmodified (flips to Skipped, not left Failed) even with \
         state_injection configured -- Skip never calls try_recover, so it needs no \
         forced-terminal special-case"
    );
}

#[test]
fn propagate_corrected_task_failure_leaves_already_completed_dependent_untouched() {
    // Documented remaining limitation on `propagate_corrected_task_failure`: a dependent
    // that already reached a terminal status (typically Completed, having consumed the
    // now-invalidated output) before the correction landed is not retroactively unwound --
    // `dag::propagate_failure`'s cancellation/skip/retry logic only affects dependents
    // still Pending/Ready/Running. This locks in that documented behavior as a regression
    // test rather than leaving it purely as a doc comment.
    let graph = graph_from_nodes(vec![make_node(0, &[]), make_node(1, &[0])]);
    let mut scheduler = make_scheduler(graph);

    scheduler.graph.tasks[0].status = TaskStatus::Completed;
    scheduler.graph.tasks[0].result = Some(TaskResult {
        output: "original output".to_string(),
        artifacts: vec![],
        duration_ms: 10,
        agent_id: Some("agent-0".to_string()),
        agent_def: Some("worker".to_string()),
    });
    scheduler.graph.tasks[1].status = TaskStatus::Completed;
    scheduler.graph.tasks[1].result = Some(TaskResult {
        output: "dependent already finished using task 0's now-invalidated output".to_string(),
        artifacts: vec![],
        duration_ms: 5,
        agent_id: Some("agent-1".to_string()),
        agent_def: Some("worker".to_string()),
    });

    let trace = vec![ToolCallSummary {
        tool: "write".to_string(),
        args_summary: None,
        ok: false,
        is_read_only: false,
    }];
    let corrected =
        scheduler.correct_completed_to_failed_if_all_tool_calls_failed(TaskId(0), Some(&trace));
    assert!(corrected);

    let actions = scheduler.propagate_corrected_task_failure(TaskId(0));

    assert_eq!(
        scheduler.graph.tasks[1].status,
        TaskStatus::Completed,
        "a dependent that already completed before the correction landed is not \
         retroactively unwound (documented limitation)"
    );
    assert!(
        actions.iter().any(
            |a| matches!(a, SchedulerAction::Done { status } if *status == GraphStatus::Failed)
        ),
        "the graph must still terminalize as Failed even though the dependent stayed \
         Completed -- task 0 itself is Failed and no non-terminal task remains: {actions:?}"
    );
}