periplon 0.2.0

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

use crate::adapters::primary::PeriplonSDKClient;
use crate::dsl::hooks::{ErrorRecovery, HooksExecutor};
use crate::dsl::loop_context::{substitute_task_variables, LoopContext};
use crate::dsl::message_bus::MessageBus;
use crate::dsl::notifications::{NotificationContext, NotificationManager};
use crate::dsl::schema::{AgentSpec, CollectionSource, DSLWorkflow, FileFormat, LoopSpec};
use crate::dsl::state::{StatePersistence, WorkflowState};
use crate::dsl::task_graph::{TaskGraph, TaskStatus};
use crate::error::{Error, Result};
use crate::options::AgentOptions;
use futures::StreamExt;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::{Mutex, Semaphore};

/// Execution context for loop and task execution
/// Groups commonly-passed parameters to avoid too_many_arguments clippy warnings
struct ExecutionContext<'a> {
    workflow_inputs: &'a HashMap<String, serde_json::Value>,
    agents: &'a Arc<Mutex<HashMap<String, PeriplonSDKClient>>>,
    task_graph: &'a Arc<Mutex<TaskGraph>>,
    state: &'a Arc<Mutex<Option<WorkflowState>>>,
    workflow_name: &'a Arc<String>,
    json_output: bool,
}

/// DSL Executor for running workflows
pub struct DSLExecutor {
    workflow: DSLWorkflow,
    agents: HashMap<String, PeriplonSDKClient>,
    task_graph: TaskGraph,
    message_bus: Arc<MessageBus>,
    state: Option<WorkflowState>,
    state_persistence: Option<StatePersistence>,
    resolved_inputs: HashMap<String, serde_json::Value>,
    notification_manager: Arc<NotificationManager>,
    workflow_start_time: Option<Instant>,
    json_output: bool,
}

impl DSLExecutor {
    /// Create a new DSL executor
    ///
    /// # Arguments
    ///
    /// * `workflow` - The workflow to execute
    ///
    /// # Returns
    ///
    /// Result containing the executor or an error
    pub fn new(workflow: DSLWorkflow) -> Result<Self> {
        // Resolve workflow inputs (use defaults)
        let resolved_inputs = Self::resolve_workflow_inputs(&workflow);

        // Initialize notification manager
        let notification_manager = Arc::new(NotificationManager::new());

        Ok(DSLExecutor {
            workflow,
            agents: HashMap::new(),
            task_graph: TaskGraph::new(),
            message_bus: Arc::new(MessageBus::new()),
            state: None,
            state_persistence: None,
            resolved_inputs,
            notification_manager,
            workflow_start_time: None,
            json_output: false,
        })
    }

    /// Get a reference to the task graph (for testing and inspection)
    pub fn task_graph(&self) -> &TaskGraph {
        &self.task_graph
    }

    /// Resolve workflow inputs by extracting default values
    fn resolve_workflow_inputs(workflow: &DSLWorkflow) -> HashMap<String, serde_json::Value> {
        let mut resolved = HashMap::new();

        for (key, input_spec) in &workflow.inputs {
            if let Some(default_value) = &input_spec.default {
                resolved.insert(key.clone(), default_value.clone());
            }
        }

        resolved
    }

    /// Substitute workflow and task variables in a string
    ///
    /// Supports:
    /// - ${workflow.variable_name} - Replace with workflow input value
    /// - ${task.variable_name} - Replace with task input value
    fn substitute_variables(
        text: &str,
        workflow_inputs: &HashMap<String, serde_json::Value>,
        task_inputs: &HashMap<String, serde_json::Value>,
    ) -> String {
        let mut result = text.to_string();

        // Replace ${workflow.variable} with workflow input values
        for (key, value) in workflow_inputs {
            let placeholder = format!("${{workflow.{}}}", key);
            let value_str = match value {
                serde_json::Value::String(s) => s.clone(),
                serde_json::Value::Number(n) => n.to_string(),
                serde_json::Value::Bool(b) => b.to_string(),
                _ => serde_json::to_string(value).unwrap_or_default(),
            };
            result = result.replace(&placeholder, &value_str);
        }

        // Replace ${task.variable} with task input values
        for (key, value) in task_inputs {
            let placeholder = format!("${{task.{}}}", key);
            let value_str = match value {
                serde_json::Value::String(s) => s.clone(),
                serde_json::Value::Number(n) => n.to_string(),
                serde_json::Value::Bool(b) => b.to_string(),
                _ => serde_json::to_string(value).unwrap_or_default(),
            };
            result = result.replace(&placeholder, &value_str);
        }

        result
    }

    /// Create a notification context with task metadata
    ///
    /// # Arguments
    ///
    /// * `task_id` - ID of the task
    /// * `task_status` - Status of the task (completed, failed, etc.)
    /// * `duration` - Task execution duration
    /// * `error_msg` - Optional error message
    fn create_notification_context(
        &self,
        task_id: &str,
        task_status: &str,
        duration: Option<std::time::Duration>,
        error_msg: Option<&str>,
    ) -> NotificationContext {
        let mut context = NotificationContext::new();

        // Add workflow-level variables
        for (key, value) in &self.resolved_inputs {
            let value_str = match value {
                serde_json::Value::String(s) => s.clone(),
                serde_json::Value::Number(n) => n.to_string(),
                serde_json::Value::Bool(b) => b.to_string(),
                _ => serde_json::to_string(value).unwrap_or_default(),
            };
            context = context.with_workflow_var(key, value_str);
        }

        // Add task metadata
        context = context
            .with_metadata("task_id", task_id)
            .with_metadata("task_status", task_status)
            .with_metadata("workflow_name", &self.workflow.name);

        if let Some(dur) = duration {
            context = context.with_metadata("duration_secs", dur.as_secs().to_string());
            context = context.with_metadata("duration_human", format!("{:.2}s", dur.as_secs_f64()));
        }

        if let Some(err) = error_msg {
            context = context.with_metadata("error", err);
        }

        // Add secrets from workflow (just the keys, not values)
        for secret_name in self.workflow.secrets.keys() {
            // Secrets are resolved at runtime via environment or other sources
            // For now, we'll just mark them as available in the context
            context = context.with_secret(secret_name, format!("${{secret.{}}}", secret_name));
        }

        context
    }

    /// Enable state persistence for this workflow
    ///
    /// # Arguments
    ///
    /// * `state_dir` - Directory to store state files (default: ".workflow_states")
    pub fn enable_state_persistence(&mut self, state_dir: Option<&str>) -> Result<()> {
        let persistence = if let Some(dir) = state_dir {
            StatePersistence::new(dir)?
        } else {
            StatePersistence::default()
        };

        self.state_persistence = Some(persistence);

        // Try to load existing state for resume
        if let Some(ref persistence) = self.state_persistence {
            if persistence.has_state(&self.workflow.name) {
                println!(
                    "Found existing state for workflow '{}' - will resume if possible",
                    self.workflow.name
                );
            }
        }

        Ok(())
    }

    /// Set JSON output mode
    ///
    /// When enabled, messages are output in full JSON format for programmatic processing.
    /// When disabled (default), messages are formatted for interactive terminal display
    /// with colors and condensed output.
    ///
    /// # Arguments
    ///
    /// * `json` - True for JSON mode, false for interactive mode
    pub fn set_json_output(&mut self, json: bool) {
        self.json_output = json;
    }

    /// Try to resume from saved state
    ///
    /// Returns true if workflow was resumed, false if starting fresh
    pub fn try_resume(&mut self) -> Result<bool> {
        if let Some(ref persistence) = self.state_persistence {
            if persistence.has_state(&self.workflow.name) {
                let saved_state = persistence.load_state(&self.workflow.name)?;

                if saved_state.can_resume() {
                    println!(
                        "Resuming workflow '{}' from checkpoint (progress: {:.1}%)",
                        self.workflow.name,
                        saved_state.get_progress() * 100.0
                    );

                    self.state = Some(saved_state);
                    return Ok(true);
                } else {
                    println!(
                        "Cannot resume workflow '{}' - status: {:?}",
                        self.workflow.name, saved_state.status
                    );
                }
            }
        }

        Ok(false)
    }

    /// Checkpoint the current workflow state
    fn checkpoint_state(&mut self) -> Result<()> {
        if let (Some(ref mut state), Some(ref persistence)) =
            (&mut self.state, &self.state_persistence)
        {
            persistence.save_state(state)?;
        }
        Ok(())
    }

    /// Get a reference to the message bus
    pub fn message_bus(&self) -> Arc<MessageBus> {
        self.message_bus.clone()
    }

    /// Get the current workflow state
    pub fn get_state(&self) -> Option<&WorkflowState> {
        self.state.as_ref()
    }

    /// Initialize the executor by creating agents and building the task graph
    pub async fn initialize(&mut self) -> Result<()> {
        // Register agents with message bus
        for agent_name in self.workflow.agents.keys() {
            self.message_bus.register_agent(agent_name.clone()).await?;
        }

        // Create communication channels from workflow configuration
        if let Some(comm_config) = &self.workflow.communication {
            for (channel_name, channel_spec) in &comm_config.channels {
                self.message_bus
                    .create_channel(
                        channel_name.clone(),
                        channel_spec.description.clone(),
                        channel_spec.participants.clone(),
                        channel_spec.message_format.clone(),
                    )
                    .await?;
            }
        }

        // Create variable context for interpolation
        let mut var_context = crate::dsl::variables::VariableContext::new();
        for (key, value) in &self.resolved_inputs {
            var_context.insert(&crate::dsl::variables::Scope::Workflow, key, value.clone());
        }

        // Create agent instances
        for (name, spec) in &self.workflow.agents {
            let options = self.agent_spec_to_options(
                spec,
                self.workflow.cwd.as_deref(),
                self.workflow.create_cwd,
                &var_context,
            )?;
            let mut client = PeriplonSDKClient::new(options);
            client.connect(None).await?;
            self.agents.insert(name.clone(), client);
        }

        // Build task graph with hierarchical tasks flattened
        // Collect tasks first to avoid borrow checker issues
        let tasks: Vec<(String, crate::dsl::schema::TaskSpec)> = self
            .workflow
            .tasks
            .iter()
            .map(|(name, spec)| (name.clone(), spec.clone()))
            .collect();

        for (name, spec) in tasks {
            self.add_hierarchical_task(&name, &spec, None)?;
        }

        println!(
            "Initialized {} agents and {} channels",
            self.message_bus.agent_count().await,
            self.message_bus.channel_count().await
        );

        // Initialize workflow state if persistence is enabled and not resuming
        if self.state_persistence.is_some() && self.state.is_none() {
            let mut state =
                WorkflowState::new(self.workflow.name.clone(), self.workflow.version.clone());

            // Register all tasks in state
            for task_id in self.task_graph.topological_sort()? {
                state.update_task_status(&task_id, TaskStatus::Pending);
            }

            self.state = Some(state);
            println!("Initialized workflow state tracking");
        }

        Ok(())
    }

    /// Add a task and its subtasks to the graph recursively
    ///
    /// # Arguments
    ///
    /// * `task_name` - Name of the task
    /// * `task_spec` - Task specification
    /// * `parent_name` - Optional parent task name for dependency tracking
    fn add_hierarchical_task(
        &mut self,
        task_name: &str,
        task_spec: &crate::dsl::schema::TaskSpec,
        parent_name: Option<&str>,
    ) -> Result<()> {
        // Create a modified spec for this task (without subtasks, as they'll be separate)
        let mut task_spec_flat = task_spec.clone();

        // If this task has subtasks, we'll add dependencies to them
        let has_subtasks = !task_spec.subtasks.is_empty();

        // Build a map of sibling task names for dependency resolution
        let sibling_names: std::collections::HashSet<String> = if let Some(parent) = parent_name {
            // Get parent task spec to find all siblings
            if let Some(parent_task) = self.workflow.tasks.get(parent) {
                parent_task
                    .subtasks
                    .iter()
                    .flat_map(|map| map.keys())
                    .map(|s| s.to_string())
                    .collect()
            } else {
                std::collections::HashSet::new()
            }
        } else {
            std::collections::HashSet::new()
        };

        // Resolve dependency names to full hierarchical names for sibling references
        if let Some(parent) = parent_name {
            task_spec_flat.depends_on = task_spec_flat
                .depends_on
                .iter()
                .map(|dep| {
                    if sibling_names.contains(dep) {
                        format!("{}.{}", parent, dep)
                    } else {
                        dep.clone()
                    }
                })
                .collect();

            // Also resolve parallel_with references
            task_spec_flat.parallel_with = task_spec_flat
                .parallel_with
                .iter()
                .map(|task| {
                    if sibling_names.contains(task) {
                        format!("{}.{}", parent, task)
                    } else {
                        task.clone()
                    }
                })
                .collect();
        }

        // Clear subtasks from the flat spec (they'll be added as separate tasks)
        // EXCEPT if this task has a loop_spec - in that case we need the subtasks
        // to execute them within each loop iteration
        let has_loop = task_spec_flat.loop_spec.is_some();
        if !has_loop {
            task_spec_flat.subtasks.clear();
        }

        // Determine if this is an executable task
        // A task is executable if it has an execution type AND no subtasks
        // OR if it has no execution type AND no subtasks (leaf task)
        // OR if it has a loop_spec (loops with subtasks need to execute the subtasks within each iteration)
        // Tasks with subtasks but no loop are NOT executable (they're organizational parents)
        let is_executable = !has_subtasks || has_loop;

        // If this task has a parent, add parent as dependency only if parent is executable
        if let Some(parent) = parent_name {
            // Check if parent task is executable by looking it up
            // A parent is only executable if it has no subtasks
            let parent_is_executable = self
                .workflow
                .tasks
                .get(parent)
                .map(|parent_spec| parent_spec.subtasks.is_empty())
                .unwrap_or(true);

            if parent_is_executable && !task_spec_flat.depends_on.contains(&parent.to_string()) {
                task_spec_flat.depends_on.push(parent.to_string());
            }
        }

        // Resolve dependencies on non-executable parent tasks to their leaf subtasks
        let mut resolved_dependencies = Vec::new();
        for dep in &task_spec_flat.depends_on {
            if let Some(dep_task) = self.workflow.tasks.get(dep) {
                // Check if the dependency is a non-executable parent (has subtasks but no loop)
                // Tasks with loops are executable even if they have subtasks
                let dep_has_loop = dep_task.loop_spec.is_some();
                let is_non_executable_parent = !dep_task.subtasks.is_empty() && !dep_has_loop;

                if is_non_executable_parent {
                    // Resolve to leaf subtasks - we need to collect all leaf tasks of this parent
                    // For now, add all immediate subtasks (this will be further resolved recursively)
                    for subtask_map in &dep_task.subtasks {
                        for subtask_name in subtask_map.keys() {
                            resolved_dependencies.push(format!("{}.{}", dep, subtask_name));
                        }
                    }
                } else {
                    // Task is executable (either has no subtasks, or has loop+subtasks)
                    resolved_dependencies.push(dep.clone());
                }
            } else {
                // Dependency not found in workflow tasks, keep as-is (might be a hierarchical reference)
                resolved_dependencies.push(dep.clone());
            }
        }
        task_spec_flat.depends_on = resolved_dependencies;

        // Add this task to the graph only if it's an executable task
        if is_executable {
            self.task_graph
                .add_task(task_name.to_string(), task_spec_flat);
        }

        // Recursively add subtasks
        // EXCEPT if the parent has a loop - in that case, subtasks are managed by the loop executor
        if has_subtasks && !has_loop {
            for subtask_map in &task_spec.subtasks {
                for (subtask_name, subtask_spec) in subtask_map {
                    let full_subtask_name = format!("{}.{}", task_name, subtask_name);

                    // Apply inheritance from parent task to subtask
                    let mut inherited_subtask_spec = subtask_spec.clone();
                    inherited_subtask_spec.inherit_from_parent(task_spec);

                    // Subtasks depend on their parent task by default
                    self.add_hierarchical_task(
                        &full_subtask_name,
                        &inherited_subtask_spec,
                        Some(task_name),
                    )?;
                }
            }
        }

        Ok(())
    }

    /// Execute the workflow
    ///
    /// Executes tasks in topological order, respecting dependencies
    /// with support for parallel execution and hooks
    pub async fn execute(&mut self) -> Result<()> {
        // Run pre-workflow hooks if they exist
        if let Some(workflows) = self.workflow.workflows.values().next() {
            if let Some(hooks) = &workflows.hooks {
                if !hooks.pre_workflow.is_empty() {
                    HooksExecutor::execute_pre_workflow(&hooks.pre_workflow, &self.workflow.name)
                        .await?;
                }
            }
        }

        // Execute the workflow and handle errors
        let execution_result = self.execute_tasks().await;

        // Run post-workflow hooks if they exist (even on error)
        if let Some(workflows) = self.workflow.workflows.values().next() {
            if let Some(hooks) = &workflows.hooks {
                if !hooks.post_workflow.is_empty() {
                    let _ = HooksExecutor::execute_post_workflow(
                        &hooks.post_workflow,
                        &self.workflow.name,
                    )
                    .await;
                }
            }
        }

        // If execution failed, run error hooks
        if let Err(ref e) = execution_result {
            if let Some(workflows) = self.workflow.workflows.values().next() {
                if let Some(hooks) = &workflows.hooks {
                    if !hooks.on_error.is_empty() {
                        let _ = HooksExecutor::execute_error(
                            &hooks.on_error,
                            &self.workflow.name,
                            &e.to_string(),
                        )
                        .await;
                    }
                }
            }

            // Mark workflow as failed in state
            if let Some(ref mut state) = self.state {
                state.mark_failed();
                let _ = self.checkpoint_state();
            }
        } else {
            // Mark workflow as completed in state
            if let Some(ref mut state) = self.state {
                state.mark_completed();
                let _ = self.checkpoint_state();
            }
        }

        execution_result
    }

    /// Execute all tasks in the workflow
    async fn execute_tasks(&mut self) -> Result<()> {
        // Record workflow start time
        self.workflow_start_time = Some(Instant::now());

        // Get execution order
        let order = self.task_graph.topological_sort()?;

        println!("Executing workflow: {}", self.workflow.name);
        println!("Task execution order: {:?}", order);

        // Send workflow start notification if configured
        if let Some(notif_config) = &self.workflow.notifications {
            if notif_config.notify_on_start && !notif_config.default_channels.is_empty() {
                let context = self.create_notification_context("workflow", "started", None, None);
                let spec = crate::dsl::schema::NotificationSpec::Structured {
                    message: format!("Workflow '{}' started", self.workflow.name),
                    title: Some(format!("Workflow Started: {}", self.workflow.name)),
                    priority: Some(crate::dsl::schema::NotificationPriority::Normal),
                    channels: notif_config.default_channels.clone(),
                    metadata: HashMap::new(),
                };
                if let Err(e) = self.notification_manager.send(&spec, &context).await {
                    eprintln!("Warning: Failed to send workflow start notification: {}", e);
                }
            }
        }

        // Wrap agents, task graph, and resolved inputs in Arc for parallel access
        let agents = Arc::new(Mutex::new(std::mem::take(&mut self.agents)));
        let task_graph = Arc::new(Mutex::new(std::mem::take(&mut self.task_graph)));
        let state = Arc::new(Mutex::new(self.state.take()));
        let workflow_inputs = Arc::new(self.resolved_inputs.clone());
        let state_persistence = Arc::new(self.state_persistence.clone());
        let workflow_name = Arc::new(self.workflow.name.clone());

        // Track which tasks we've already processed
        let mut processed = std::collections::HashSet::new();

        for task_id in order {
            // Skip if already processed (as part of parallel group)
            if processed.contains(&task_id) {
                continue;
            }

            // Skip if task was already completed (resume functionality)
            if let Some(ref workflow_state) = *state.lock().await {
                if workflow_state.get_task_status(&task_id) == Some(TaskStatus::Completed) {
                    println!("Skipping already completed task: {}", task_id);
                    processed.insert(task_id.clone());
                    continue;
                }
            }

            // Get parallel tasks
            let parallel_tasks = {
                let graph = task_graph.lock().await;
                graph.get_parallel_tasks(&task_id)
            };

            if parallel_tasks.is_empty() {
                // Execute task sequentially
                self.execute_task_parallel(
                    &task_id,
                    agents.clone(),
                    task_graph.clone(),
                    state.clone(),
                    workflow_inputs.clone(),
                    state_persistence.clone(),
                )
                .await?;
                processed.insert(task_id.clone());
            } else {
                // Execute tasks in parallel using tokio::spawn
                println!(
                    "Executing tasks in parallel: {} with {:?}",
                    task_id, parallel_tasks
                );

                let mut handles = vec![];

                // Spawn main task
                {
                    let task_id = task_id.clone();
                    let agents = agents.clone();
                    let graph = task_graph.clone();
                    let workflow_state = state.clone();
                    let inputs = workflow_inputs.clone();
                    let persistence = state_persistence.clone();
                    let wf_name = workflow_name.clone();
                    let json_out = self.json_output;

                    let handle = tokio::spawn(async move {
                        execute_task_static(
                            task_id,
                            agents,
                            graph,
                            workflow_state,
                            inputs,
                            persistence,
                            wf_name,
                            json_out,
                        )
                        .await
                    });
                    handles.push(handle);
                }

                // Spawn parallel tasks
                for parallel_id in &parallel_tasks {
                    let status = {
                        let graph = task_graph.lock().await;
                        graph.get_task_status(parallel_id)
                    };

                    if status == Some(TaskStatus::Pending) {
                        let parallel_id = parallel_id.clone();
                        let agents = agents.clone();
                        let graph = task_graph.clone();
                        let workflow_state = state.clone();
                        let inputs = workflow_inputs.clone();
                        let persistence = state_persistence.clone();
                        let wf_name = workflow_name.clone();
                        let json_out = self.json_output;

                        let handle = tokio::spawn(async move {
                            execute_task_static(
                                parallel_id,
                                agents,
                                graph,
                                workflow_state,
                                inputs,
                                persistence,
                                wf_name,
                                json_out,
                            )
                            .await
                        });
                        handles.push(handle);
                    }
                }

                // Wait for all parallel tasks to complete
                for handle in handles {
                    match handle.await {
                        Ok(Ok(())) => {}
                        Ok(Err(e)) => return Err(e),
                        Err(e) => return Err(Error::InvalidInput(format!("Task panicked: {}", e))),
                    }
                }

                processed.insert(task_id.clone());
                for parallel_id in parallel_tasks {
                    processed.insert(parallel_id);
                }
            }
        }

        // Restore agents, task graph, and state
        self.agents = Arc::try_unwrap(agents)
            .map_err(|_| Error::InvalidInput("Failed to unwrap agents".to_string()))?
            .into_inner();
        self.task_graph = Arc::try_unwrap(task_graph)
            .map_err(|_| Error::InvalidInput("Failed to unwrap task graph".to_string()))?
            .into_inner();
        self.state = Arc::try_unwrap(state)
            .map_err(|_| Error::InvalidInput("Failed to unwrap state".to_string()))?
            .into_inner();

        // Checkpoint state after execution
        if self.state.is_some() {
            let _ = self.checkpoint_state();
        }

        println!("Workflow execution completed");

        // Send workflow completion notification if configured
        if let Some(notif_config) = &self.workflow.notifications {
            if notif_config.notify_on_workflow_completion
                && !notif_config.default_channels.is_empty()
            {
                let duration = self.workflow_start_time.map(|start| start.elapsed());
                let context =
                    self.create_notification_context("workflow", "completed", duration, None);
                let spec = crate::dsl::schema::NotificationSpec::Structured {
                    message: format!("Workflow '{}' completed successfully", self.workflow.name),
                    title: Some(format!("Workflow Completed: {}", self.workflow.name)),
                    priority: Some(crate::dsl::schema::NotificationPriority::Normal),
                    channels: notif_config.default_channels.clone(),
                    metadata: HashMap::new(),
                };
                if let Err(e) = self.notification_manager.send(&spec, &context).await {
                    eprintln!(
                        "Warning: Failed to send workflow completion notification: {}",
                        e
                    );
                }
            }
        }

        Ok(())
    }

    /// Execute a single task with shared state (for parallel execution)
    async fn execute_task_parallel(
        &self,
        task_id: &str,
        agents: Arc<Mutex<HashMap<String, PeriplonSDKClient>>>,
        task_graph: Arc<Mutex<TaskGraph>>,
        state: Arc<Mutex<Option<WorkflowState>>>,
        workflow_inputs: Arc<HashMap<String, serde_json::Value>>,
        state_persistence: Arc<Option<StatePersistence>>,
    ) -> Result<()> {
        let workflow_name = Arc::new(self.workflow.name.clone());
        execute_task_static(
            task_id.to_string(),
            agents,
            task_graph,
            state,
            workflow_inputs,
            state_persistence,
            workflow_name,
            self.json_output,
        )
        .await
    }

    /// Convert DSL AgentSpec to SDK AgentOptions
    ///
    /// # Arguments
    ///
    /// * `spec` - Agent specification
    /// * `workflow_cwd` - Workflow-level working directory (optional)
    /// * `workflow_create_cwd` - Workflow-level create_cwd flag (optional)
    ///
    /// # Working Directory Priority
    ///
    /// 1. Agent-level cwd (highest priority)
    /// 2. Workflow-level cwd
    /// 3. None (current directory - backwards compatible)
    ///
    /// # Create CWD Priority
    ///
    /// 1. Agent-level create_cwd (highest priority)
    /// 2. Workflow-level create_cwd
    /// 3. false (backwards compatible - don't create)
    fn agent_spec_to_options(
        &self,
        spec: &AgentSpec,
        workflow_cwd: Option<&str>,
        workflow_create_cwd: Option<bool>,
        var_context: &crate::dsl::variables::VariableContext,
    ) -> Result<AgentOptions> {
        let add_dirs = spec
            .permissions
            .allowed_directories
            .iter()
            .map(std::path::PathBuf::from)
            .collect();

        // Interpolate workflow cwd if present
        let interpolated_workflow_cwd = workflow_cwd.map(|cwd| {
            var_context
                .interpolate(cwd)
                .unwrap_or_else(|_| cwd.to_string())
        });

        // Interpolate agent cwd if present
        let interpolated_agent_cwd = spec
            .cwd
            .as_ref()
            .map(|cwd| var_context.interpolate(cwd).unwrap_or_else(|_| cwd.clone()));

        // Determine working directory with cascading defaults
        let cwd = interpolated_agent_cwd
            .as_deref()
            .or(interpolated_workflow_cwd.as_deref())
            .map(std::path::PathBuf::from);

        // Determine create_cwd with cascading defaults
        let create_cwd = spec.create_cwd.or(workflow_create_cwd).unwrap_or(false);

        let options = AgentOptions {
            allowed_tools: spec.tools.clone(),
            model: spec.model.clone(),
            max_turns: spec.max_turns,
            permission_mode: Some(spec.permissions.mode.clone()),
            add_dirs,
            cwd,
            create_cwd,
            ..Default::default()
        };
        Ok(options)
    }

    /// Shutdown the executor and disconnect all agents
    pub async fn shutdown(&mut self) -> Result<()> {
        println!("Shutting down executor...");

        for (name, agent) in &mut self.agents {
            println!("Disconnecting agent: {}", name);
            agent.disconnect().await?;
        }

        println!("Executor shutdown complete");
        Ok(())
    }

    /// Get workflow information
    pub fn get_workflow_info(&self) -> (&str, &str) {
        (&self.workflow.name, &self.workflow.version)
    }

    /// Get task count
    pub fn get_task_count(&self) -> usize {
        self.task_graph.task_count()
    }

    /// Check if execution is complete
    pub fn is_complete(&self) -> bool {
        self.task_graph.is_complete()
    }
}

/// Static function for executing a task (used in parallel execution)
///
/// This function can be called from tokio::spawn and includes retry logic
#[allow(clippy::too_many_arguments)]
async fn execute_task_static(
    task_id: String,
    agents: Arc<Mutex<HashMap<String, PeriplonSDKClient>>>,
    task_graph: Arc<Mutex<TaskGraph>>,
    state: Arc<Mutex<Option<WorkflowState>>>,
    workflow_inputs: Arc<HashMap<String, serde_json::Value>>,
    state_persistence: Arc<Option<StatePersistence>>,
    workflow_name: Arc<String>,
    json_output: bool,
) -> Result<()> {
    // Get task spec and error recovery strategy
    let (spec, recovery_strategy) = {
        let graph = task_graph.lock().await;
        let task_node = graph
            .get_task(&task_id)
            .ok_or_else(|| Error::InvalidInput(format!("Task '{}' not found", task_id)))?;

        // Get error recovery strategy from task spec
        let strategy = ErrorRecovery::get_strategy_from_spec(task_node.spec.on_error.as_ref());

        (task_node.spec.clone(), strategy)
    };

    println!("Executing task: {} - {}", task_id, spec.description);

    // Check if this is a loop task
    if let Some(ref loop_spec) = spec.loop_spec {
        println!(
            "Task '{}' has loop specification - delegating to loop executor",
            task_id
        );
        let ctx = ExecutionContext {
            workflow_inputs: &workflow_inputs,
            agents: &agents,
            task_graph: &task_graph,
            state: &state,
            workflow_name: &workflow_name,
            json_output,
        };
        return execute_task_with_loop(&task_id, &spec, loop_spec, &ctx).await;
    }

    // Check condition if present
    if let Some(ref condition) = spec.condition {
        let condition_met = {
            let graph = task_graph.lock().await;
            let workflow_state = state.lock().await;
            let state_ref = workflow_state.as_ref();
            evaluate_condition(condition, &graph, state_ref)
        };

        if !condition_met {
            println!("Task '{}' condition not met - skipping", task_id);

            // Mark task as skipped
            {
                let mut graph = task_graph.lock().await;
                graph.update_task_status(&task_id, TaskStatus::Skipped)?;
            }
            if let Some(ref mut workflow_state) = *state.lock().await {
                workflow_state.update_task_status(&task_id, TaskStatus::Skipped);
            }

            return Ok(());
        }

        println!(
            "Task '{}' condition met - proceeding with execution",
            task_id
        );
    }

    // Attempt execution with retry logic (for errors)
    let mut error_attempt = 0;
    // Track DoD retries separately
    let mut dod_attempt = 0;
    // Store last DoD feedback for retry attempts
    let mut last_dod_feedback: Option<String> = None;

    loop {
        // Record attempt in state
        if let Some(ref mut workflow_state) = *state.lock().await {
            workflow_state.record_task_attempt(&task_id);
        }
        // Update status to running
        {
            let mut graph = task_graph.lock().await;
            graph.update_task_status(&task_id, TaskStatus::Running)?;
        }
        if let Some(ref mut workflow_state) = *state.lock().await {
            workflow_state.update_task_status(&task_id, TaskStatus::Running);
        }

        // Create variable context for interpolation
        let mut var_context = crate::dsl::variables::VariableContext::new();
        for (key, value) in workflow_inputs.iter() {
            var_context.insert(&crate::dsl::variables::Scope::Workflow, key, value.clone());
        }

        // Interpolate task description
        let interpolated_description = var_context
            .interpolate(&spec.description)
            .unwrap_or_else(|_| spec.description.clone());

        // Build task description with DoD feedback if this is a retry
        let task_description = if let Some(ref feedback) = last_dod_feedback {
            // Include the actual unmet criteria feedback
            format!("{}\n\n{}", interpolated_description, feedback)
        } else {
            interpolated_description
        };

        // Try to execute the task
        match execute_task_attempt(
            &task_id,
            &task_description,
            &spec,
            &workflow_inputs,
            &agents,
            error_attempt,
            &state,
            &workflow_name,
            json_output,
        )
        .await
        {
            Ok(task_output) => {
                // Task executed successfully - now check definition of done
                if let Some(ref dod) = spec.definition_of_done {
                    println!("Checking definition of done for task: {}", task_id);

                    // Use the variable context created earlier
                    let dod_results =
                        check_definition_of_done(dod, task_output.as_deref(), &var_context).await;
                    let all_met = dod_results.iter().all(|r| r.met);

                    if !all_met {
                        let mut unmet_feedback = format_unmet_criteria(&dod_results);

                        // Enhance feedback with permission hints
                        unmet_feedback = enhance_feedback_with_permission_hints(
                            unmet_feedback,
                            task_output.as_deref().unwrap_or(""),
                            &dod_results,
                            dod.auto_elevate_permissions,
                        );

                        println!("Definition of done not met for task '{}':", task_id);
                        println!("{}", unmet_feedback);

                        dod_attempt += 1;

                        if dod_attempt <= dod.max_retries {
                            println!(
                                "Retrying task '{}' (DoD attempt {}/{})",
                                task_id, dod_attempt, dod.max_retries
                            );

                            // Apply auto-elevation if configured and permission issue detected
                            if dod.auto_elevate_permissions
                                && detect_permission_issue(
                                    task_output.as_deref().unwrap_or(""),
                                    &dod_results,
                                )
                            {
                                println!(
                                    "  🔓 Auto-elevating permissions to 'bypassPermissions' for retry..."
                                );

                                // Actually update the agent's permission mode
                                if let Some(ref agent_id) = spec.agent {
                                    let mut agents_guard = agents.lock().await;
                                    if let Some(agent) = agents_guard.get_mut(agent_id) {
                                        if let Err(e) =
                                            agent.set_permission_mode("bypassPermissions").await
                                        {
                                            eprintln!(
                                                "Warning: Failed to elevate permissions: {}",
                                                e
                                            );
                                        } else {
                                            println!("  ✓ Permissions elevated successfully");
                                        }
                                    }
                                }
                            }

                            // Store feedback for next iteration
                            last_dod_feedback = Some(unmet_feedback);

                            // Continue loop to retry with feedback
                            continue;
                        } else {
                            println!(
                                "Task '{}' exhausted all DoD retries ({}/{})",
                                task_id, dod_attempt, dod.max_retries
                            );

                            if dod.fail_on_unmet {
                                // Mark as failed
                                {
                                    let mut graph = task_graph.lock().await;
                                    graph.update_task_status(&task_id, TaskStatus::Failed)?;
                                }
                                if let Some(ref mut workflow_state) = *state.lock().await {
                                    workflow_state.update_task_status(&task_id, TaskStatus::Failed);
                                    workflow_state.record_task_error(
                                        &task_id,
                                        &format!(
                                            "Definition of done not met after {} retries",
                                            dod.max_retries
                                        ),
                                    );
                                }
                                return Err(Error::InvalidInput(format!(
                                    "Task '{}' failed: definition of done not met after {} retries",
                                    task_id, dod.max_retries
                                )));
                            }
                            // Otherwise fall through to mark as completed despite unmet DoD
                        }
                    } else {
                        println!("✓ Definition of done met for task: {}", task_id);
                    }
                }

                // Success - update status and record result
                {
                    let mut graph = task_graph.lock().await;
                    graph.update_task_status(&task_id, TaskStatus::Completed)?;
                }
                if let Some(ref mut workflow_state) = *state.lock().await {
                    workflow_state.update_task_status(&task_id, TaskStatus::Completed);

                    // Record task result for workflow context
                    if let Some(ref output) = task_output {
                        workflow_state.record_task_result(&task_id, output);
                    }
                }

                // Checkpoint state after task completion
                if let (Some(ref workflow_state), Some(ref persistence)) =
                    (&*state.lock().await, &*state_persistence)
                {
                    if let Err(e) = persistence.save_state(workflow_state) {
                        eprintln!(
                            "Warning: Failed to checkpoint state after task '{}': {}",
                            task_id, e
                        );
                    }
                }

                println!("Task completed: {}", task_id);

                // Handle on_complete actions
                if let Some(on_complete) = &spec.on_complete {
                    if let Some(notify_spec) = &on_complete.notify {
                        // Extract message from NotificationSpec (Simple or Structured)
                        let message = match notify_spec {
                            crate::dsl::NotificationSpec::Simple(msg) => msg.clone(),
                            crate::dsl::NotificationSpec::Structured { message, .. } => {
                                message.clone()
                            }
                        };
                        println!("Notification: {}", message);
                    }
                }

                return Ok(());
            }
            Err(e) => {
                println!(
                    "Task '{}' failed (attempt {}): {}",
                    task_id,
                    error_attempt + 1,
                    e
                );

                // Record error in state
                if let Some(ref mut workflow_state) = *state.lock().await {
                    workflow_state.record_task_error(&task_id, &e.to_string());
                }

                error_attempt += 1;

                // Check if we should retry
                if !ErrorRecovery::should_retry(&recovery_strategy, error_attempt) {
                    // No more retries - mark as failed
                    {
                        let mut graph = task_graph.lock().await;
                        graph.update_task_status(&task_id, TaskStatus::Failed)?;
                    }
                    if let Some(ref mut workflow_state) = *state.lock().await {
                        workflow_state.update_task_status(&task_id, TaskStatus::Failed);
                    }

                    // Try fallback agent if available
                    if let Some(fallback_agent) =
                        ErrorRecovery::get_fallback_agent(&recovery_strategy)
                    {
                        println!("Attempting fallback with agent: {}", fallback_agent);

                        // Reset to Running status for fallback attempt
                        {
                            let mut graph = task_graph.lock().await;
                            graph.update_task_status(&task_id, TaskStatus::Running)?;
                        }
                        if let Some(ref mut workflow_state) = *state.lock().await {
                            workflow_state.update_task_status(&task_id, TaskStatus::Running);
                        }

                        // Execute with fallback agent
                        match execute_task_with_agent(
                            &task_id,
                            &spec,
                            &agents,
                            fallback_agent,
                            error_attempt,
                            json_output,
                        )
                        .await
                        {
                            Ok(()) => {
                                println!("Task completed with fallback agent: {}", task_id);

                                // Mark as completed
                                {
                                    let mut graph = task_graph.lock().await;
                                    graph.update_task_status(&task_id, TaskStatus::Completed)?;
                                }
                                if let Some(ref mut workflow_state) = *state.lock().await {
                                    workflow_state
                                        .update_task_status(&task_id, TaskStatus::Completed);
                                }

                                return Ok(());
                            }
                            Err(fallback_err) => {
                                println!("Fallback agent also failed: {}", fallback_err);

                                // Mark as failed again
                                {
                                    let mut graph = task_graph.lock().await;
                                    graph.update_task_status(&task_id, TaskStatus::Failed)?;
                                }
                                if let Some(ref mut workflow_state) = *state.lock().await {
                                    workflow_state.update_task_status(&task_id, TaskStatus::Failed);
                                    workflow_state.record_task_error(
                                        &task_id,
                                        &format!(
                                            "Primary and fallback failed: {} / {}",
                                            e, fallback_err
                                        ),
                                    );
                                }

                                return Err(fallback_err);
                            }
                        }
                    }

                    return Err(e);
                }

                // Calculate retry delay with optional exponential backoff
                let retry_delay = calculate_retry_delay(&recovery_strategy, error_attempt);
                println!(
                    "Retrying task '{}' (attempt {}) in {}s...",
                    task_id,
                    error_attempt + 1,
                    retry_delay
                );
                tokio::time::sleep(tokio::time::Duration::from_secs(retry_delay)).await;
            }
        }
    }
}

/// Execute a script task
async fn execute_script_task(
    _task_id: &str,
    script_spec: &crate::dsl::schema::ScriptSpec,
    workflow_inputs: &HashMap<String, serde_json::Value>,
    task_inputs: &HashMap<String, serde_json::Value>,
    attempt: u32,
) -> Result<Option<String>> {
    use crate::dsl::schema::ScriptLanguage;
    use tokio::process::Command;

    // Determine the interpreter based on language
    let (interpreter, args): (&str, Vec<&str>) = match script_spec.language {
        ScriptLanguage::Python => ("python3", vec!["-c"]),
        ScriptLanguage::JavaScript => ("node", vec!["-e"]),
        ScriptLanguage::Bash => ("bash", vec!["-c"]),
        ScriptLanguage::Ruby => ("ruby", vec!["-e"]),
        ScriptLanguage::Perl => ("perl", vec!["-e"]),
    };

    // Get script content - either inline or from file
    let raw_script_content = if let Some(content) = &script_spec.content {
        content.clone()
    } else if let Some(file_path) = &script_spec.file {
        // Interpolate variables in file path
        let interpolated_file_path =
            DSLExecutor::substitute_variables(file_path, workflow_inputs, task_inputs);
        tokio::fs::read_to_string(&interpolated_file_path)
            .await
            .map_err(|e| {
                Error::InvalidInput(format!(
                    "Failed to read script file '{}': {}",
                    interpolated_file_path, e
                ))
            })?
    } else {
        return Err(Error::InvalidInput(
            "Script must specify either 'content' or 'file'".to_string(),
        ));
    };

    // Substitute workflow and task variables in script content
    let script_content =
        DSLExecutor::substitute_variables(&raw_script_content, workflow_inputs, task_inputs);

    // Build command
    let mut cmd = Command::new(interpreter);
    cmd.args(&args);
    cmd.arg(&script_content);

    // Set working directory if specified (with variable interpolation)
    if let Some(working_dir) = &script_spec.working_dir {
        let interpolated_working_dir =
            DSLExecutor::substitute_variables(working_dir, workflow_inputs, task_inputs);
        cmd.current_dir(interpolated_working_dir);
    }

    // Set environment variables (with variable interpolation)
    for (key, value) in &script_spec.env {
        let interpolated_value =
            DSLExecutor::substitute_variables(value, workflow_inputs, task_inputs);
        cmd.env(key, interpolated_value);
    }

    // Capture stdout and stderr
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    if attempt > 0 {
        println!(
            "  [Retry {}] Executing {} script...",
            attempt,
            format!("{:?}", script_spec.language).to_lowercase()
        );
    } else {
        println!(
            "  Executing {} script...",
            format!("{:?}", script_spec.language).to_lowercase()
        );
    }

    // Execute with timeout if specified
    let output = if let Some(timeout_secs) = script_spec.timeout_secs {
        tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), cmd.output())
            .await
            .map_err(|_| {
                Error::InvalidInput(format!(
                    "Script execution timed out after {} seconds",
                    timeout_secs
                ))
            })?
            .map_err(|e| Error::InvalidInput(format!("Failed to execute script: {}", e)))?
    } else {
        cmd.output()
            .await
            .map_err(|e| Error::InvalidInput(format!("Failed to execute script: {}", e)))?
    };

    // Convert output to strings
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    // Print output
    if !stdout.is_empty() {
        print!("{}", stdout);
    }
    if !stderr.is_empty() {
        eprint!("{}", stderr);
    }

    // Check exit status
    if !output.status.success() {
        return Err(Error::InvalidInput(format!(
            "Script failed with exit code: {:?}",
            output.status.code()
        )));
    }

    // Return combined output
    let combined_output = format!("{}{}", stdout, stderr);
    Ok(if combined_output.is_empty() {
        None
    } else {
        Some(combined_output)
    })
}

/// Execute a command task
async fn execute_command_task(
    _task_id: &str,
    command_spec: &crate::dsl::schema::CommandSpec,
    workflow_inputs: &HashMap<String, serde_json::Value>,
    task_inputs: &HashMap<String, serde_json::Value>,
    attempt: u32,
) -> Result<Option<String>> {
    use tokio::process::Command;

    // Substitute variables in executable
    let executable =
        DSLExecutor::substitute_variables(&command_spec.executable, workflow_inputs, task_inputs);

    // Substitute variables in args
    let args: Vec<String> = command_spec
        .args
        .iter()
        .map(|arg| DSLExecutor::substitute_variables(arg, workflow_inputs, task_inputs))
        .collect();

    // Build command
    let mut cmd = Command::new(&executable);
    cmd.args(&args);

    // Set working directory if specified
    if let Some(working_dir) = &command_spec.working_dir {
        let working_dir =
            DSLExecutor::substitute_variables(working_dir, workflow_inputs, task_inputs);
        cmd.current_dir(working_dir);
    }

    // Set environment variables
    for (key, value) in &command_spec.env {
        let value = DSLExecutor::substitute_variables(value, workflow_inputs, task_inputs);
        cmd.env(key, value);
    }

    // Capture stdout and stderr based on spec
    if command_spec.capture_stdout {
        cmd.stdout(std::process::Stdio::piped());
    }
    if command_spec.capture_stderr {
        cmd.stderr(std::process::Stdio::piped());
    }

    if attempt > 0 {
        println!(
            "  [Retry {}] Executing command: {} {}",
            attempt,
            executable,
            args.join(" ")
        );
    } else {
        println!("  Executing command: {} {}", executable, args.join(" "));
    }

    // Execute with timeout if specified
    let output = if let Some(timeout_secs) = command_spec.timeout_secs {
        tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), cmd.output())
            .await
            .map_err(|_| {
                Error::InvalidInput(format!(
                    "Command execution timed out after {} seconds",
                    timeout_secs
                ))
            })?
            .map_err(|e| Error::InvalidInput(format!("Failed to execute command: {}", e)))?
    } else {
        cmd.output()
            .await
            .map_err(|e| Error::InvalidInput(format!("Failed to execute command: {}", e)))?
    };

    // Convert output to strings
    let stdout = if command_spec.capture_stdout {
        String::from_utf8_lossy(&output.stdout).to_string()
    } else {
        String::new()
    };
    let stderr = if command_spec.capture_stderr {
        String::from_utf8_lossy(&output.stderr).to_string()
    } else {
        String::new()
    };

    // Print output
    if !stdout.is_empty() {
        print!("{}", stdout);
    }
    if !stderr.is_empty() {
        eprint!("{}", stderr);
    }

    // Check exit status
    if !output.status.success() {
        return Err(Error::InvalidInput(format!(
            "Command '{}' failed with exit code: {:?}",
            executable,
            output.status.code()
        )));
    }

    // Return combined output
    let combined_output = format!("{}{}", stdout, stderr);
    Ok(if combined_output.is_empty() {
        None
    } else {
        Some(combined_output)
    })
}

/// Attempt to execute a task once
#[allow(clippy::too_many_arguments)]
async fn execute_task_attempt(
    _task_id: &str,
    task_description: &str,
    _spec: &crate::dsl::schema::TaskSpec,
    workflow_inputs: &HashMap<String, serde_json::Value>,
    agents: &Arc<Mutex<HashMap<String, PeriplonSDKClient>>>,
    attempt: u32,
    workflow_state: &Arc<Mutex<Option<crate::dsl::state::WorkflowState>>>,
    workflow_name: &str,
    json_output: bool,
) -> Result<Option<String>> {
    // Check what type of task this is and execute accordingly
    if let Some(script_spec) = &_spec.script {
        // Execute script task with variable substitution
        return execute_script_task(
            _task_id,
            script_spec,
            workflow_inputs,
            &_spec.inputs,
            attempt,
        )
        .await;
    }

    // Check if this is a command task
    if let Some(command_spec) = &_spec.command {
        // Execute command task
        return execute_command_task(
            _task_id,
            command_spec,
            workflow_inputs,
            &_spec.inputs,
            attempt,
        )
        .await;
    }

    // Default to agent-based execution
    let agent_name = _spec.agent.as_ref().ok_or_else(|| {
        Error::InvalidInput(format!("No agent specified for task '{}'", _task_id))
    })?;

    // Build workflow context for agent-based tasks (only if inject_context is true)
    let workflow_context = if _spec.inject_context {
        if let Some(ref state) = *workflow_state.lock().await {
            // Include context if there are completed tasks, or if output file is specified
            let has_workflow_context =
                !state.get_completed_tasks().is_empty() || !state.get_failed_tasks().is_empty();
            let has_output_file = _spec.output.is_some();

            if has_workflow_context || has_output_file {
                state.build_context_summary(workflow_name, None, _spec.output.as_deref())
            } else {
                String::new()
            }
        } else {
            String::new()
        }
    } else {
        String::new()
    };

    // Prepend context to task description for agent (only if inject_context is true)
    let enhanced_description = if _spec.inject_context && !workflow_context.is_empty() {
        format!("{}\n{}", workflow_context, task_description)
    } else {
        task_description.to_string()
    };

    // Execute task query
    let mut agents_guard = agents.lock().await;
    let agent = agents_guard
        .get_mut(agent_name)
        .ok_or_else(|| Error::InvalidInput(format!("Agent '{}' not found", agent_name)))?;

    agent.query(&enhanced_description).await?;

    // Process response and capture output
    let stream = agent.receive_response()?;
    futures::pin_mut!(stream);
    let mut output = String::new();

    while let Some(msg) = stream.next().await {
        // Capture output for DoD checking
        output.push_str(&format!("{:?}\n", msg));

        // Log messages using formatter
        if attempt > 0 {
            let prefix_str = format!("Retry {}", attempt);
            let formatted =
                crate::dsl::message_formatter::format_message(&msg, json_output, Some(&prefix_str));
            println!("{}", formatted);
        } else {
            let formatted = crate::dsl::message_formatter::format_message(&msg, json_output, None);
            println!("{}", formatted);
        }
    }

    Ok(if output.is_empty() {
        None
    } else {
        Some(output)
    })
}

/// Execute a task with a specific agent (for fallback support)
async fn execute_task_with_agent(
    _task_id: &str,
    spec: &crate::dsl::schema::TaskSpec,
    agents: &Arc<Mutex<HashMap<String, PeriplonSDKClient>>>,
    agent_name: &str,
    attempt: u32,
    json_output: bool,
) -> Result<()> {
    // Execute task query with specified agent
    let mut agents_guard = agents.lock().await;
    let agent = agents_guard
        .get_mut(agent_name)
        .ok_or_else(|| Error::InvalidInput(format!("Agent '{}' not found", agent_name)))?;

    agent.query(&spec.description).await?;

    // Process response
    let stream = agent.receive_response()?;
    futures::pin_mut!(stream);
    while let Some(msg) = stream.next().await {
        // Log messages using formatter
        if attempt > 0 {
            let prefix_str = "Fallback".to_string();
            let formatted =
                crate::dsl::message_formatter::format_message(&msg, json_output, Some(&prefix_str));
            println!("{}", formatted);
        } else {
            let formatted = crate::dsl::message_formatter::format_message(&msg, json_output, None);
            println!("{}", formatted);
        }
    }

    Ok(())
}

/// Calculate retry delay with optional exponential backoff
///
/// # Arguments
///
/// * `recovery_strategy` - Error recovery strategy
/// * `attempt` - Current error attempt number (1-based, 1 = first retry)
///
/// # Returns
///
/// Delay in seconds
fn calculate_retry_delay(
    recovery_strategy: &crate::dsl::hooks::RecoveryStrategy,
    attempt: u32,
) -> u64 {
    use crate::dsl::hooks::RecoveryStrategy;

    match recovery_strategy {
        RecoveryStrategy::Retry { config, .. } => {
            let base_delay = config.as_ref().map(|c| c.retry_delay_secs).unwrap_or(1);

            let use_backoff = config
                .as_ref()
                .map(|c| c.exponential_backoff)
                .unwrap_or(false);

            if use_backoff {
                // Exponential backoff: base_delay * 2^(attempt-1)
                // For attempt 1 (first retry): base_delay * 2^0 = base_delay
                // For attempt 2 (second retry): base_delay * 2^1 = base_delay * 2
                // For attempt 3 (third retry): base_delay * 2^2 = base_delay * 4
                // Cap at 60 seconds to avoid extremely long delays
                let exponent = attempt.saturating_sub(1);
                let delay = base_delay * 2u64.pow(exponent);
                delay.min(60)
            } else {
                base_delay
            }
        }
        _ => 1, // Default 1 second for other strategies
    }
}

/// Evaluate a condition against the current workflow state
///
/// # Arguments
///
/// * `condition` - The condition to evaluate
/// * `task_graph` - Current task graph state
/// * `workflow_state` - Current workflow state (optional)
///
/// # Returns
///
/// true if the condition is met, false otherwise
fn evaluate_condition(
    condition: &crate::dsl::schema::ConditionSpec,
    task_graph: &TaskGraph,
    workflow_state: Option<&WorkflowState>,
) -> bool {
    use crate::dsl::schema::ConditionSpec;

    match condition {
        ConditionSpec::Single(cond) => evaluate_single_condition(cond, task_graph, workflow_state),
        ConditionSpec::And { and } => and
            .iter()
            .all(|c| evaluate_condition(c, task_graph, workflow_state)),
        ConditionSpec::Or { or } => or
            .iter()
            .any(|c| evaluate_condition(c, task_graph, workflow_state)),
        ConditionSpec::Not { not } => !evaluate_condition(not, task_graph, workflow_state),
    }
}

/// Evaluate a single condition
fn evaluate_single_condition(
    condition: &crate::dsl::schema::Condition,
    task_graph: &TaskGraph,
    workflow_state: Option<&WorkflowState>,
) -> bool {
    use crate::dsl::schema::{Condition, TaskStatusCondition};

    match condition {
        Condition::TaskStatus { task, status } => {
            // Get task status from task graph
            let task_status = task_graph.get_task_status(task);
            matches!(
                (task_status, status),
                (Some(TaskStatus::Completed), TaskStatusCondition::Completed)
                    | (Some(TaskStatus::Failed), TaskStatusCondition::Failed)
                    | (Some(TaskStatus::Running), TaskStatusCondition::Running)
                    | (Some(TaskStatus::Pending), TaskStatusCondition::Pending)
                    | (Some(TaskStatus::Skipped), TaskStatusCondition::Skipped)
            )
        }
        Condition::StateEquals { key, value } => {
            // Check workflow state
            if let Some(state) = workflow_state {
                state.get_metadata(key) == Some(value)
            } else {
                false
            }
        }
        Condition::StateExists { key } => {
            // Check if state key exists
            if let Some(state) = workflow_state {
                state.get_metadata(key).is_some()
            } else {
                false
            }
        }
        Condition::Always => true,
        Condition::Never => false,
    }
}

/// Check definition of done criteria
///
/// # Arguments
///
/// * `dod` - Definition of done specification
/// * `_task_output` - Output from task execution (for output matching)
///
/// # Returns
///
/// Vector of criterion results
async fn check_definition_of_done(
    dod: &crate::dsl::schema::DefinitionOfDone,
    _task_output: Option<&str>,
    var_context: &crate::dsl::variables::VariableContext,
) -> Vec<crate::dsl::schema::CriterionResult> {
    let mut results = Vec::new();

    for criterion in &dod.criteria {
        let result = check_criterion(criterion, _task_output, var_context).await;
        results.push(result);
    }

    results
}

/// Check a single criterion
async fn check_criterion(
    criterion: &crate::dsl::schema::DoneCriterion,
    _task_output: Option<&str>,
    var_context: &crate::dsl::variables::VariableContext,
) -> crate::dsl::schema::CriterionResult {
    use crate::dsl::schema::{CriterionResult, DoneCriterion, OutputSource};

    match criterion {
        DoneCriterion::FileExists { path, description } => {
            // Interpolate variables in path
            let interpolated_path = var_context
                .interpolate(path)
                .unwrap_or_else(|_| path.clone());
            let exists = std::path::Path::new(&interpolated_path).exists();
            CriterionResult {
                met: exists,
                description: description.clone(),
                details: if exists {
                    format!("File '{}' exists", interpolated_path)
                } else {
                    format!("File '{}' does not exist", interpolated_path)
                },
            }
        }
        DoneCriterion::FileContains {
            path,
            pattern,
            description,
        } => {
            // Interpolate variables in path and pattern
            let interpolated_path = var_context
                .interpolate(path)
                .unwrap_or_else(|_| path.clone());
            let interpolated_pattern = var_context
                .interpolate(pattern)
                .unwrap_or_else(|_| pattern.clone());
            match std::fs::read_to_string(&interpolated_path) {
                Ok(content) => {
                    // Try regex first, fall back to substring matching if regex is invalid
                    let contains = match regex::Regex::new(&interpolated_pattern) {
                        Ok(re) => re.is_match(&content),
                        Err(_) => content.contains(&interpolated_pattern), // Fallback to substring
                    };
                    CriterionResult {
                        met: contains,
                        description: description.clone(),
                        details: if contains {
                            format!(
                                "File '{}' contains pattern '{}'",
                                interpolated_path, interpolated_pattern
                            )
                        } else {
                            format!(
                                "File '{}' does not contain pattern '{}'",
                                interpolated_path, interpolated_pattern
                            )
                        },
                    }
                }
                Err(e) => CriterionResult {
                    met: false,
                    description: description.clone(),
                    details: format!("Failed to read file '{}': {}", interpolated_path, e),
                },
            }
        }
        DoneCriterion::FileNotContains {
            path,
            pattern,
            description,
        } => {
            // Interpolate variables in path and pattern
            let interpolated_path = var_context
                .interpolate(path)
                .unwrap_or_else(|_| path.clone());
            let interpolated_pattern = var_context
                .interpolate(pattern)
                .unwrap_or_else(|_| pattern.clone());
            match std::fs::read_to_string(&interpolated_path) {
                Ok(content) => {
                    // Try regex first, fall back to substring matching if regex is invalid
                    let contains = match regex::Regex::new(&interpolated_pattern) {
                        Ok(re) => re.is_match(&content),
                        Err(_) => content.contains(&interpolated_pattern), // Fallback to substring
                    };
                    let not_contains = !contains;
                    CriterionResult {
                        met: not_contains,
                        description: description.clone(),
                        details: if not_contains {
                            format!(
                                "File '{}' does not contain pattern '{}'",
                                interpolated_path, interpolated_pattern
                            )
                        } else {
                            format!(
                                "File '{}' contains pattern '{}' (should not)",
                                interpolated_path, interpolated_pattern
                            )
                        },
                    }
                }
                Err(e) => CriterionResult {
                    met: false,
                    description: description.clone(),
                    details: format!("Failed to read file '{}': {}", interpolated_path, e),
                },
            }
        }
        DoneCriterion::CommandSucceeds {
            command,
            args,
            description,
            working_dir,
        } => {
            // Interpolate variables in command, args, and working_dir
            let interpolated_command = var_context
                .interpolate(command)
                .unwrap_or_else(|_| command.clone());
            let interpolated_args: Vec<String> = args
                .iter()
                .map(|arg| var_context.interpolate(arg).unwrap_or_else(|_| arg.clone()))
                .collect();
            let interpolated_working_dir = working_dir
                .as_ref()
                .map(|dir| var_context.interpolate(dir).unwrap_or_else(|_| dir.clone()));

            let mut cmd = tokio::process::Command::new(&interpolated_command);
            cmd.args(&interpolated_args);

            if let Some(ref dir) = interpolated_working_dir {
                cmd.current_dir(dir);
            }

            match cmd.output().await {
                Ok(output) => {
                    let success = output.status.success();

                    let details = if success {
                        format!("Command '{}' succeeded", interpolated_command)
                    } else {
                        // Capture stdout and stderr for failed commands so agent can fix errors
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        let stderr = String::from_utf8_lossy(&output.stderr);

                        let mut error_msg = format!(
                            "Command '{}' failed with exit code: {}\n\n",
                            interpolated_command,
                            output.status.code().unwrap_or(-1)
                        );

                        if !stderr.is_empty() {
                            error_msg.push_str("STDERR:\n");
                            error_msg.push_str("```\n");
                            error_msg.push_str(&stderr);
                            error_msg.push_str("```\n\n");
                        }

                        if !stdout.is_empty() {
                            error_msg.push_str("STDOUT:\n");
                            error_msg.push_str("```\n");
                            error_msg.push_str(&stdout);
                            error_msg.push_str("```\n");
                        }

                        error_msg
                    };

                    CriterionResult {
                        met: success,
                        description: description.clone(),
                        details,
                    }
                }
                Err(e) => CriterionResult {
                    met: false,
                    description: description.clone(),
                    details: format!(
                        "Failed to execute command '{}': {}",
                        interpolated_command, e
                    ),
                },
            }
        }
        DoneCriterion::OutputMatches {
            source,
            pattern,
            description,
        } => {
            // Interpolate variables in pattern
            let interpolated_pattern = var_context
                .interpolate(pattern)
                .unwrap_or_else(|_| pattern.clone());

            let content = match source {
                OutputSource::File { path } => {
                    // Interpolate variables in file path
                    let interpolated_path = var_context
                        .interpolate(path)
                        .unwrap_or_else(|_| path.clone());
                    std::fs::read_to_string(&interpolated_path).ok()
                }
                OutputSource::TaskOutput => _task_output.map(|s| s.to_string()),
            };

            match content {
                Some(text) => {
                    let matches = text.contains(&interpolated_pattern);
                    CriterionResult {
                        met: matches,
                        description: description.clone(),
                        details: if matches {
                            format!("Output matches pattern '{}'", interpolated_pattern)
                        } else {
                            format!("Output does not match pattern '{}'", interpolated_pattern)
                        },
                    }
                }
                None => CriterionResult {
                    met: false,
                    description: description.clone(),
                    details: "Failed to read output".to_string(),
                },
            }
        }
        DoneCriterion::DirectoryExists { path, description } => {
            // Interpolate variables in path
            let interpolated_path = var_context
                .interpolate(path)
                .unwrap_or_else(|_| path.clone());
            let exists = std::path::Path::new(&interpolated_path).is_dir();
            CriterionResult {
                met: exists,
                description: description.clone(),
                details: if exists {
                    format!("Directory '{}' exists", interpolated_path)
                } else {
                    format!("Directory '{}' does not exist", interpolated_path)
                },
            }
        }
        DoneCriterion::TestsPassed {
            command,
            args,
            description,
        } => {
            // Interpolate variables in command and args
            let interpolated_command = var_context
                .interpolate(command)
                .unwrap_or_else(|_| command.clone());
            let interpolated_args: Vec<String> = args
                .iter()
                .map(|arg| var_context.interpolate(arg).unwrap_or_else(|_| arg.clone()))
                .collect();

            let mut cmd = tokio::process::Command::new(&interpolated_command);
            cmd.args(&interpolated_args);

            match cmd.output().await {
                Ok(output) => {
                    let success = output.status.success();

                    let details = if success {
                        format!("Tests passed ({})", interpolated_command)
                    } else {
                        // Capture full stdout and stderr for failed tests so agent can fix errors
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        let stderr = String::from_utf8_lossy(&output.stderr);

                        let mut error_msg = format!(
                            "Tests failed ({}) with exit code: {}\n\n",
                            interpolated_command,
                            output.status.code().unwrap_or(-1)
                        );

                        if !stderr.is_empty() {
                            error_msg.push_str("STDERR:\n");
                            error_msg.push_str("```\n");
                            error_msg.push_str(&stderr);
                            error_msg.push_str("```\n\n");
                        }

                        if !stdout.is_empty() {
                            error_msg.push_str("STDOUT:\n");
                            error_msg.push_str("```\n");
                            error_msg.push_str(&stdout);
                            error_msg.push_str("```\n");
                        }

                        error_msg
                    };

                    CriterionResult {
                        met: success,
                        description: description.clone(),
                        details,
                    }
                }
                Err(e) => CriterionResult {
                    met: false,
                    description: description.clone(),
                    details: format!("Failed to run tests '{}': {}", interpolated_command, e),
                },
            }
        }
    }
}

/// Format unmet criteria for agent feedback
fn format_unmet_criteria(results: &[crate::dsl::schema::CriterionResult]) -> String {
    let unmet: Vec<_> = results.iter().filter(|r| !r.met).collect();

    if unmet.is_empty() {
        return String::new();
    }

    let mut feedback = String::from("\n\n=== DEFINITION OF DONE - UNMET CRITERIA ===\n\n");
    feedback.push_str("The following criteria were not met:\n\n");

    for (i, result) in unmet.iter().enumerate() {
        feedback.push_str(&format!(
            "{}. {}\n   Status: ✗ FAILED\n   Details: {}\n\n",
            i + 1,
            result.description,
            result.details
        ));
    }

    feedback.push_str("Please address these issues and retry the task.\n");
    feedback
}

/// Detect if DoD failure is likely due to permission issues
fn detect_permission_issue(output: &str, results: &[crate::dsl::schema::CriterionResult]) -> bool {
    // Check output for permission-related keywords
    let permission_keywords = [
        "permission",
        "permissions",
        "write access",
        "read access",
        "file write",
        "cannot create",
        "cannot write",
        "access denied",
        "forbidden",
    ];

    let output_lower = output.to_lowercase();
    let has_permission_mention = permission_keywords
        .iter()
        .any(|keyword| output_lower.contains(keyword));

    // Check if failures are file-related (likely permission issues)
    let has_file_failures = results.iter().any(|r| {
        !r.met
            && (r.description.to_lowercase().contains("file")
                || r.details.to_lowercase().contains("does not exist")
                || r.details.to_lowercase().contains("not found"))
    });

    has_permission_mention || has_file_failures
}

/// Enhance feedback with permission hints if permission issues detected
fn enhance_feedback_with_permission_hints(
    mut feedback: String,
    output: &str,
    results: &[crate::dsl::schema::CriterionResult],
    auto_elevate: bool,
) -> String {
    if detect_permission_issue(output, results) {
        feedback.push_str("\n⚠️  PERMISSION HINT:\n");
        feedback.push_str("The failure appears to be related to file access or permissions.\n");

        if auto_elevate {
            feedback.push_str(
                "Auto-elevation is enabled - 'bypassPermissions' mode will be granted on retry.\n",
            );
            feedback
                .push_str("All tool operations will be automatically approved for this retry.\n");
        } else {
            feedback.push_str("Consider:\n");
            feedback.push_str("1. Ensuring required files exist before checking\n");
            feedback.push_str("2. Creating necessary files if they don't exist\n");
            feedback.push_str("3. Requesting write permissions if needed\n\n");
            feedback.push_str(
                "TIP: Add 'auto_elevate_permissions: true' to the definition_of_done config\n",
            );
            feedback.push_str("     to automatically grant enhanced permissions on retry.\n");
        }
    }

    feedback
}

/// Extract a value from JSON using a simple path notation
///
/// Supports:
/// - Dot notation: "data.items"
/// - Array indexing: "data[0]"
/// - Combined: "data.items[0].name"
///
/// # Arguments
///
/// * `value` - The JSON value to extract from
/// * `path` - The path to extract (e.g., "data.items")
///
/// # Returns
///
/// The extracted JSON value
fn extract_json_path(value: &serde_json::Value, path: &str) -> Result<serde_json::Value> {
    let mut current = value.clone();

    // Split path by dots and handle array indices
    for segment in path.split('.') {
        if segment.is_empty() {
            continue;
        }

        // Check for array index notation like "items[0]"
        if let Some(bracket_pos) = segment.find('[') {
            let key = &segment[..bracket_pos];
            let index_str = &segment[bracket_pos + 1..segment.len() - 1];
            let index: usize = index_str.parse().map_err(|_| {
                Error::InvalidInput(format!("Invalid array index in JSON path: {}", segment))
            })?;

            // First navigate to the key
            if !key.is_empty() {
                current = current
                    .get(key)
                    .ok_or_else(|| {
                        Error::InvalidInput(format!("JSON path key '{}' not found", key))
                    })?
                    .clone();
            }

            // Then get the array element
            current = current
                .get(index)
                .ok_or_else(|| {
                    Error::InvalidInput(format!("JSON path index {} out of bounds", index))
                })?
                .clone();
        } else {
            // Simple key access
            current = current
                .get(segment)
                .ok_or_else(|| {
                    Error::InvalidInput(format!("JSON path key '{}' not found", segment))
                })?
                .clone();
        }
    }

    Ok(current)
}

/// Resolve a collection source to a vector of JSON values
///
/// # Arguments
///
/// * `collection` - The collection source specification
/// * `state` - Optional workflow state for state-based collections
///
/// # Returns
///
/// Vector of JSON values representing the collection items
async fn resolve_collection(
    collection: &CollectionSource,
    state: Option<&WorkflowState>,
) -> Result<Vec<serde_json::Value>> {
    match collection {
        CollectionSource::State { key } => {
            // Read from workflow state
            let state = state.ok_or_else(|| {
                Error::InvalidInput(
                    "Workflow state not available for state-based collection".to_string(),
                )
            })?;

            let value = state
                .get_metadata(key)
                .ok_or_else(|| Error::InvalidInput(format!("State key '{}' not found", key)))?;

            // Expect an array
            match value {
                serde_json::Value::Array(arr) => Ok(arr.clone()),
                _ => Err(Error::InvalidInput(format!(
                    "State key '{}' is not an array",
                    key
                ))),
            }
        }
        CollectionSource::File { path, format } => {
            // Read from file
            let content = std::fs::read_to_string(path).map_err(|e| {
                Error::InvalidInput(format!("Failed to read collection file '{}': {}", path, e))
            })?;

            match format {
                FileFormat::Json => {
                    let value: serde_json::Value = serde_json::from_str(&content).map_err(|e| {
                        Error::InvalidInput(format!("Failed to parse JSON file '{}': {}", path, e))
                    })?;

                    match value {
                        serde_json::Value::Array(arr) => Ok(arr),
                        _ => Err(Error::InvalidInput(format!(
                            "JSON file '{}' does not contain an array",
                            path
                        ))),
                    }
                }
                FileFormat::JsonLines => {
                    let items: Result<Vec<serde_json::Value>> = content
                        .lines()
                        .enumerate()
                        .map(|(i, line)| {
                            serde_json::from_str(line).map_err(|e| {
                                Error::InvalidInput(format!(
                                    "Failed to parse JSON line {} in '{}': {}",
                                    i + 1,
                                    path,
                                    e
                                ))
                            })
                        })
                        .collect();
                    items
                }
                FileFormat::Csv => {
                    // Simple CSV parsing - split by comma, each row becomes array
                    let items: Vec<serde_json::Value> = content
                        .lines()
                        .skip(1) // Skip header
                        .map(|line| {
                            let fields: Vec<&str> = line.split(',').collect();
                            serde_json::Value::Array(
                                fields
                                    .iter()
                                    .map(|f| serde_json::Value::String(f.to_string()))
                                    .collect(),
                            )
                        })
                        .collect();
                    Ok(items)
                }
                FileFormat::Lines => {
                    let items: Vec<serde_json::Value> = content
                        .lines()
                        .map(|line| serde_json::Value::String(line.to_string()))
                        .collect();
                    Ok(items)
                }
            }
        }
        CollectionSource::Range { start, end, step } => {
            // Generate numeric range
            let step_size = step.unwrap_or(1);
            let mut items = Vec::new();

            let mut current = *start;
            while current < *end {
                items.push(serde_json::Value::Number(current.into()));
                current += step_size;
            }

            Ok(items)
        }
        CollectionSource::Inline { items } => {
            // Use provided items directly
            Ok(items.clone())
        }
        CollectionSource::Http {
            url,
            method,
            headers,
            body,
            format,
            json_path,
        } => {
            // Make HTTP request
            let client = reqwest::Client::new();
            let mut request = match method.to_uppercase().as_str() {
                "GET" => client.get(url),
                "POST" => client.post(url),
                "PUT" => client.put(url),
                "DELETE" => client.delete(url),
                "PATCH" => client.patch(url),
                _ => {
                    return Err(Error::InvalidInput(format!(
                        "Unsupported HTTP method: {}",
                        method
                    )))
                }
            };

            // Add headers if provided
            if let Some(headers_map) = headers {
                for (key, value) in headers_map {
                    request = request.header(key, value);
                }
            }

            // Add body if provided
            if let Some(body_content) = body {
                request = request.body(body_content.clone());
            }

            // Execute request
            let response = request.send().await.map_err(|e| {
                Error::InvalidInput(format!("HTTP request to '{}' failed: {}", url, e))
            })?;

            // Check status
            if !response.status().is_success() {
                return Err(Error::InvalidInput(format!(
                    "HTTP request to '{}' returned status: {}",
                    url,
                    response.status()
                )));
            }

            // Get response body
            let response_text = response.text().await.map_err(|e| {
                Error::InvalidInput(format!("Failed to read response from '{}': {}", url, e))
            })?;

            // Parse based on format
            let mut value: serde_json::Value = match format {
                FileFormat::Json => serde_json::from_str(&response_text).map_err(|e| {
                    Error::InvalidInput(format!(
                        "Failed to parse JSON response from '{}': {}",
                        url, e
                    ))
                })?,
                FileFormat::JsonLines => {
                    let items: Result<Vec<serde_json::Value>> = response_text
                        .lines()
                        .enumerate()
                        .map(|(i, line)| {
                            serde_json::from_str(line).map_err(|e| {
                                Error::InvalidInput(format!(
                                    "Failed to parse JSON line {} from '{}': {}",
                                    i + 1,
                                    url,
                                    e
                                ))
                            })
                        })
                        .collect();
                    serde_json::Value::Array(items?)
                }
                FileFormat::Lines => {
                    let items: Vec<serde_json::Value> = response_text
                        .lines()
                        .map(|line| serde_json::Value::String(line.to_string()))
                        .collect();
                    serde_json::Value::Array(items)
                }
                FileFormat::Csv => {
                    let items: Vec<serde_json::Value> = response_text
                        .lines()
                        .skip(1) // Skip header
                        .map(|line| {
                            let fields: Vec<&str> = line.split(',').collect();
                            serde_json::Value::Array(
                                fields
                                    .iter()
                                    .map(|f| serde_json::Value::String(f.to_string()))
                                    .collect(),
                            )
                        })
                        .collect();
                    serde_json::Value::Array(items)
                }
            };

            // Apply JSON path if provided
            if let Some(path) = json_path {
                value = extract_json_path(&value, path)?;
            }

            // Ensure result is an array
            match value {
                serde_json::Value::Array(arr) => Ok(arr),
                _ => Err(Error::InvalidInput(format!(
                    "HTTP response from '{}' does not contain an array",
                    url
                ))),
            }
        }
    }
}

/// Execute a task with loop specification (ForEach or Repeat only in Phase 2)
///
/// # Arguments
///
/// * `task_id` - Task identifier
/// * `spec` - Task specification with loop_spec
/// * `loop_spec` - Loop specification
/// * `agents` - Shared agent map
/// * `task_graph` - Shared task graph
/// * `state` - Shared workflow state
async fn execute_task_with_loop(
    task_id: &str,
    spec: &crate::dsl::schema::TaskSpec,
    loop_spec: &LoopSpec,
    ctx: &ExecutionContext<'_>,
) -> Result<()> {
    match loop_spec {
        LoopSpec::ForEach {
            collection,
            iterator,
            parallel,
            ..
        } => {
            // Resolve collection
            let items = {
                let state_guard = ctx.state.lock().await;
                resolve_collection(collection, state_guard.as_ref()).await?
            };

            // Initialize loop state
            {
                let mut state_guard = ctx.state.lock().await;
                if let Some(ref mut workflow_state) = *state_guard {
                    workflow_state.init_loop(task_id, Some(items.len()));
                }
            }

            println!(
                "Executing ForEach loop for task '{}': {} items",
                task_id,
                items.len()
            );

            if *parallel {
                // Parallel execution with semaphore limiting
                let max_parallel = loop_spec.max_parallel().unwrap_or(items.len().min(10)); // Default to 10 or item count
                let workflow_inputs_arc = Arc::new(ctx.workflow_inputs.clone());
                execute_foreach_parallel(
                    task_id,
                    spec,
                    &items,
                    iterator,
                    max_parallel,
                    workflow_inputs_arc,
                    ctx,
                )
                .await?;
            } else {
                // Sequential execution
                execute_foreach_sequential(task_id, spec, &items, iterator, ctx).await?;
            }

            println!("ForEach loop completed for task '{}'", task_id);
            Ok(())
        }
        LoopSpec::Repeat {
            count,
            iterator,
            parallel,
            ..
        } => {
            // Initialize loop state
            {
                let mut state_guard = ctx.state.lock().await;
                if let Some(ref mut workflow_state) = *state_guard {
                    workflow_state.init_loop(task_id, Some(*count));
                }
            }

            println!(
                "Executing Repeat loop for task '{}': {} iterations",
                task_id, count
            );

            if *parallel {
                // Parallel execution with semaphore limiting
                let max_parallel = loop_spec.max_parallel().unwrap_or((*count).min(10)); // Default to 10 or count
                let workflow_inputs_arc = Arc::new(ctx.workflow_inputs.clone());
                execute_repeat_parallel(
                    task_id,
                    spec,
                    *count,
                    iterator.as_deref(),
                    max_parallel,
                    workflow_inputs_arc,
                    ctx,
                )
                .await?;
            } else {
                // Sequential execution
                execute_repeat_sequential(task_id, spec, *count, iterator.as_deref(), ctx).await?;
            }

            println!("Repeat loop completed for task '{}'", task_id);
            Ok(())
        }
        LoopSpec::While {
            condition,
            max_iterations,
            iteration_variable,
            delay_between_secs,
        } => {
            // Initialize loop state (unknown total iterations)
            {
                let mut state_guard = ctx.state.lock().await;
                if let Some(ref mut workflow_state) = *state_guard {
                    workflow_state.init_loop(task_id, None);
                }
            }

            println!(
                "Executing While loop for task '{}': max {} iterations",
                task_id, max_iterations
            );

            // Sequential execution
            execute_while_sequential(
                task_id,
                spec,
                condition,
                *max_iterations,
                iteration_variable.as_deref(),
                *delay_between_secs,
                ctx,
            )
            .await?;

            println!("While loop completed for task '{}'", task_id);
            Ok(())
        }
        LoopSpec::RepeatUntil {
            condition,
            min_iterations,
            max_iterations,
            iteration_variable,
            delay_between_secs,
        } => {
            // Initialize loop state (unknown total iterations)
            {
                let mut state_guard = ctx.state.lock().await;
                if let Some(ref mut workflow_state) = *state_guard {
                    workflow_state.init_loop(task_id, None);
                }
            }

            println!(
                "Executing RepeatUntil loop for task '{}': min {}, max {} iterations",
                task_id,
                min_iterations.unwrap_or(1),
                max_iterations
            );

            // Sequential execution
            execute_repeat_until_sequential(
                task_id,
                spec,
                condition,
                *min_iterations,
                *max_iterations,
                iteration_variable.as_deref(),
                *delay_between_secs,
                ctx,
            )
            .await?;

            println!("RepeatUntil loop completed for task '{}'", task_id);
            Ok(())
        }
    }
}

/// Execute subtasks within a loop iteration
///
/// This function executes all subtasks of a loop task for a single iteration.
/// Subtasks are executed sequentially, respecting their dependencies.
///
/// NOTE: The `substituted_parent` should already have loop variables substituted
/// via `substitute_task_variables`, so the subtasks within it will also have
/// variables properly replaced.
#[allow(clippy::too_many_arguments)]
async fn execute_subtasks_in_loop_iteration(
    parent_task_id: &str,
    substituted_parent: &crate::dsl::schema::TaskSpec,
    workflow_inputs: &HashMap<String, serde_json::Value>,
    agents: &Arc<Mutex<HashMap<String, PeriplonSDKClient>>>,
    task_graph: &Arc<Mutex<TaskGraph>>,
    state: &Arc<Mutex<Option<WorkflowState>>>,
    workflow_name: &Arc<String>,
    json_output: bool,
) -> Result<Option<String>> {
    // Execute each subtask in order
    // NOTE: subtasks are already substituted because they're part of substituted_parent
    for subtask_map in &substituted_parent.subtasks {
        for (subtask_name, subtask_spec) in subtask_map {
            let full_subtask_id = format!("{}.{}", parent_task_id, subtask_name);

            println!(
                "    Executing subtask: {} - {}",
                full_subtask_id, subtask_spec.description
            );

            // Check if subtask has dependencies and if they're met
            if !subtask_spec.depends_on.is_empty() {
                // Check dependencies within the same iteration
                let deps_met = {
                    let graph = task_graph.lock().await;
                    subtask_spec.depends_on.iter().all(|dep| {
                        // For local dependencies (sibling subtasks), check if they completed
                        let dep_full_id = if dep.contains('.') {
                            dep.clone()
                        } else {
                            format!("{}.{}", parent_task_id, dep)
                        };

                        // Check in task graph
                        if let Some(dep_task) = graph.get_task(&dep_full_id) {
                            dep_task.status == TaskStatus::Completed
                        } else {
                            // Dependency not in graph, assume it's met
                            true
                        }
                    })
                };

                if !deps_met {
                    println!(
                        "      Skipping subtask {} - dependencies not met",
                        subtask_name
                    );
                    continue;
                }
            }

            // Check condition if present
            if let Some(ref condition) = subtask_spec.condition {
                let condition_met = {
                    let graph = task_graph.lock().await;
                    let workflow_state = state.lock().await;
                    evaluate_condition(condition, &graph, workflow_state.as_ref())
                };

                if !condition_met {
                    println!(
                        "      Skipping subtask {} - condition not met",
                        subtask_name
                    );
                    continue;
                }
            }

            // Execute subtask
            let result = execute_task_attempt(
                &full_subtask_id,
                &subtask_spec.description,
                subtask_spec,
                workflow_inputs,
                agents,
                0,
                state,
                workflow_name,
                json_output,
            )
            .await;

            // Update status in task graph and handle errors
            match result {
                Ok(_) => {
                    let mut graph = task_graph.lock().await;
                    let _ = graph.update_task_status(&full_subtask_id, TaskStatus::Completed);
                    println!("      ✓ Subtask {} completed", subtask_name);
                }
                Err(e) => {
                    let mut graph = task_graph.lock().await;
                    let _ = graph.update_task_status(&full_subtask_id, TaskStatus::Failed);
                    println!("      ✗ Subtask {} failed: {}", subtask_name, e);
                    // If subtask fails and has no error recovery, fail the iteration
                    return Err(e);
                }
            }
        }
    }

    Ok(None)
}

/// Execute ForEach loop sequentially
async fn execute_foreach_sequential(
    task_id: &str,
    spec: &crate::dsl::schema::TaskSpec,
    items: &[serde_json::Value],
    iterator: &str,
    ctx: &ExecutionContext<'_>,
) -> Result<()> {
    // Wrap loop execution with timeout if specified
    let timeout_duration = spec
        .loop_control
        .as_ref()
        .and_then(|lc| lc.timeout_secs)
        .map(tokio::time::Duration::from_secs);

    let loop_future = async {
        // Get checkpoint interval if configured
        let checkpoint_interval = spec
            .loop_control
            .as_ref()
            .and_then(|lc| lc.checkpoint_interval)
            .filter(|&interval| interval > 0);

        for (iteration, item) in items.iter().enumerate() {
            // Check if this iteration was already completed (resume capability)
            let already_completed = {
                let state_guard = ctx.state.lock().await;
                if let Some(ref workflow_state) = *state_guard {
                    workflow_state.is_iteration_completed(task_id, iteration)
                } else {
                    false
                }
            };

            if already_completed {
                println!(
                    "  Iteration {}: Already completed, skipping (resume)",
                    iteration + 1
                );
                continue;
            }

            // Check continue condition BEFORE executing iteration
            if let Some(ref loop_control) = spec.loop_control {
                if let Some(ref continue_cond) = loop_control.continue_condition {
                    let should_continue = {
                        let task_graph_guard = ctx.task_graph.lock().await;
                        let state_guard = ctx.state.lock().await;
                        evaluate_condition(continue_cond, &task_graph_guard, state_guard.as_ref())
                    };
                    if should_continue {
                        println!(
                            "  Iteration {}: Skipping due to continue condition",
                            iteration + 1
                        );
                        continue;
                    }
                }
            }

            println!(
                "  Iteration {}/{}: Processing item: {:?}",
                iteration + 1,
                items.len(),
                item
            );

            // Create loop context
            let mut context = LoopContext::new(iteration);
            context.set_variable(iterator.to_string(), item.clone());

            // Substitute variables in task
            let substituted_task = substitute_task_variables(spec, &context);

            // Update loop state
            {
                let mut state_guard = ctx.state.lock().await;
                if let Some(ref mut workflow_state) = *state_guard {
                    workflow_state.update_loop_iteration(
                        task_id,
                        iteration,
                        TaskStatus::Running,
                        Some(item.clone()),
                    );
                }
            }

            // Execute task iteration
            // If the task has subtasks, execute them instead of the parent task
            let result = if !substituted_task.subtasks.is_empty() {
                println!(
                    "  Task has {} subtasks - executing within loop iteration",
                    substituted_task.subtasks.len()
                );
                execute_subtasks_in_loop_iteration(
                    task_id,
                    &substituted_task,
                    ctx.workflow_inputs,
                    ctx.agents,
                    ctx.task_graph,
                    ctx.state,
                    ctx.workflow_name,
                    ctx.json_output,
                )
                .await
            } else {
                execute_task_attempt(
                    &format!("{}[{}]", task_id, iteration),
                    &substituted_task.description,
                    &substituted_task,
                    ctx.workflow_inputs,
                    ctx.agents,
                    0,
                    ctx.state,
                    ctx.workflow_name,
                    ctx.json_output,
                )
                .await
            };

            match result {
                Ok(output) => {
                    // Update iteration status
                    {
                        let mut state_guard = ctx.state.lock().await;
                        if let Some(ref mut workflow_state) = *state_guard {
                            workflow_state.update_loop_iteration(
                                task_id,
                                iteration,
                                TaskStatus::Completed,
                                Some(item.clone()),
                            );

                            // Store result if collection is enabled
                            if spec
                                .loop_control
                                .as_ref()
                                .is_some_and(|lc| lc.collect_results)
                            {
                                if let Some(output_str) = output {
                                    workflow_state.store_loop_result(
                                        task_id,
                                        serde_json::Value::String(output_str),
                                    );
                                }
                            }
                        }
                    }
                    println!("  Iteration {} completed successfully", iteration + 1);

                    // Save checkpoint if configured and interval reached
                    if let Some(interval) = checkpoint_interval {
                        if (iteration + 1) % interval == 0 {
                            let state_guard = ctx.state.lock().await;
                            if let Some(ref workflow_state) = *state_guard {
                                if let Err(e) = workflow_state.save_checkpoint() {
                                    println!("  Warning: Failed to save checkpoint: {}", e);
                                } else {
                                    println!("  Checkpoint saved at iteration {}", iteration + 1);
                                }
                            }
                        }
                    }
                }
                Err(e) => {
                    // Update iteration status
                    {
                        let mut state_guard = ctx.state.lock().await;
                        if let Some(ref mut workflow_state) = *state_guard {
                            workflow_state.update_loop_iteration(
                                task_id,
                                iteration,
                                TaskStatus::Failed,
                                Some(item.clone()),
                            );
                        }
                    }

                    // Check if we should break on error
                    let break_on_error = spec
                        .loop_control
                        .as_ref()
                        .and_then(|lc| lc.break_condition.as_ref())
                        .is_some();

                    if break_on_error {
                        return Err(e);
                    }

                    println!("  Iteration {} failed: {}", iteration + 1, e);
                }
            }

            // Check break condition AFTER executing iteration
            if let Some(ref loop_control) = spec.loop_control {
                if let Some(ref break_cond) = loop_control.break_condition {
                    let should_break = {
                        let task_graph_guard = ctx.task_graph.lock().await;
                        let state_guard = ctx.state.lock().await;
                        evaluate_condition(break_cond, &task_graph_guard, state_guard.as_ref())
                    };
                    if should_break {
                        println!(
                            "  Breaking loop due to break condition at iteration {}",
                            iteration + 1
                        );
                        break;
                    }
                }
            }
        }

        Ok(())
    };

    // Execute with or without timeout
    if let Some(timeout) = timeout_duration {
        match tokio::time::timeout(timeout, loop_future).await {
            Ok(result) => result,
            Err(_) => {
                println!("  Loop timed out after {:?}", timeout);
                Err(Error::InvalidInput(format!(
                    "Loop '{}' timed out after {} seconds",
                    task_id,
                    timeout.as_secs()
                )))
            }
        }
    } else {
        loop_future.await
    }
}

/// Execute Repeat loop sequentially
async fn execute_repeat_sequential(
    task_id: &str,
    spec: &crate::dsl::schema::TaskSpec,
    count: usize,
    iterator: Option<&str>,
    ctx: &ExecutionContext<'_>,
) -> Result<()> {
    for iteration in 0..count {
        // Check continue condition BEFORE executing iteration
        if let Some(ref loop_control) = spec.loop_control {
            if let Some(ref continue_cond) = loop_control.continue_condition {
                let should_continue = {
                    let task_graph_guard = ctx.task_graph.lock().await;
                    let state_guard = ctx.state.lock().await;
                    evaluate_condition(continue_cond, &task_graph_guard, state_guard.as_ref())
                };
                if should_continue {
                    println!(
                        "  Iteration {}: Skipping due to continue condition",
                        iteration + 1
                    );
                    continue;
                }
            }
        }

        println!("  Iteration {}/{}", iteration + 1, count);

        // Create loop context
        let mut context = LoopContext::new(iteration);
        if let Some(iter_name) = iterator {
            context.set_variable(
                iter_name.to_string(),
                serde_json::Value::Number(iteration.into()),
            );
        }

        // Substitute variables in task
        let substituted_task = substitute_task_variables(spec, &context);

        // Update loop state
        {
            let mut state_guard = ctx.state.lock().await;
            if let Some(ref mut workflow_state) = *state_guard {
                workflow_state.update_loop_iteration(
                    task_id,
                    iteration,
                    TaskStatus::Running,
                    Some(serde_json::Value::Number(iteration.into())),
                );
            }
        }

        // Execute task iteration
        match execute_task_attempt(
            &format!("{}[{}]", task_id, iteration),
            &substituted_task.description,
            &substituted_task,
            ctx.workflow_inputs,
            ctx.agents,
            0,
            ctx.state,
            ctx.workflow_name,
            ctx.json_output,
        )
        .await
        {
            Ok(output) => {
                // Update iteration status
                {
                    let mut state_guard = ctx.state.lock().await;
                    if let Some(ref mut workflow_state) = *state_guard {
                        workflow_state.update_loop_iteration(
                            task_id,
                            iteration,
                            TaskStatus::Completed,
                            Some(serde_json::Value::Number(iteration.into())),
                        );

                        // Store result if collection is enabled
                        if spec
                            .loop_control
                            .as_ref()
                            .is_some_and(|lc| lc.collect_results)
                        {
                            if let Some(output_str) = output {
                                workflow_state.store_loop_result(
                                    task_id,
                                    serde_json::Value::String(output_str),
                                );
                            }
                        }
                    }
                }
                println!("  Iteration {} completed successfully", iteration + 1);
            }
            Err(e) => {
                // Update iteration status
                {
                    let mut state_guard = ctx.state.lock().await;
                    if let Some(ref mut workflow_state) = *state_guard {
                        workflow_state.update_loop_iteration(
                            task_id,
                            iteration,
                            TaskStatus::Failed,
                            Some(serde_json::Value::Number(iteration.into())),
                        );
                    }
                }

                // Check if we should break on error
                let break_on_error = spec
                    .loop_control
                    .as_ref()
                    .and_then(|lc| lc.break_condition.as_ref())
                    .is_some();

                if break_on_error {
                    return Err(e);
                }

                println!("  Iteration {} failed: {}", iteration + 1, e);
            }
        }

        // Check break condition AFTER executing iteration
        if let Some(ref loop_control) = spec.loop_control {
            if let Some(ref break_cond) = loop_control.break_condition {
                let should_break = {
                    let task_graph_guard = ctx.task_graph.lock().await;
                    let state_guard = ctx.state.lock().await;
                    evaluate_condition(break_cond, &task_graph_guard, state_guard.as_ref())
                };
                if should_break {
                    println!(
                        "  Breaking loop due to break condition at iteration {}",
                        iteration + 1
                    );
                    break;
                }
            }
        }
    }

    Ok(())
}

/// Execute While loop sequentially
///
/// Evaluates condition BEFORE each iteration. Stops when condition becomes false.
async fn execute_while_sequential(
    task_id: &str,
    spec: &crate::dsl::schema::TaskSpec,
    condition: &crate::dsl::schema::ConditionSpec,
    max_iterations: usize,
    iteration_variable: Option<&str>,
    delay_between_secs: Option<u64>,
    ctx: &ExecutionContext<'_>,
) -> Result<()> {
    let mut iteration = 0;

    loop {
        // Check max iterations safety limit
        if iteration >= max_iterations {
            println!(
                "  While loop reached max iterations limit: {}",
                max_iterations
            );
            break;
        }

        // Evaluate condition BEFORE executing iteration
        let condition_met = {
            let state_guard = ctx.state.lock().await;
            let task_graph = TaskGraph::new(); // We need access to task_graph for condition evaluation
            evaluate_condition(condition, &task_graph, state_guard.as_ref())
        };

        if !condition_met {
            println!(
                "  While loop condition became false at iteration {}",
                iteration
            );
            break;
        }

        println!(
            "  Iteration {}: Condition is true, executing...",
            iteration + 1
        );

        // Create loop context
        let mut context = LoopContext::new(iteration);
        if let Some(iter_name) = iteration_variable {
            context.set_variable(
                iter_name.to_string(),
                serde_json::Value::Number(iteration.into()),
            );
        }

        // Substitute variables in task
        let substituted_task = substitute_task_variables(spec, &context);

        // Update loop state
        {
            let mut state_guard = ctx.state.lock().await;
            if let Some(ref mut workflow_state) = *state_guard {
                workflow_state.update_loop_iteration(
                    task_id,
                    iteration,
                    TaskStatus::Running,
                    Some(serde_json::Value::Number(iteration.into())),
                );
            }
        }

        // Execute task iteration
        match execute_task_attempt(
            &format!("{}[{}]", task_id, iteration),
            &substituted_task.description,
            &substituted_task,
            ctx.workflow_inputs,
            ctx.agents,
            0,
            ctx.state,
            ctx.workflow_name,
            ctx.json_output,
        )
        .await
        {
            Ok(output) => {
                // Update iteration status
                {
                    let mut state_guard = ctx.state.lock().await;
                    if let Some(ref mut workflow_state) = *state_guard {
                        workflow_state.update_loop_iteration(
                            task_id,
                            iteration,
                            TaskStatus::Completed,
                            Some(serde_json::Value::Number(iteration.into())),
                        );

                        // Store result if collection is enabled
                        if spec
                            .loop_control
                            .as_ref()
                            .is_some_and(|lc| lc.collect_results)
                        {
                            if let Some(output_str) = output {
                                workflow_state.store_loop_result(
                                    task_id,
                                    serde_json::Value::String(output_str),
                                );
                            }
                        }
                    }
                }
                println!("  Iteration {} completed successfully", iteration + 1);
            }
            Err(e) => {
                // Update iteration status
                {
                    let mut state_guard = ctx.state.lock().await;
                    if let Some(ref mut workflow_state) = *state_guard {
                        workflow_state.update_loop_iteration(
                            task_id,
                            iteration,
                            TaskStatus::Failed,
                            Some(serde_json::Value::Number(iteration.into())),
                        );
                    }
                }

                // Check if we should break on error
                let break_on_error = spec
                    .loop_control
                    .as_ref()
                    .and_then(|lc| lc.break_condition.as_ref())
                    .is_some();

                if break_on_error {
                    return Err(e);
                }

                println!("  Iteration {} failed: {}", iteration + 1, e);
            }
        }

        iteration += 1;

        // Apply delay if configured
        if let Some(delay_secs) = delay_between_secs {
            if delay_secs > 0 {
                println!("  Waiting {} seconds before next iteration...", delay_secs);
                tokio::time::sleep(tokio::time::Duration::from_secs(delay_secs)).await;
            }
        }
    }

    println!("  While loop completed after {} iterations", iteration);
    Ok(())
}

/// Execute RepeatUntil loop sequentially
///
/// Executes at least once (or min_iterations times), evaluates condition AFTER each iteration.
/// Stops when condition becomes true.
#[allow(clippy::too_many_arguments)]
async fn execute_repeat_until_sequential(
    task_id: &str,
    spec: &crate::dsl::schema::TaskSpec,
    condition: &crate::dsl::schema::ConditionSpec,
    min_iterations: Option<usize>,
    max_iterations: usize,
    iteration_variable: Option<&str>,
    delay_between_secs: Option<u64>,
    ctx: &ExecutionContext<'_>,
) -> Result<()> {
    let min = min_iterations.unwrap_or(1);
    let mut iteration = 0;

    loop {
        // Check max iterations safety limit
        if iteration >= max_iterations {
            println!(
                "  RepeatUntil loop reached max iterations limit: {}",
                max_iterations
            );
            break;
        }

        println!("  Iteration {}", iteration + 1);

        // Create loop context
        let mut context = LoopContext::new(iteration);
        if let Some(iter_name) = iteration_variable {
            context.set_variable(
                iter_name.to_string(),
                serde_json::Value::Number(iteration.into()),
            );
        }

        // Substitute variables in task
        let substituted_task = substitute_task_variables(spec, &context);

        // Update loop state
        {
            let mut state_guard = ctx.state.lock().await;
            if let Some(ref mut workflow_state) = *state_guard {
                workflow_state.update_loop_iteration(
                    task_id,
                    iteration,
                    TaskStatus::Running,
                    Some(serde_json::Value::Number(iteration.into())),
                );
            }
        }

        // Execute task iteration
        match execute_task_attempt(
            &format!("{}[{}]", task_id, iteration),
            &substituted_task.description,
            &substituted_task,
            ctx.workflow_inputs,
            ctx.agents,
            0,
            ctx.state,
            ctx.workflow_name,
            ctx.json_output,
        )
        .await
        {
            Ok(output) => {
                // Update iteration status
                {
                    let mut state_guard = ctx.state.lock().await;
                    if let Some(ref mut workflow_state) = *state_guard {
                        workflow_state.update_loop_iteration(
                            task_id,
                            iteration,
                            TaskStatus::Completed,
                            Some(serde_json::Value::Number(iteration.into())),
                        );

                        // Store result if collection is enabled
                        if spec
                            .loop_control
                            .as_ref()
                            .is_some_and(|lc| lc.collect_results)
                        {
                            if let Some(output_str) = output {
                                workflow_state.store_loop_result(
                                    task_id,
                                    serde_json::Value::String(output_str),
                                );
                            }
                        }
                    }
                }
                println!("  Iteration {} completed successfully", iteration + 1);
            }
            Err(e) => {
                // Update iteration status
                {
                    let mut state_guard = ctx.state.lock().await;
                    if let Some(ref mut workflow_state) = *state_guard {
                        workflow_state.update_loop_iteration(
                            task_id,
                            iteration,
                            TaskStatus::Failed,
                            Some(serde_json::Value::Number(iteration.into())),
                        );
                    }
                }

                // Check if we should break on error
                let break_on_error = spec
                    .loop_control
                    .as_ref()
                    .and_then(|lc| lc.break_condition.as_ref())
                    .is_some();

                if break_on_error {
                    return Err(e);
                }

                println!("  Iteration {} failed: {}", iteration + 1, e);
            }
        }

        iteration += 1;

        // Evaluate condition AFTER executing iteration
        let condition_met = {
            let state_guard = ctx.state.lock().await;
            let task_graph = TaskGraph::new(); // We need access to task_graph for condition evaluation
            evaluate_condition(condition, &task_graph, state_guard.as_ref())
        };

        // Stop if condition is met AND we've done minimum iterations
        if condition_met && iteration >= min {
            println!(
                "  RepeatUntil condition became true at iteration {}",
                iteration
            );
            break;
        }

        // Apply delay if configured
        if let Some(delay_secs) = delay_between_secs {
            if delay_secs > 0 {
                println!("  Waiting {} seconds before next iteration...", delay_secs);
                tokio::time::sleep(tokio::time::Duration::from_secs(delay_secs)).await;
            }
        }
    }

    println!(
        "  RepeatUntil loop completed after {} iterations",
        iteration
    );
    Ok(())
}

/// Execute ForEach loop in parallel with semaphore-based concurrency limiting
///
/// Spawns tasks for each iteration but limits concurrent execution via Semaphore.
async fn execute_foreach_parallel(
    task_id: &str,
    spec: &crate::dsl::schema::TaskSpec,
    items: &[serde_json::Value],
    iterator: &str,
    max_parallel: usize,
    workflow_inputs: Arc<HashMap<String, serde_json::Value>>,
    ctx: &ExecutionContext<'_>,
) -> Result<()> {
    use tokio::task::JoinSet;

    println!(
        "  Executing ForEach in parallel: {} items, max {} concurrent",
        items.len(),
        max_parallel
    );

    // Clone items to owned Vec to avoid lifetime issues
    let items_owned: Vec<_> = items.to_vec();
    let total_items = items_owned.len();

    // Create semaphore to limit concurrency
    let semaphore = Arc::new(Semaphore::new(max_parallel));

    // Create join set to track spawned tasks
    let mut join_set = JoinSet::new();

    // Spawn tasks for each iteration
    for (iteration, item) in items_owned.into_iter().enumerate() {
        let task_id = task_id.to_string();
        let spec = spec.clone();
        let iterator = iterator.to_string();
        let agents = ctx.agents.clone();
        let state = ctx.state.clone();
        let semaphore = semaphore.clone();
        let workflow_inputs_clone = workflow_inputs.clone();
        let workflow_name_clone = ctx.workflow_name.clone();
        let json_output = ctx.json_output;

        join_set.spawn(async move {
            // Acquire semaphore permit
            let _permit = semaphore.acquire().await.unwrap();

            println!(
                "  [Parallel] Iteration {}/{}: Processing item: {:?}",
                iteration + 1,
                total_items,
                item
            );

            // Create loop context
            let mut context = LoopContext::new(iteration);
            context.set_variable(iterator, item.clone()); // Clone for state tracking

            // Substitute variables in task
            let substituted_task = substitute_task_variables(&spec, &context);

            // Update loop state to Running
            {
                let mut state_guard = state.lock().await;
                if let Some(ref mut workflow_state) = *state_guard {
                    workflow_state.update_loop_iteration(
                        &task_id,
                        iteration,
                        TaskStatus::Running,
                        Some(item.clone()),
                    );
                }
            }

            // Execute task iteration
            let result = execute_task_attempt(
                &format!("{}[{}]", task_id, iteration),
                &substituted_task.description,
                &substituted_task,
                &workflow_inputs_clone,
                &agents,
                0,
                &state,
                &workflow_name_clone,
                json_output,
            )
            .await;

            // Update state based on result
            match result {
                Ok(output) => {
                    let mut state_guard = state.lock().await;
                    if let Some(ref mut workflow_state) = *state_guard {
                        workflow_state.update_loop_iteration(
                            &task_id,
                            iteration,
                            TaskStatus::Completed,
                            Some(item.clone()),
                        );

                        // Store result if collection is enabled
                        if spec
                            .loop_control
                            .as_ref()
                            .is_some_and(|lc| lc.collect_results)
                        {
                            if let Some(output_str) = output {
                                workflow_state.store_loop_result(
                                    &task_id,
                                    serde_json::Value::String(output_str),
                                );
                            }
                        }
                    }
                    println!(
                        "  [Parallel] Iteration {} completed successfully",
                        iteration + 1
                    );
                    Ok(())
                }
                Err(e) => {
                    let mut state_guard = state.lock().await;
                    if let Some(ref mut workflow_state) = *state_guard {
                        workflow_state.update_loop_iteration(
                            &task_id,
                            iteration,
                            TaskStatus::Failed,
                            Some(item),
                        );
                    }
                    println!("  [Parallel] Iteration {} failed: {}", iteration + 1, e);
                    Err(e)
                }
            }
        });
    }

    // Wait for all tasks to complete and collect results
    let mut errors = Vec::new();
    while let Some(result) = join_set.join_next().await {
        match result {
            Ok(Ok(())) => {
                // Task completed successfully
            }
            Ok(Err(e)) => {
                // Task failed
                errors.push(e);
            }
            Err(join_err) => {
                // Join error (task panicked)
                errors.push(Error::InvalidInput(format!("Task panicked: {}", join_err)));
            }
        }
    }

    // Return first error if any occurred
    if let Some(error) = errors.into_iter().next() {
        return Err(error);
    }

    Ok(())
}

/// Execute Repeat loop in parallel with semaphore-based concurrency limiting
///
/// Spawns tasks for each iteration but limits concurrent execution via Semaphore.
async fn execute_repeat_parallel(
    task_id: &str,
    spec: &crate::dsl::schema::TaskSpec,
    count: usize,
    iterator: Option<&str>,
    max_parallel: usize,
    workflow_inputs: Arc<HashMap<String, serde_json::Value>>,
    ctx: &ExecutionContext<'_>,
) -> Result<()> {
    use tokio::task::JoinSet;

    println!(
        "  Executing Repeat in parallel: {} iterations, max {} concurrent",
        count, max_parallel
    );

    // Create semaphore to limit concurrency
    let semaphore = Arc::new(Semaphore::new(max_parallel));

    // Create join set to track spawned tasks
    let mut join_set = JoinSet::new();

    // Spawn tasks for each iteration
    for iteration in 0..count {
        let task_id = task_id.to_string();
        let spec = spec.clone();
        let iterator = iterator.map(|s| s.to_string());
        let agents = ctx.agents.clone();
        let state = ctx.state.clone();
        let semaphore = semaphore.clone();
        let workflow_inputs_clone = workflow_inputs.clone();
        let workflow_name_clone = ctx.workflow_name.clone();
        let json_output = ctx.json_output;

        join_set.spawn(async move {
            // Acquire semaphore permit
            let _permit = semaphore.acquire().await.unwrap();

            println!("  [Parallel] Iteration {}/{}", iteration + 1, count);

            // Create loop context
            let mut context = LoopContext::new(iteration);
            if let Some(iter_name) = iterator {
                context.set_variable(iter_name, serde_json::Value::Number(iteration.into()));
            }

            // Substitute variables in task
            let substituted_task = substitute_task_variables(&spec, &context);

            // Update loop state to Running
            {
                let mut state_guard = state.lock().await;
                if let Some(ref mut workflow_state) = *state_guard {
                    workflow_state.update_loop_iteration(
                        &task_id,
                        iteration,
                        TaskStatus::Running,
                        Some(serde_json::Value::Number(iteration.into())),
                    );
                }
            }

            // Execute task iteration
            let result = execute_task_attempt(
                &format!("{}[{}]", task_id, iteration),
                &substituted_task.description,
                &substituted_task,
                &workflow_inputs_clone,
                &agents,
                0,
                &state,
                &workflow_name_clone,
                json_output,
            )
            .await;

            // Update state based on result
            match result {
                Ok(output) => {
                    let mut state_guard = state.lock().await;
                    if let Some(ref mut workflow_state) = *state_guard {
                        workflow_state.update_loop_iteration(
                            &task_id,
                            iteration,
                            TaskStatus::Completed,
                            Some(serde_json::Value::Number(iteration.into())),
                        );

                        // Store result if collection is enabled
                        if spec
                            .loop_control
                            .as_ref()
                            .is_some_and(|lc| lc.collect_results)
                        {
                            if let Some(output_str) = output {
                                workflow_state.store_loop_result(
                                    &task_id,
                                    serde_json::Value::String(output_str),
                                );
                            }
                        }
                    }
                    println!(
                        "  [Parallel] Iteration {} completed successfully",
                        iteration + 1
                    );
                    Ok(())
                }
                Err(e) => {
                    let mut state_guard = state.lock().await;
                    if let Some(ref mut workflow_state) = *state_guard {
                        workflow_state.update_loop_iteration(
                            &task_id,
                            iteration,
                            TaskStatus::Failed,
                            Some(serde_json::Value::Number(iteration.into())),
                        );
                    }
                    println!("  [Parallel] Iteration {} failed: {}", iteration + 1, e);
                    Err(e)
                }
            }
        });
    }

    // Wait for all tasks to complete and collect results
    let mut errors = Vec::new();
    while let Some(result) = join_set.join_next().await {
        match result {
            Ok(Ok(())) => {
                // Task completed successfully
            }
            Ok(Err(e)) => {
                // Task failed
                errors.push(e);
            }
            Err(join_err) => {
                // Join error (task panicked)
                errors.push(Error::InvalidInput(format!("Task panicked: {}", join_err)));
            }
        }
    }

    // Return first error if any occurred
    if let Some(error) = errors.into_iter().next() {
        return Err(error);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::Provider;
    use crate::dsl::schema::PermissionsSpec;

    #[test]
    fn test_executor_creation() {
        let workflow = DSLWorkflow {
            provider: Provider::Claude,
            model: None,
            name: "Test Workflow".to_string(),
            version: "1.0.0".to_string(),
            dsl_version: "1.0.0".to_string(),
            cwd: None,
            create_cwd: None,
            secrets: HashMap::new(),
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            agents: HashMap::new(),
            tasks: HashMap::new(),
            workflows: HashMap::new(),
            tools: None,
            communication: None,
            mcp_servers: HashMap::new(),
            subflows: HashMap::new(),
            imports: HashMap::new(),
            notifications: None,
            limits: None,
        };

        let executor = DSLExecutor::new(workflow).unwrap();
        let (name, version) = executor.get_workflow_info();
        assert_eq!(name, "Test Workflow");
        assert_eq!(version, "1.0.0");
    }

    #[test]
    fn test_agent_spec_to_options() {
        let workflow = DSLWorkflow {
            provider: Provider::Claude,
            model: None,
            name: "Test".to_string(),
            version: "1.0.0".to_string(),
            dsl_version: "1.0.0".to_string(),
            cwd: None,
            create_cwd: None,
            secrets: HashMap::new(),
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            agents: HashMap::new(),
            tasks: HashMap::new(),
            workflows: HashMap::new(),
            tools: None,
            communication: None,
            mcp_servers: HashMap::new(),
            subflows: HashMap::new(),
            imports: HashMap::new(),
            notifications: None,
            limits: None,
        };

        let executor = DSLExecutor::new(workflow).unwrap();

        let agent_spec = AgentSpec {
            provider: None,
            description: "Test agent".to_string(),
            model: Some("claude-sonnet-4-5".to_string()),
            system_prompt: None,
            cwd: None,
            create_cwd: None,
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            tools: vec!["Read".to_string(), "Write".to_string()],
            permissions: PermissionsSpec {
                mode: "acceptEdits".to_string(),
                allowed_directories: vec!["./src".to_string(), "/tmp/test".to_string()],
            },
            max_turns: Some(10),
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let options = executor
            .agent_spec_to_options(&agent_spec, None, None, &var_context)
            .unwrap();
        assert_eq!(options.allowed_tools.len(), 2);
        assert_eq!(options.model, Some("claude-sonnet-4-5".to_string()));
        assert_eq!(options.max_turns, Some(10));
        assert_eq!(options.permission_mode, Some("acceptEdits".to_string()));
        assert_eq!(options.add_dirs.len(), 2);
        assert_eq!(options.add_dirs[0], std::path::PathBuf::from("./src"));
        assert_eq!(options.add_dirs[1], std::path::PathBuf::from("/tmp/test"));
        assert_eq!(options.cwd, None); // No cwd set
        assert!(!options.create_cwd); // Default is false
    }

    #[test]
    fn test_cwd_workflow_level_only() {
        let workflow = DSLWorkflow {
            provider: Provider::Claude,
            model: None,
            name: "Test".to_string(),
            version: "1.0.0".to_string(),
            dsl_version: "1.0.0".to_string(),
            cwd: Some("/workflow/dir".to_string()),
            create_cwd: None,
            secrets: HashMap::new(),
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            agents: HashMap::new(),
            tasks: HashMap::new(),
            workflows: HashMap::new(),
            tools: None,
            communication: None,
            mcp_servers: HashMap::new(),
            subflows: HashMap::new(),
            imports: HashMap::new(),
            notifications: None,
            limits: None,
        };

        let executor = DSLExecutor::new(workflow).unwrap();

        let agent_spec = AgentSpec {
            provider: None,
            description: "Test agent".to_string(),
            model: None,
            system_prompt: None,
            cwd: None,
            create_cwd: None,
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            tools: vec![],
            permissions: PermissionsSpec::default(),
            max_turns: None,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let options = executor
            .agent_spec_to_options(&agent_spec, Some("/workflow/dir"), None, &var_context)
            .unwrap();
        assert_eq!(options.cwd, Some(std::path::PathBuf::from("/workflow/dir")));
    }

    #[test]
    fn test_cwd_agent_level_only() {
        let workflow = DSLWorkflow {
            provider: Provider::Claude,
            model: None,
            name: "Test".to_string(),
            version: "1.0.0".to_string(),
            dsl_version: "1.0.0".to_string(),
            cwd: None,
            create_cwd: None,
            secrets: HashMap::new(),
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            agents: HashMap::new(),
            tasks: HashMap::new(),
            workflows: HashMap::new(),
            tools: None,
            communication: None,
            mcp_servers: HashMap::new(),
            subflows: HashMap::new(),
            imports: HashMap::new(),
            notifications: None,
            limits: None,
        };

        let executor = DSLExecutor::new(workflow).unwrap();

        let agent_spec = AgentSpec {
            provider: None,
            description: "Test agent".to_string(),
            model: None,
            system_prompt: None,
            cwd: Some("/agent/dir".to_string()),
            create_cwd: None,
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            tools: vec![],
            permissions: PermissionsSpec::default(),
            max_turns: None,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let options = executor
            .agent_spec_to_options(&agent_spec, None, None, &var_context)
            .unwrap();
        assert_eq!(options.cwd, Some(std::path::PathBuf::from("/agent/dir")));
    }

    #[test]
    fn test_cwd_agent_overrides_workflow() {
        let workflow = DSLWorkflow {
            provider: Provider::Claude,
            model: None,
            name: "Test".to_string(),
            version: "1.0.0".to_string(),
            dsl_version: "1.0.0".to_string(),
            cwd: Some("/workflow/dir".to_string()),
            create_cwd: None,
            secrets: HashMap::new(),
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            agents: HashMap::new(),
            tasks: HashMap::new(),
            workflows: HashMap::new(),
            tools: None,
            communication: None,
            mcp_servers: HashMap::new(),
            subflows: HashMap::new(),
            imports: HashMap::new(),
            notifications: None,
            limits: None,
        };

        let executor = DSLExecutor::new(workflow).unwrap();

        let agent_spec = AgentSpec {
            provider: None,
            description: "Test agent".to_string(),
            model: None,
            system_prompt: None,
            cwd: Some("/agent/dir".to_string()),
            create_cwd: None,
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            tools: vec![],
            permissions: PermissionsSpec::default(),
            max_turns: None,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let options = executor
            .agent_spec_to_options(&agent_spec, Some("/workflow/dir"), None, &var_context)
            .unwrap();
        // Agent-level cwd should override workflow-level
        assert_eq!(options.cwd, Some(std::path::PathBuf::from("/agent/dir")));
    }

    #[test]
    fn test_cwd_backwards_compatibility() {
        let workflow = DSLWorkflow {
            provider: Provider::Claude,
            model: None,
            name: "Test".to_string(),
            version: "1.0.0".to_string(),
            dsl_version: "1.0.0".to_string(),
            cwd: None,
            create_cwd: None,
            secrets: HashMap::new(),
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            agents: HashMap::new(),
            tasks: HashMap::new(),
            workflows: HashMap::new(),
            tools: None,
            communication: None,
            mcp_servers: HashMap::new(),
            subflows: HashMap::new(),
            imports: HashMap::new(),
            notifications: None,
            limits: None,
        };

        let executor = DSLExecutor::new(workflow).unwrap();

        let agent_spec = AgentSpec {
            provider: None,
            description: "Test agent".to_string(),
            model: None,
            system_prompt: None,
            cwd: None,
            create_cwd: None,
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            tools: vec![],
            permissions: PermissionsSpec::default(),
            max_turns: None,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let options = executor
            .agent_spec_to_options(&agent_spec, None, None, &var_context)
            .unwrap();
        // No cwd set - should default to None (current directory)
        assert_eq!(options.cwd, None);
    }

    #[test]
    fn test_create_cwd_workflow_level() {
        let workflow = DSLWorkflow {
            provider: Provider::Claude,
            model: None,
            name: "Test".to_string(),
            version: "1.0.0".to_string(),
            dsl_version: "1.0.0".to_string(),
            cwd: Some("/tmp/test".to_string()),
            create_cwd: Some(true),
            secrets: HashMap::new(),
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            agents: HashMap::new(),
            tasks: HashMap::new(),
            workflows: HashMap::new(),
            tools: None,
            communication: None,
            mcp_servers: HashMap::new(),
            subflows: HashMap::new(),
            imports: HashMap::new(),
            notifications: None,
            limits: None,
        };

        let executor = DSLExecutor::new(workflow).unwrap();

        let agent_spec = AgentSpec {
            provider: None,
            description: "Test agent".to_string(),
            model: None,
            system_prompt: None,
            cwd: None,
            create_cwd: None,
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            tools: vec![],
            permissions: PermissionsSpec::default(),
            max_turns: None,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let options = executor
            .agent_spec_to_options(&agent_spec, Some("/tmp/test"), Some(true), &var_context)
            .unwrap();
        assert!(options.create_cwd);
    }

    #[test]
    fn test_create_cwd_agent_overrides_workflow() {
        let workflow = DSLWorkflow {
            provider: Provider::Claude,
            model: None,
            name: "Test".to_string(),
            version: "1.0.0".to_string(),
            dsl_version: "1.0.0".to_string(),
            cwd: Some("/tmp/test".to_string()),
            create_cwd: Some(true),
            secrets: HashMap::new(),
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            agents: HashMap::new(),
            tasks: HashMap::new(),
            workflows: HashMap::new(),
            tools: None,
            communication: None,
            mcp_servers: HashMap::new(),
            subflows: HashMap::new(),
            imports: HashMap::new(),
            notifications: None,
            limits: None,
        };

        let executor = DSLExecutor::new(workflow).unwrap();

        let agent_spec = AgentSpec {
            provider: None,
            description: "Test agent".to_string(),
            model: None,
            system_prompt: None,
            cwd: Some("/agent/dir".to_string()),
            create_cwd: Some(false), // Agent explicitly disables create_cwd
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            tools: vec![],
            permissions: PermissionsSpec::default(),
            max_turns: None,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let options = executor
            .agent_spec_to_options(&agent_spec, Some("/tmp/test"), Some(true), &var_context)
            .unwrap();
        // Agent-level create_cwd should override workflow-level
        assert!(!options.create_cwd);
    }

    #[test]
    fn test_create_cwd_defaults_to_false() {
        let workflow = DSLWorkflow {
            provider: Provider::Claude,
            model: None,
            name: "Test".to_string(),
            version: "1.0.0".to_string(),
            dsl_version: "1.0.0".to_string(),
            cwd: Some("/tmp/test".to_string()),
            create_cwd: None,
            secrets: HashMap::new(),
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            agents: HashMap::new(),
            tasks: HashMap::new(),
            workflows: HashMap::new(),
            tools: None,
            communication: None,
            mcp_servers: HashMap::new(),
            subflows: HashMap::new(),
            imports: HashMap::new(),
            notifications: None,
            limits: None,
        };

        let executor = DSLExecutor::new(workflow).unwrap();

        let agent_spec = AgentSpec {
            provider: None,
            description: "Test agent".to_string(),
            model: None,
            system_prompt: None,
            cwd: None,
            create_cwd: None,
            inputs: HashMap::new(),
            outputs: HashMap::new(),
            tools: vec![],
            permissions: PermissionsSpec::default(),
            max_turns: None,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let options = executor
            .agent_spec_to_options(&agent_spec, Some("/tmp/test"), None, &var_context)
            .unwrap();
        // No create_cwd set - should default to false
        assert!(!options.create_cwd);
    }

    #[test]
    fn test_condition_always() {
        use crate::dsl::schema::{Condition, ConditionSpec};

        let task_graph = TaskGraph::new();
        let condition = ConditionSpec::Single(Condition::Always);
        assert!(evaluate_condition(&condition, &task_graph, None));
    }

    #[test]
    fn test_condition_never() {
        use crate::dsl::schema::{Condition, ConditionSpec};

        let task_graph = TaskGraph::new();
        let condition = ConditionSpec::Single(Condition::Never);
        assert!(!evaluate_condition(&condition, &task_graph, None));
    }

    #[test]
    fn test_condition_task_status_completed() {
        use crate::dsl::schema::{Condition, ConditionSpec, TaskSpec, TaskStatusCondition};

        let mut task_graph = TaskGraph::new();
        task_graph.add_task("task1".to_string(), TaskSpec::default());
        task_graph
            .update_task_status("task1", TaskStatus::Completed)
            .unwrap();

        let condition = ConditionSpec::Single(Condition::TaskStatus {
            task: "task1".to_string(),
            status: TaskStatusCondition::Completed,
        });

        assert!(evaluate_condition(&condition, &task_graph, None));
    }

    #[test]
    fn test_condition_task_status_failed() {
        use crate::dsl::schema::{Condition, ConditionSpec, TaskSpec, TaskStatusCondition};

        let mut task_graph = TaskGraph::new();
        task_graph.add_task("task1".to_string(), TaskSpec::default());
        task_graph
            .update_task_status("task1", TaskStatus::Failed)
            .unwrap();

        let condition = ConditionSpec::Single(Condition::TaskStatus {
            task: "task1".to_string(),
            status: TaskStatusCondition::Failed,
        });

        assert!(evaluate_condition(&condition, &task_graph, None));
    }

    #[test]
    fn test_condition_task_status_skipped() {
        use crate::dsl::schema::{Condition, ConditionSpec, TaskSpec, TaskStatusCondition};

        let mut task_graph = TaskGraph::new();
        task_graph.add_task("task1".to_string(), TaskSpec::default());
        task_graph
            .update_task_status("task1", TaskStatus::Skipped)
            .unwrap();

        let condition = ConditionSpec::Single(Condition::TaskStatus {
            task: "task1".to_string(),
            status: TaskStatusCondition::Skipped,
        });

        assert!(evaluate_condition(&condition, &task_graph, None));
    }

    #[test]
    fn test_condition_state_equals() {
        use crate::dsl::schema::{Condition, ConditionSpec};

        let task_graph = TaskGraph::new();
        let mut workflow_state = WorkflowState::new("test".to_string(), "1.0.0".to_string());
        workflow_state.add_metadata("environment".to_string(), serde_json::json!("production"));

        let condition = ConditionSpec::Single(Condition::StateEquals {
            key: "environment".to_string(),
            value: serde_json::json!("production"),
        });

        assert!(evaluate_condition(
            &condition,
            &task_graph,
            Some(&workflow_state)
        ));
    }

    #[test]
    fn test_condition_state_exists() {
        use crate::dsl::schema::{Condition, ConditionSpec};

        let task_graph = TaskGraph::new();
        let mut workflow_state = WorkflowState::new("test".to_string(), "1.0.0".to_string());
        workflow_state.add_metadata("key1".to_string(), serde_json::json!("value1"));

        let condition = ConditionSpec::Single(Condition::StateExists {
            key: "key1".to_string(),
        });

        assert!(evaluate_condition(
            &condition,
            &task_graph,
            Some(&workflow_state)
        ));

        let condition_not_exists = ConditionSpec::Single(Condition::StateExists {
            key: "key2".to_string(),
        });

        assert!(!evaluate_condition(
            &condition_not_exists,
            &task_graph,
            Some(&workflow_state)
        ));
    }

    #[test]
    fn test_condition_and() {
        use crate::dsl::schema::{Condition, ConditionSpec};

        let task_graph = TaskGraph::new();
        let condition = ConditionSpec::And {
            and: vec![
                ConditionSpec::Single(Condition::Always),
                ConditionSpec::Single(Condition::Always),
            ],
        };

        assert!(evaluate_condition(&condition, &task_graph, None));

        let condition_with_never = ConditionSpec::And {
            and: vec![
                ConditionSpec::Single(Condition::Always),
                ConditionSpec::Single(Condition::Never),
            ],
        };

        assert!(!evaluate_condition(
            &condition_with_never,
            &task_graph,
            None
        ));
    }

    #[test]
    fn test_condition_or() {
        use crate::dsl::schema::{Condition, ConditionSpec};

        let task_graph = TaskGraph::new();
        let condition = ConditionSpec::Or {
            or: vec![
                ConditionSpec::Single(Condition::Always),
                ConditionSpec::Single(Condition::Never),
            ],
        };

        assert!(evaluate_condition(&condition, &task_graph, None));

        let condition_all_never = ConditionSpec::Or {
            or: vec![
                ConditionSpec::Single(Condition::Never),
                ConditionSpec::Single(Condition::Never),
            ],
        };

        assert!(!evaluate_condition(&condition_all_never, &task_graph, None));
    }

    #[test]
    fn test_condition_not() {
        use crate::dsl::schema::{Condition, ConditionSpec};

        let task_graph = TaskGraph::new();
        let condition = ConditionSpec::Not {
            not: Box::new(ConditionSpec::Single(Condition::Never)),
        };

        assert!(evaluate_condition(&condition, &task_graph, None));

        let condition_not_always = ConditionSpec::Not {
            not: Box::new(ConditionSpec::Single(Condition::Always)),
        };

        assert!(!evaluate_condition(
            &condition_not_always,
            &task_graph,
            None
        ));
    }

    #[test]
    fn test_condition_complex() {
        use crate::dsl::schema::{Condition, ConditionSpec, TaskSpec, TaskStatusCondition};

        let mut task_graph = TaskGraph::new();
        task_graph.add_task("task1".to_string(), TaskSpec::default());
        task_graph
            .update_task_status("task1", TaskStatus::Completed)
            .unwrap();

        let mut workflow_state = WorkflowState::new("test".to_string(), "1.0.0".to_string());
        workflow_state.add_metadata("env".to_string(), serde_json::json!("prod"));

        // (task1 completed) AND (env == "prod")
        let condition = ConditionSpec::And {
            and: vec![
                ConditionSpec::Single(Condition::TaskStatus {
                    task: "task1".to_string(),
                    status: TaskStatusCondition::Completed,
                }),
                ConditionSpec::Single(Condition::StateEquals {
                    key: "env".to_string(),
                    value: serde_json::json!("prod"),
                }),
            ],
        };

        assert!(evaluate_condition(
            &condition,
            &task_graph,
            Some(&workflow_state)
        ));
    }

    #[tokio::test]
    async fn test_dod_file_exists_met() {
        use crate::dsl::schema::DoneCriterion;

        // Create a temp file
        let temp_file = std::env::temp_dir().join("test_dod_file_exists.txt");
        std::fs::write(&temp_file, "test content").unwrap();

        let criterion = DoneCriterion::FileExists {
            path: temp_file.to_string_lossy().to_string(),
            description: "Test file must exist".to_string(),
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, None, &var_context).await;
        assert!(result.met);
        assert_eq!(result.description, "Test file must exist");

        // Cleanup
        std::fs::remove_file(temp_file).ok();
    }

    #[tokio::test]
    async fn test_dod_file_exists_not_met() {
        use crate::dsl::schema::DoneCriterion;

        let nonexistent_file = std::env::temp_dir().join("nonexistent_file_xyz.txt");
        let criterion = DoneCriterion::FileExists {
            path: nonexistent_file.to_string_lossy().to_string(),
            description: "Nonexistent file".to_string(),
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, None, &var_context).await;
        assert!(!result.met);
        assert!(result.details.contains("does not exist"));
    }

    #[tokio::test]
    async fn test_dod_file_contains_met() {
        use crate::dsl::schema::DoneCriterion;

        let temp_file = std::env::temp_dir().join("test_dod_file_contains.txt");
        std::fs::write(&temp_file, "Hello World\nTest Content").unwrap();

        let criterion = DoneCriterion::FileContains {
            path: temp_file.to_string_lossy().to_string(),
            pattern: "Hello World".to_string(),
            description: "File must contain greeting".to_string(),
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, None, &var_context).await;
        assert!(result.met);

        std::fs::remove_file(temp_file).ok();
    }

    #[tokio::test]
    async fn test_dod_file_contains_regex_pattern() {
        use crate::dsl::schema::DoneCriterion;

        let temp_file = std::env::temp_dir().join("test_dod_file_contains_regex.txt");
        std::fs::write(
            &temp_file,
            "group_list\ngroup_install\ngroup_update\ngroup_validate",
        )
        .unwrap();

        // Test regex pattern matching with .*
        let criterion = DoneCriterion::FileContains {
            path: temp_file.to_string_lossy().to_string(),
            pattern: "group.*list".to_string(),
            description: "File must contain group_list".to_string(),
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, None, &var_context).await;
        assert!(
            result.met,
            "Regex pattern 'group.*list' should match 'group_list'"
        );

        // Test another regex pattern
        let criterion2 = DoneCriterion::FileContains {
            path: temp_file.to_string_lossy().to_string(),
            pattern: "group.*(update|validate)".to_string(),
            description: "File must contain group_update or group_validate".to_string(),
        };

        let result2 = check_criterion(&criterion2, None, &var_context).await;
        assert!(
            result2.met,
            "Regex pattern 'group.*(update|validate)' should match"
        );

        std::fs::remove_file(temp_file).ok();
    }

    #[tokio::test]
    async fn test_dod_file_not_contains_met() {
        use crate::dsl::schema::DoneCriterion;

        let temp_file = std::env::temp_dir().join("test_dod_file_not_contains.txt");
        std::fs::write(&temp_file, "Clean code").unwrap();

        let criterion = DoneCriterion::FileNotContains {
            path: temp_file.to_string_lossy().to_string(),
            pattern: "TODO".to_string(),
            description: "No TODOs allowed".to_string(),
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, None, &var_context).await;
        assert!(result.met);

        std::fs::remove_file(temp_file).ok();
    }

    #[tokio::test]
    async fn test_dod_file_not_contains_failed() {
        use crate::dsl::schema::DoneCriterion;

        let temp_file = std::env::temp_dir().join("test_dod_file_not_contains_fail.txt");
        std::fs::write(&temp_file, "Code with TODO: fix this").unwrap();

        let criterion = DoneCriterion::FileNotContains {
            path: temp_file.to_string_lossy().to_string(),
            pattern: "TODO".to_string(),
            description: "No TODOs allowed".to_string(),
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, None, &var_context).await;
        assert!(!result.met);
        assert!(result.details.contains("should not"));

        std::fs::remove_file(temp_file).ok();
    }

    #[tokio::test]
    async fn test_dod_directory_exists() {
        use crate::dsl::schema::DoneCriterion;

        let temp_dir = std::env::temp_dir().join("test_dod_directory");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let criterion = DoneCriterion::DirectoryExists {
            path: temp_dir.to_string_lossy().to_string(),
            description: "Output directory must exist".to_string(),
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, None, &var_context).await;
        assert!(result.met);

        std::fs::remove_dir(temp_dir).ok();
    }

    #[tokio::test]
    async fn test_dod_command_succeeds() {
        use crate::dsl::schema::DoneCriterion;

        let criterion = DoneCriterion::CommandSucceeds {
            command: "echo".to_string(),
            args: vec!["test".to_string()],
            description: "Echo command should succeed".to_string(),
            working_dir: None,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, None, &var_context).await;
        assert!(result.met);
    }

    #[tokio::test]
    async fn test_dod_command_fails() {
        use crate::dsl::schema::DoneCriterion;

        let criterion = DoneCriterion::CommandSucceeds {
            command: "false".to_string(),
            args: vec![],
            description: "False command should fail".to_string(),
            working_dir: None,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, None, &var_context).await;
        assert!(!result.met);
        assert!(result.details.contains("failed"));
    }

    #[tokio::test]
    async fn test_dod_command_captures_output() {
        use crate::dsl::schema::DoneCriterion;

        // Use a shell command that writes to both stdout and stderr, then fails
        let criterion = DoneCriterion::CommandSucceeds {
            command: "sh".to_string(),
            args: vec![
                "-c".to_string(),
                "echo 'This is stdout output'; echo 'This is stderr output' >&2; exit 1"
                    .to_string(),
            ],
            description: "Command that outputs to stdout/stderr and fails".to_string(),
            working_dir: None,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, None, &var_context).await;

        // Verify command failed
        assert!(!result.met);

        // Verify stdout and stderr are captured in details
        assert!(result.details.contains("STDOUT"));
        assert!(result.details.contains("This is stdout output"));
        assert!(result.details.contains("STDERR"));
        assert!(result.details.contains("This is stderr output"));
    }

    #[tokio::test]
    async fn test_dod_output_matches() {
        use crate::dsl::schema::{DoneCriterion, OutputSource};

        let task_output = "Build succeeded\nAll tests passed";

        let criterion = DoneCriterion::OutputMatches {
            source: OutputSource::TaskOutput,
            pattern: "tests passed".to_string(),
            description: "Output must indicate tests passed".to_string(),
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let result = check_criterion(&criterion, Some(task_output), &var_context).await;
        assert!(result.met);
    }

    #[test]
    fn test_format_unmet_criteria() {
        use crate::dsl::schema::CriterionResult;

        let results = vec![
            CriterionResult {
                met: true,
                description: "File exists".to_string(),
                details: "File found".to_string(),
            },
            CriterionResult {
                met: false,
                description: "Tests must pass".to_string(),
                details: "Tests failed with 3 errors".to_string(),
            },
            CriterionResult {
                met: false,
                description: "No TODO comments".to_string(),
                details: "Found TODO in line 42".to_string(),
            },
        ];

        let feedback = format_unmet_criteria(&results);
        assert!(feedback.contains("DEFINITION OF DONE"));
        assert!(feedback.contains("Tests must pass"));
        assert!(feedback.contains("No TODO comments"));
        assert!(feedback.contains("✗ FAILED"));
        assert!(!feedback.contains("File exists")); // Met criteria not included
    }

    #[tokio::test]
    async fn test_check_definition_of_done_all_met() {
        use crate::dsl::schema::{DefinitionOfDone, DoneCriterion};

        let temp_file = std::env::temp_dir().join("test_dod_all_met.txt");
        std::fs::write(&temp_file, "Complete").unwrap();

        let temp_file_str = temp_file.to_string_lossy().to_string();
        let dod = DefinitionOfDone {
            criteria: vec![
                DoneCriterion::FileExists {
                    path: temp_file_str.clone(),
                    description: "File must exist".to_string(),
                },
                DoneCriterion::FileContains {
                    path: temp_file_str,
                    pattern: "Complete".to_string(),
                    description: "File must be complete".to_string(),
                },
            ],
            max_retries: 3,
            fail_on_unmet: true,
            auto_elevate_permissions: false,
        };

        let var_context = crate::dsl::variables::VariableContext::new();
        let results = check_definition_of_done(&dod, None, &var_context).await;
        assert_eq!(results.len(), 2);
        assert!(results.iter().all(|r| r.met));

        std::fs::remove_file(temp_file).ok();
    }

    #[tokio::test]
    async fn test_check_definition_of_done_some_unmet() {
        use crate::dsl::schema::{DefinitionOfDone, DoneCriterion};

        let existing_file = std::env::temp_dir().join("existing_file.txt");
        let nonexistent_file = std::env::temp_dir().join("nonexistent_xyz_abc.txt");

        let dod = DefinitionOfDone {
            criteria: vec![
                DoneCriterion::FileExists {
                    path: existing_file.to_string_lossy().to_string(),
                    description: "File must exist".to_string(),
                },
                DoneCriterion::FileExists {
                    path: nonexistent_file.to_string_lossy().to_string(),
                    description: "Another file must exist".to_string(),
                },
            ],
            max_retries: 2,
            fail_on_unmet: true,
            auto_elevate_permissions: false,
        };

        // Create one file but not the other
        std::fs::write(&existing_file, "test").unwrap();

        let var_context = crate::dsl::variables::VariableContext::new();
        let results = check_definition_of_done(&dod, None, &var_context).await;
        assert_eq!(results.len(), 2);
        assert!(results[0].met);
        assert!(!results[1].met);

        std::fs::remove_file(existing_file).ok();
    }
}