torc 0.21.0

Workflow management system
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
use crate::client::apis::{configuration::Configuration, default_api};
use crate::client::parameter_expansion::{
    ParameterValue, cartesian_product, parse_parameter_value, substitute_parameters, zip_parameters,
};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::Path;

use crate::models;
use regex::Regex;
use serde::{Deserialize, Serialize};

/// Result of validating a workflow specification (dry-run)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValidationResult {
    /// Whether the validation passed with no errors
    pub valid: bool,
    /// Validation errors that would prevent workflow creation
    pub errors: Vec<String>,
    /// Warnings that don't prevent creation but may indicate issues
    pub warnings: Vec<String>,
    /// Summary of what would be created
    pub summary: ValidationSummary,
}

/// Summary of workflow components that would be created
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValidationSummary {
    /// Name of the workflow
    pub workflow_name: String,
    /// Description of the workflow
    pub workflow_description: Option<String>,
    /// Number of jobs that would be created
    pub job_count: usize,
    /// Number of jobs before parameter expansion
    pub job_count_before_expansion: usize,
    /// Number of files that would be created
    pub file_count: usize,
    /// Number of files before parameter expansion
    pub file_count_before_expansion: usize,
    /// Number of user data records that would be created
    pub user_data_count: usize,
    /// Number of resource requirements that would be created
    pub resource_requirements_count: usize,
    /// Number of Slurm schedulers that would be created
    pub slurm_scheduler_count: usize,
    /// Number of workflow actions that would be created
    pub action_count: usize,
    /// Whether the workflow has on_workflow_start schedule_nodes action
    pub has_schedule_nodes_action: bool,
    /// List of job names that would be created
    pub job_names: Vec<String>,
    /// List of scheduler names
    pub scheduler_names: Vec<String>,
}

#[cfg(feature = "client")]
use kdl::{KdlDocument, KdlNode};

/// File specification for JSON serialization (without workflow_id and id)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileSpec {
    /// Name of the file
    pub name: String,
    /// Path to the file
    pub path: String,
    /// File modification time as Unix timestamp (seconds since epoch).
    /// If not specified, torc automatically checks if the file exists on disk
    /// during workflow creation and uses its actual modification time.
    /// This distinguishes input files (exist before workflow) from output files
    /// (created by jobs). Used by RO-Crate for automatic entity generation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub st_mtime: Option<f64>,
    /// Optional parameters for generating multiple files
    /// Supports range notation (e.g., "1:100" or "1:100:5") and lists (e.g., "[1,5,10]")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<HashMap<String, String>>,
    /// How to combine multiple parameters: "product" (default, Cartesian product) or "zip"
    /// With "zip", parameters are combined element-wise (all must have the same length)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameter_mode: Option<String>,
    /// Names of workflow-level parameters to use for this file
    /// If set, only these parameters from the workflow will be used
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_parameters: Option<Vec<String>>,
}

impl FileSpec {
    /// Create a new FileSpec with only required fields
    #[allow(dead_code)]
    pub fn new(name: String, path: String) -> FileSpec {
        FileSpec {
            name,
            path,
            st_mtime: None,
            parameters: None,
            parameter_mode: None,
            use_parameters: None,
        }
    }

    /// Expand this FileSpec into multiple FileSpecs based on its parameters
    /// Returns a single-element vec if no parameters are present
    pub fn expand(&self) -> Result<Vec<FileSpec>, String> {
        // If no parameters, return a clone
        let Some(ref params) = self.parameters else {
            return Ok(vec![self.clone()]);
        };

        // Parse all parameter values
        let mut parsed_params: HashMap<String, Vec<ParameterValue>> = HashMap::new();
        for (name, value) in params {
            let values = parse_parameter_value(value)?;
            parsed_params.insert(name.clone(), values);
        }

        // Generate combinations based on parameter_mode
        let mode = self.parameter_mode.as_deref().unwrap_or("product");
        let combinations = match mode {
            "zip" => zip_parameters(&parsed_params)?,
            _ => cartesian_product(&parsed_params),
        };

        // Create a FileSpec for each combination
        let mut expanded = Vec::new();
        for combo in combinations {
            let mut new_spec = self.clone();
            new_spec.parameters = None; // Remove parameters from expanded specs
            new_spec.parameter_mode = None; // Remove parameter_mode from expanded specs

            // Substitute parameters in name and path
            new_spec.name = substitute_parameters(&self.name, &combo);
            new_spec.path = substitute_parameters(&self.path, &combo);

            expanded.push(new_spec);
        }

        Ok(expanded)
    }
}

/// User data specification for JSON serialization (without workflow_id and id)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UserDataSpec {
    /// Whether the user data is ephemeral
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_ephemeral: Option<bool>,
    /// Name of the user data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The data content as JSON value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

/// Workflow action specification for defining conditional actions
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkflowActionSpec {
    /// Trigger type: on_workflow_start, on_workflow_complete, on_jobs_ready, on_jobs_complete
    pub trigger_type: String,
    /// Action type: run_commands, schedule_nodes
    pub action_type: String,
    /// For on_jobs_ready/on_jobs_complete: exact job names to match
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jobs: Option<Vec<String>>,
    /// For on_jobs_ready/on_jobs_complete: regex patterns to match job names
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job_name_regexes: Option<Vec<String>>,
    /// For run_commands action: array of commands to execute
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commands: Option<Vec<String>>,
    /// For schedule_nodes action: scheduler name (will be translated to scheduler_id)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduler: Option<String>,
    /// For schedule_nodes action: scheduler type (e.g., "slurm", "local")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduler_type: Option<String>,
    /// For schedule_nodes action: number of node allocations to request
    #[serde(skip_serializing_if = "Option::is_none")]
    pub num_allocations: Option<i64>,
    /// For schedule_nodes action: whether to start one worker per node
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_one_worker_per_node: Option<bool>,
    /// For schedule_nodes action: maximum parallel jobs
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_parallel_jobs: Option<i32>,
    /// Whether the action persists and can be claimed by multiple workers (default: false)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub persistent: Option<bool>,
}

/// Resource requirements specification for JSON serialization (without workflow_id and id)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResourceRequirementsSpec {
    /// Name of the resource requirements configuration
    pub name: String,
    /// Number of CPUs required
    pub num_cpus: i64,
    /// Number of GPUs required
    #[serde(default)]
    pub num_gpus: i64,
    /// Number of nodes required (defaults to 1)
    #[serde(default = "ResourceRequirementsSpec::default_num_nodes")]
    pub num_nodes: i64,
    /// Memory requirement
    pub memory: String,
    /// Runtime limit (defaults to 1 hour)
    #[serde(default = "ResourceRequirementsSpec::default_runtime")]
    pub runtime: String,
}

impl ResourceRequirementsSpec {
    fn default_num_nodes() -> i64 {
        1
    }

    fn default_runtime() -> String {
        "PT1H".to_string()
    }
}

/// A rule for handling specific exit codes in a failure handler
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FailureHandlerRuleSpec {
    /// Exit codes that trigger this rule. Can be omitted if match_all_exit_codes is true.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub exit_codes: Vec<i32>,
    /// If true, this rule matches any non-zero exit code.
    /// Use this for simple retry-on-any-failure behavior.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub match_all_exit_codes: bool,
    /// Optional recovery script to run before retrying
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recovery_script: Option<String>,
    /// Maximum number of retry attempts (defaults to 3)
    #[serde(default = "FailureHandlerRuleSpec::default_max_retries")]
    pub max_retries: i32,
}

impl FailureHandlerRuleSpec {
    fn default_max_retries() -> i32 {
        3
    }
}

/// Failure handler specification for JSON serialization (without workflow_id and id)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FailureHandlerSpec {
    /// Name of the failure handler
    pub name: String,
    /// Rules for handling different exit codes
    pub rules: Vec<FailureHandlerRuleSpec>,
}

/// Slurm scheduler specification for JSON serialization (without workflow_id and id)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SlurmSchedulerSpec {
    /// Name of the scheduler
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Slurm account
    pub account: String,
    /// Generic resources (GRES)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gres: Option<String>,
    /// Memory specification
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mem: Option<String>,
    /// Number of nodes (defaults to 1)
    #[serde(default = "SlurmSchedulerSpec::default_nodes")]
    pub nodes: i64,
    /// Number of tasks per node
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ntasks_per_node: Option<i64>,
    /// Partition name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub partition: Option<String>,
    /// Quality of service
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qos: Option<String>,
    /// Temporary storage
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tmp: Option<String>,
    /// Wall time limit (defaults to 1 hour)
    #[serde(default = "SlurmSchedulerSpec::default_walltime")]
    pub walltime: String,
    /// Extra parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extra: Option<String>,
}

impl SlurmSchedulerSpec {
    fn default_nodes() -> i64 {
        1
    }

    fn default_walltime() -> String {
        "01:00:00".to_string()
    }
}

/// Parameters that are managed by torc and cannot be set in slurm_defaults
/// Note: "account" is allowed in slurm_defaults as a workflow-level default
pub const SLURM_EXCLUDED_PARAMS: &[&str] = &[
    "partition",
    "nodes",
    "walltime",
    "time",
    "mem",
    "gres",
    "name",
    "job-name",
];

/// Default Slurm parameters to apply to all schedulers in a workflow
///
/// These parameters are applied at runtime to both user-defined and auto-generated
/// Slurm schedulers. Any valid sbatch parameter can be specified except for those
/// managed by torc: partition, nodes, walltime/time, mem, gres, name/job-name.
///
/// The "account" parameter is allowed and can be used as a workflow-level default.
///
/// Parameters should use the sbatch long option name (without the leading --).
/// For example: "qos", "constraint", "mail-user", "mail-type", "reservation", etc.
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SlurmDefaultsSpec(pub std::collections::HashMap<String, serde_json::Value>);

impl SlurmDefaultsSpec {
    /// Validate that no excluded parameters are present
    /// Returns an error listing all excluded parameters found
    pub fn validate(&self) -> Result<(), String> {
        let excluded_found: Vec<&str> = self
            .0
            .keys()
            .filter(|k| {
                let key_lower = k.to_lowercase();
                SLURM_EXCLUDED_PARAMS
                    .iter()
                    .any(|excluded| key_lower == *excluded)
            })
            .map(|k| k.as_str())
            .collect();

        if excluded_found.is_empty() {
            Ok(())
        } else {
            Err(format!(
                "slurm_defaults contains excluded parameters managed by torc: {}. \
                 These cannot be set as defaults.",
                excluded_found.join(", ")
            ))
        }
    }

    /// Convert all values to strings for use in config map
    ///
    /// Only string, number, and boolean values are supported. Arrays, objects, and null
    /// values are skipped with a warning since they cannot be meaningfully converted
    /// to Slurm parameter values.
    pub fn to_string_map(&self) -> std::collections::HashMap<String, String> {
        self.0
            .iter()
            .filter_map(|(k, v)| {
                let value_str = match v {
                    serde_json::Value::String(s) => Some(s.clone()),
                    serde_json::Value::Number(n) => Some(n.to_string()),
                    serde_json::Value::Bool(b) => Some(b.to_string()),
                    serde_json::Value::Array(_)
                    | serde_json::Value::Object(_)
                    | serde_json::Value::Null => {
                        log::warn!(
                            "Skipping slurm_defaults key '{}': unsupported value type (arrays, objects, and null are not valid Slurm parameter values)",
                            k
                        );
                        None
                    }
                };
                value_str.map(|v| (k.clone(), v))
            })
            .collect()
    }
}

/// Specification for a job within a workflow
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct JobSpec {
    /// Name of the job
    pub name: String,
    /// Command to execute for this job
    pub command: String,
    /// Optional script for job invocation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub invocation_script: Option<String>,
    /// Whether to cancel this job if a blocking job fails
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel_on_blocking_job_failure: Option<bool>,
    /// Whether this job supports termination
    #[serde(skip_serializing_if = "Option::is_none")]
    pub supports_termination: Option<bool>,
    /// Name of the resource requirements configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource_requirements: Option<String>,
    /// Name of the failure handler for this job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failure_handler: Option<String>,
    /// Names of jobs that must complete before this job can run (exact matches)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub depends_on: Option<Vec<String>>,
    /// Regex patterns for jobs that must complete before this job can run
    #[serde(skip_serializing_if = "Option::is_none")]
    pub depends_on_regexes: Option<Vec<String>>,
    /// Names of input files required by this job (exact matches)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_files: Option<Vec<String>>,
    /// Regex patterns for input files required by this job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_file_regexes: Option<Vec<String>>,
    /// Names of output files produced by this job (exact matches)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_files: Option<Vec<String>>,
    /// Regex patterns for output files produced by this job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_file_regexes: Option<Vec<String>>,
    /// Names of input user data required by this job (exact matches)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_user_data: Option<Vec<String>>,
    /// Regex patterns for input user data required by this job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_user_data_regexes: Option<Vec<String>>,
    /// Names of output data produced by this job (exact matches)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_user_data: Option<Vec<String>>,
    /// Regex patterns for output data produced by this job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_user_data_regexes: Option<Vec<String>>,
    /// Name of the scheduler to use for this job
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduler: Option<String>,
    /// Optional parameters for generating multiple jobs
    /// Supports range notation (e.g., "1:100" or "1:100:5") and lists (e.g., "[1,5,10]")
    /// Multiple parameters create a Cartesian product of jobs by default
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<HashMap<String, String>>,
    /// How to combine multiple parameters: "product" (default, Cartesian product) or "zip"
    /// With "zip", parameters are combined element-wise (all must have the same length)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameter_mode: Option<String>,
    /// Names of workflow-level parameters to use for this job
    /// If set, only these parameters from the workflow will be used
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_parameters: Option<Vec<String>>,
    /// Per-job override for stdout/stderr capture configuration.
    /// If set, overrides the workflow-level `execution_config.stdio` for this job.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stdio: Option<StdioConfig>,
}

impl JobSpec {
    /// Create a new JobSpec with only required fields
    #[allow(dead_code)]
    pub fn new(name: String, command: String) -> JobSpec {
        JobSpec {
            name,
            command,
            invocation_script: None,
            cancel_on_blocking_job_failure: Some(false),
            supports_termination: Some(false),
            resource_requirements: None,
            failure_handler: None,
            depends_on: None,
            depends_on_regexes: None,
            input_files: None,
            input_file_regexes: None,
            output_files: None,
            output_file_regexes: None,
            input_user_data: None,
            input_user_data_regexes: None,
            output_user_data: None,
            output_user_data_regexes: None,
            scheduler: None,
            parameters: None,
            parameter_mode: None,
            use_parameters: None,
            stdio: None,
        }
    }

    /// Expand this JobSpec into multiple JobSpecs based on its parameters
    /// Returns a single-element vec if no parameters are present
    pub fn expand(&self) -> Result<Vec<JobSpec>, String> {
        // If no parameters, return a clone
        let Some(ref params) = self.parameters else {
            return Ok(vec![self.clone()]);
        };

        // Parse all parameter values
        let mut parsed_params: HashMap<String, Vec<ParameterValue>> = HashMap::new();
        for (name, value) in params {
            let values = parse_parameter_value(value)?;
            parsed_params.insert(name.clone(), values);
        }

        // Generate combinations based on parameter_mode
        let mode = self.parameter_mode.as_deref().unwrap_or("product");
        let combinations = match mode {
            "zip" => zip_parameters(&parsed_params)?,
            _ => cartesian_product(&parsed_params),
        };

        // Create a JobSpec for each combination
        let mut expanded = Vec::new();
        for combo in combinations {
            let mut new_spec = self.clone();
            new_spec.parameters = None; // Remove parameters from expanded specs
            new_spec.parameter_mode = None; // Remove parameter_mode from expanded specs

            // Substitute parameters in all string fields
            new_spec.name = substitute_parameters(&self.name, &combo);
            new_spec.command = substitute_parameters(&self.command, &combo);

            if let Some(ref script) = self.invocation_script {
                new_spec.invocation_script = Some(substitute_parameters(script, &combo));
            }

            if let Some(ref rr_name) = self.resource_requirements {
                new_spec.resource_requirements = Some(substitute_parameters(rr_name, &combo));
            }

            if let Some(ref sched_name) = self.scheduler {
                new_spec.scheduler = Some(substitute_parameters(sched_name, &combo));
            }

            // Substitute parameters in name vectors
            if let Some(ref names) = self.depends_on {
                new_spec.depends_on = Some(
                    names
                        .iter()
                        .map(|n| substitute_parameters(n, &combo))
                        .collect(),
                );
            }

            if let Some(ref names) = self.input_files {
                new_spec.input_files = Some(
                    names
                        .iter()
                        .map(|n| substitute_parameters(n, &combo))
                        .collect(),
                );
            }

            if let Some(ref names) = self.output_files {
                new_spec.output_files = Some(
                    names
                        .iter()
                        .map(|n| substitute_parameters(n, &combo))
                        .collect(),
                );
            }

            if let Some(ref names) = self.input_user_data {
                new_spec.input_user_data = Some(
                    names
                        .iter()
                        .map(|n| substitute_parameters(n, &combo))
                        .collect(),
                );
            }

            if let Some(ref names) = self.output_user_data {
                new_spec.output_user_data = Some(
                    names
                        .iter()
                        .map(|n| substitute_parameters(n, &combo))
                        .collect(),
                );
            }

            // Substitute parameters in regex pattern vectors
            if let Some(ref regexes) = self.depends_on_regexes {
                new_spec.depends_on_regexes = Some(
                    regexes
                        .iter()
                        .map(|r| substitute_parameters(r, &combo))
                        .collect(),
                );
            }

            if let Some(ref regexes) = self.input_file_regexes {
                new_spec.input_file_regexes = Some(
                    regexes
                        .iter()
                        .map(|r| substitute_parameters(r, &combo))
                        .collect(),
                );
            }

            if let Some(ref regexes) = self.output_file_regexes {
                new_spec.output_file_regexes = Some(
                    regexes
                        .iter()
                        .map(|r| substitute_parameters(r, &combo))
                        .collect(),
                );
            }

            if let Some(ref regexes) = self.input_user_data_regexes {
                new_spec.input_user_data_regexes = Some(
                    regexes
                        .iter()
                        .map(|r| substitute_parameters(r, &combo))
                        .collect(),
                );
            }

            if let Some(ref regexes) = self.output_user_data_regexes {
                new_spec.output_user_data_regexes = Some(
                    regexes
                        .iter()
                        .map(|r| substitute_parameters(r, &combo))
                        .collect(),
                );
            }

            expanded.push(new_spec);
        }

        Ok(expanded)
    }
}

/// How to capture stdout and stderr for job processes.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum StdioMode {
    /// Separate stdout and stderr files (.o and .e) — the default.
    #[default]
    Separate,
    /// Combine stdout and stderr into a single file (.log) per job.
    Combined,
    /// Don't capture stdout (send to /dev/null); capture stderr only.
    NoStdout,
    /// Don't capture stderr (send to /dev/null); capture stdout only.
    NoStderr,
    /// Don't capture either stdout or stderr.
    None,
    // Future: CombinedPerNode — all jobs on a node share one chronological file,
    // each line tagged with the job ID.
}

/// Configuration for job stdout/stderr capture.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct StdioConfig {
    /// How to capture stdout/stderr. Default: separate files.
    #[serde(default)]
    pub mode: StdioMode,
    /// Delete stdout/stderr files if the job completes successfully.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delete_on_success: Option<bool>,
}

/// Execution mode for job processes.
///
/// Controls how torc manages job processes during execution, particularly
/// around termination and resource enforcement.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ExecutionMode {
    /// Direct shell execution - torc manages termination via SIGTERM/SIGKILL.
    /// Use when srun/sacct are unreliable or running outside Slurm.
    Direct,
    /// Slurm srun execution - Slurm manages resource limits and termination.
    /// Jobs are wrapped with `srun` inside Slurm allocations.
    Slurm,
    /// Auto-detect based on environment - uses `slurm` if SLURM_JOB_ID is set,
    /// otherwise `direct`. This is the default behavior.
    #[default]
    Auto,
}

/// Unified execution configuration that controls how jobs are run.
///
/// This replaces the old `SlurmConfig` with a mode-based approach that clearly
/// distinguishes between direct execution (torc manages everything) and Slurm
/// execution (srun manages resources and termination).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ExecutionConfig {
    /// Execution mode: direct, slurm, or auto (default).
    #[serde(default)]
    pub mode: ExecutionMode,

    // ========== Shared settings (both modes) ==========
    /// Seconds before end_time to send SIGKILL (direct mode) or set srun --time (slurm mode).
    /// Default: 60.
    /// - Direct mode: After this time, any remaining jobs are force-killed with SIGKILL.
    /// - Slurm mode: srun --time is set to (remaining_time - sigkill_headroom_seconds) so
    ///   Slurm kills the step before the allocation expires, giving the job runner time
    ///   to detect the timeout and report results.
    ///
    /// If `srun_termination_signal` is set (e.g., "TERM@120"), ensure its time value
    /// (120 seconds) is less than `sigkill_headroom_seconds` so the signal is sent
    /// before Slurm kills the step.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sigkill_headroom_seconds: Option<i64>,

    /// Exit code to use when a job times out.
    /// Default: 152 (matches Slurm's TIMEOUT exit code).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_exit_code: Option<i32>,

    /// Enable staggered startup for job runners to mitigate thundering herd.
    /// When true (default), each runner sleeps a deterministic jitter before
    /// contacting the server, spreading load when many nodes start at once.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub staggered_start: Option<bool>,

    // ========== Direct mode only ==========
    /// When true (default), monitor memory/CPU usage and kill jobs that exceed
    /// their resource requirements (OOM enforcement). Only applies in direct mode.
    /// Setting this to false with slurm mode is an error — use direct mode instead.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_resources: Option<bool>,

    /// Signal to send before SIGKILL for graceful termination (direct mode only).
    /// Default: "SIGTERM". Other common values: "SIGINT", "SIGUSR1".
    /// In slurm mode, use `srun_termination_signal` instead.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub termination_signal: Option<String>,

    /// Seconds before SIGKILL to send the termination signal (direct mode only).
    /// Default: 30. This gives jobs time to handle the signal gracefully.
    /// In slurm mode, termination timing is controlled by `srun_termination_signal`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sigterm_lead_seconds: Option<i64>,

    /// Exit code to use when a job is OOM-killed (direct mode only).
    /// Default: 137 (128 + SIGKILL = 128 + 9).
    /// In slurm mode, Slurm manages OOM detection.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oom_exit_code: Option<i32>,

    // ========== Slurm mode only ==========
    /// Signal specification for srun steps, passed as `srun --signal=<value>` (slurm mode only).
    /// Format: `<signal>@<seconds>` (e.g., `TERM@120` sends SIGTERM 120 seconds
    /// before the step time limit).
    /// In direct mode, use `termination_signal` instead.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub srun_termination_signal: Option<String>,

    /// When true, allow Slurm to bind tasks to specific CPU cores (slurm mode only).
    /// By default (false), srun passes `--cpu-bind=none` to disable binding.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_cpu_bind: Option<bool>,

    // ========== Stdio settings ==========
    /// Workflow-level default for stdout/stderr capture.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stdio: Option<StdioConfig>,

    /// Per-job stdio overrides keyed by job name.
    /// Populated during workflow creation from per-job `stdio` fields in the spec.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job_stdio_overrides: Option<HashMap<String, StdioConfig>>,
}

impl ExecutionConfig {
    /// Default value for sigterm_lead_seconds (30 seconds)
    pub const DEFAULT_SIGTERM_LEAD_SECONDS: i64 = 30;
    /// Default value for sigkill_headroom_seconds (60 seconds)
    pub const DEFAULT_SIGKILL_HEADROOM_SECONDS: i64 = 60;
    /// Default exit code for timeout (matches Slurm's TIMEOUT)
    pub const DEFAULT_TIMEOUT_EXIT_CODE: i32 = 152;
    /// Default exit code for OOM kill (128 + SIGKILL)
    pub const DEFAULT_OOM_EXIT_CODE: i32 = 137;

    /// Resolve the effective execution mode based on the configured mode and environment.
    /// - Direct -> Direct
    /// - Slurm -> Slurm
    /// - Auto -> Slurm if SLURM_JOB_ID is set, else Direct
    pub fn effective_mode(&self) -> ExecutionMode {
        match self.mode {
            ExecutionMode::Direct => ExecutionMode::Direct,
            ExecutionMode::Slurm => ExecutionMode::Slurm,
            ExecutionMode::Auto => {
                if std::env::var("SLURM_JOB_ID").is_ok() {
                    ExecutionMode::Slurm
                } else {
                    ExecutionMode::Direct
                }
            }
        }
    }

    /// Whether to use srun wrapping (true for effective Slurm mode).
    pub fn use_srun(&self) -> bool {
        matches!(self.effective_mode(), ExecutionMode::Slurm)
    }

    /// Whether to enforce resource limits.
    pub fn limit_resources(&self) -> bool {
        self.limit_resources.unwrap_or(true)
    }

    /// Whether to enable CPU binding in Slurm mode.
    pub fn enable_cpu_bind(&self) -> bool {
        self.enable_cpu_bind.unwrap_or(false)
    }

    /// Get the termination signal name for direct mode.
    pub fn termination_signal(&self) -> &str {
        self.termination_signal.as_deref().unwrap_or("SIGTERM")
    }

    /// Get the sigterm lead time in seconds.
    pub fn sigterm_lead_seconds(&self) -> i64 {
        self.sigterm_lead_seconds
            .unwrap_or(Self::DEFAULT_SIGTERM_LEAD_SECONDS)
    }

    /// Get the sigkill headroom time in seconds.
    pub fn sigkill_headroom_seconds(&self) -> i64 {
        self.sigkill_headroom_seconds
            .unwrap_or(Self::DEFAULT_SIGKILL_HEADROOM_SECONDS)
    }

    /// Get the timeout exit code.
    pub fn timeout_exit_code(&self) -> i32 {
        self.timeout_exit_code
            .unwrap_or(Self::DEFAULT_TIMEOUT_EXIT_CODE)
    }

    /// Get the OOM exit code.
    pub fn oom_exit_code(&self) -> i32 {
        self.oom_exit_code.unwrap_or(Self::DEFAULT_OOM_EXIT_CODE)
    }

    /// Whether staggered startup is enabled for Slurm job runners.
    pub fn staggered_start(&self) -> bool {
        self.staggered_start.unwrap_or(true)
    }

    /// Resolve the effective `StdioConfig` for a job, checking per-job overrides first.
    pub fn stdio_for_job(&self, job_name: &str) -> StdioConfig {
        if let Some(ref overrides) = self.job_stdio_overrides
            && let Some(cfg) = overrides.get(job_name)
        {
            return cfg.clone();
        }
        self.stdio.clone().unwrap_or_default()
    }

    /// Whether to delete stdio files on successful completion for a job.
    pub fn delete_stdio_on_success(&self, job_name: &str) -> bool {
        self.stdio_for_job(job_name)
            .delete_on_success
            .unwrap_or(false)
    }

    /// Validate the configuration, returning any warnings.
    ///
    /// Returns a list of warning messages for potential issues:
    /// - If `srun_termination_signal` time value is >= `sigkill_headroom_seconds`,
    ///   the signal won't be sent before Slurm kills the step.
    pub fn validate(&self) -> Vec<String> {
        let mut warnings = Vec::new();

        // Check srun_termination_signal vs sigkill_headroom_seconds
        if let Some(ref signal_spec) = self.srun_termination_signal
            && let Some(signal_seconds) = Self::parse_srun_signal_seconds(signal_spec)
        {
            let headroom = self.sigkill_headroom_seconds();
            if signal_seconds >= headroom {
                warnings.push(format!(
                    "srun_termination_signal '{}' specifies {}s, which is >= sigkill_headroom_seconds ({}s). \
                     The signal will not be sent before Slurm kills the step. \
                     Consider increasing sigkill_headroom_seconds or reducing the signal time.",
                    signal_spec, signal_seconds, headroom
                ));
            }
        }

        warnings
    }

    /// Parse the seconds value from an srun --signal spec like "TERM@120".
    /// Returns None if the spec doesn't contain a valid time value.
    fn parse_srun_signal_seconds(signal_spec: &str) -> Option<i64> {
        // Format: "<signal>@<seconds>" or just "<signal>"
        if let Some(at_pos) = signal_spec.find('@') {
            let seconds_str = &signal_spec[at_pos + 1..];
            seconds_str.parse::<i64>().ok()
        } else {
            None
        }
    }

    /// Build from a WorkflowModel's execution_config or legacy slurm_config JSON blob.
    ///
    /// Checks execution_config first; falls back to slurm_config for old workflows.
    pub fn from_workflow_model(workflow: &models::WorkflowModel) -> ExecutionConfig {
        if let Some(ref json_str) = workflow.execution_config {
            serde_json::from_str(json_str).unwrap_or_default()
        } else if let Some(ref json_str) = workflow.slurm_config {
            // Fall back to legacy slurm_config for old workflows
            Self::from_legacy_slurm_config_json(json_str)
        } else {
            ExecutionConfig::default()
        }
    }

    /// Convert a legacy slurm_config JSON blob to ExecutionConfig for backward compatibility.
    ///
    /// This handles workflows created before ExecutionConfig was introduced.
    fn from_legacy_slurm_config_json(json_str: &str) -> ExecutionConfig {
        // Legacy slurm_config format:
        // { "limit_resources": bool, "use_srun": bool, "srun_termination_signal": str, "enable_cpu_bind": bool }
        #[derive(Deserialize, Default)]
        struct LegacySlurmConfig {
            limit_resources: Option<bool>,
            use_srun: Option<bool>,
            srun_termination_signal: Option<String>,
            enable_cpu_bind: Option<bool>,
        }

        let legacy: LegacySlurmConfig = serde_json::from_str(json_str).unwrap_or_default();
        ExecutionConfig {
            // use_srun=true means Slurm mode, use_srun=false means Direct mode
            // If not set, default to Auto for backward compatibility
            mode: match legacy.use_srun {
                Some(true) => ExecutionMode::Slurm,
                Some(false) => ExecutionMode::Direct,
                None => ExecutionMode::Auto,
            },
            limit_resources: legacy.limit_resources,
            srun_termination_signal: legacy.srun_termination_signal,
            enable_cpu_bind: legacy.enable_cpu_bind,
            // Direct mode settings use defaults when converting from legacy
            termination_signal: None,
            sigterm_lead_seconds: None,
            sigkill_headroom_seconds: None,
            timeout_exit_code: None,
            oom_exit_code: None,
            staggered_start: None,
            stdio: None,
            job_stdio_overrides: None,
        }
    }
}

/// Specification for a complete workflow
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkflowSpec {
    /// Name of the workflow
    pub name: String,
    /// User who owns this workflow (optional - will default to current user)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    /// Description of the workflow (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Shared parameters that can be used by jobs and files
    /// Jobs/files can reference these by setting use_parameters to parameter names
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<HashMap<String, String>>,
    /// Inform all compute nodes to shut down this number of seconds before the expiration time
    /// Deprecated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compute_node_expiration_buffer_seconds: Option<i64>,
    /// Inform all compute nodes to wait for new jobs for this time period before exiting
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compute_node_wait_for_new_jobs_seconds: Option<i64>,
    /// Inform all compute nodes to ignore workflow completions and hold onto allocations indefinitely
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compute_node_ignore_workflow_completion: Option<bool>,
    /// Inform all compute nodes to wait this number of minutes if the database becomes unresponsive
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compute_node_wait_for_healthy_database_minutes: Option<i64>,
    /// Method for sorting jobs when claiming them from the server
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jobs_sort_method: Option<models::ClaimJobsSortMethod>,
    /// Jobs that make up this workflow
    pub jobs: Vec<JobSpec>,
    /// Files associated with this workflow
    #[serde(skip_serializing_if = "Option::is_none")]
    pub files: Option<Vec<FileSpec>>,
    /// User data associated with this workflow
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_data: Option<Vec<UserDataSpec>>,
    /// Resource requirements available for this workflow
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource_requirements: Option<Vec<ResourceRequirementsSpec>>,
    /// Failure handlers available for this workflow
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failure_handlers: Option<Vec<FailureHandlerSpec>>,
    /// Slurm schedulers available for this workflow
    #[serde(skip_serializing_if = "Option::is_none")]
    pub slurm_schedulers: Option<Vec<SlurmSchedulerSpec>>,
    /// Default Slurm parameters to apply to all schedulers
    #[serde(skip_serializing_if = "Option::is_none")]
    pub slurm_defaults: Option<SlurmDefaultsSpec>,
    /// Resource monitoring configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource_monitor: Option<crate::client::resource_monitor::ResourceMonitorConfig>,
    /// Actions to execute based on workflow/job state transitions
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actions: Option<Vec<WorkflowActionSpec>>,
    /// Use PendingFailed status for failed jobs (enables AI-assisted recovery)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_pending_failed: Option<bool>,
    /// When true, automatically create RO-Crate entities for workflow files.
    /// Input files get entities during initialization; output files get entities on job completion.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_ro_crate: Option<bool>,
    /// Project name or identifier for grouping workflows
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    /// Arbitrary metadata as JSON string
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<String>,
    /// Unified execution configuration controlling how jobs are run.
    /// Controls execution mode (direct, slurm, or auto) and related settings like
    /// resource limits, termination signals, and timeouts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_config: Option<ExecutionConfig>,
}

impl WorkflowSpec {
    /// Create a new WorkflowSpec with required fields
    #[allow(dead_code)]
    pub fn new(
        name: String,
        user: String,
        description: Option<String>,
        jobs: Vec<JobSpec>,
    ) -> WorkflowSpec {
        WorkflowSpec {
            name,
            user: Some(user),
            description,
            parameters: None,
            compute_node_expiration_buffer_seconds: None,
            compute_node_wait_for_new_jobs_seconds: None,
            compute_node_ignore_workflow_completion: None,
            compute_node_wait_for_healthy_database_minutes: None,
            jobs_sort_method: None,
            jobs,
            files: None,
            user_data: None,
            resource_requirements: None,
            failure_handlers: None,
            slurm_schedulers: None,
            slurm_defaults: None,
            resource_monitor: None,
            actions: None,
            use_pending_failed: None,
            enable_ro_crate: None,
            project: None,
            metadata: None,
            execution_config: None,
        }
    }

    /// Deserialize a WorkflowSpec from a serde_json::Value
    /// This is the common conversion point for all file formats
    pub fn from_json_value(value: serde_json::Value) -> Result<Self, Box<dyn std::error::Error>> {
        // Check for removed fields and provide helpful migration guidance
        // before serde's deny_unknown_fields produces a generic error.
        if let serde_json::Value::Object(ref map) = value
            && map.contains_key("slurm_config")
        {
            return Err(
                "The 'slurm_config' field has been removed from the workflow spec. \
                 Use 'execution_config' instead.\n\
                 See docs: docs/src/core/reference/workflow-spec.md \
                 and docs/src/core/concepts/execution-modes.md"
                    .into(),
            );
        }
        Ok(serde_json::from_value(value)?)
    }

    /// Expand all parameterized jobs and files in this workflow spec
    /// This modifies the spec in-place, replacing parameterized specs with their expanded versions
    ///
    /// Parameter resolution order:
    /// 1. If job/file has its own `parameters`, use those (local params override workflow params)
    /// 2. If job/file has `use_parameters`, select only those from workflow-level params
    pub fn expand_parameters(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        let workflow_params = self.parameters.clone();

        // Expand all jobs
        let mut expanded_jobs = Vec::new();
        for job in &self.jobs {
            // Resolve parameters for this job
            let mut job_with_params = job.clone();
            job_with_params.parameters =
                Self::resolve_parameters(&job.parameters, &job.use_parameters, &workflow_params);
            // Clear use_parameters after resolution
            job_with_params.use_parameters = None;

            let expanded = job_with_params
                .expand()
                .map_err(|e| format!("Failed to expand job '{}': {}", job.name, e))?;
            expanded_jobs.extend(expanded);
        }
        self.jobs = expanded_jobs;

        // Expand all files
        if let Some(ref files) = self.files {
            let mut expanded_files = Vec::new();
            for file in files {
                // Resolve parameters for this file
                let mut file_with_params = file.clone();
                file_with_params.parameters = Self::resolve_parameters(
                    &file.parameters,
                    &file.use_parameters,
                    &workflow_params,
                );
                // Clear use_parameters after resolution
                file_with_params.use_parameters = None;

                let expanded = file_with_params
                    .expand()
                    .map_err(|e| format!("Failed to expand file '{}': {}", file.name, e))?;
                expanded_files.extend(expanded);
            }
            self.files = Some(expanded_files);
        }

        Ok(())
    }

    /// Resolve parameters for a job or file
    ///
    /// Returns the effective parameters based on:
    /// 1. If local_params is set, return it (local overrides workflow)
    /// 2. If use_params is set, filter workflow_params to only those names
    /// 3. If neither is set, return None (job/file is not parameterized)
    fn resolve_parameters(
        local_params: &Option<HashMap<String, String>>,
        use_params: &Option<Vec<String>>,
        workflow_params: &Option<HashMap<String, String>>,
    ) -> Option<HashMap<String, String>> {
        // If local parameters are defined, use them (they take precedence)
        if local_params.is_some() {
            return local_params.clone();
        }

        // If no use_parameters specified, don't inherit workflow parameters
        // Jobs must explicitly opt-in via use_parameters
        let Some(param_names) = use_params else {
            return None;
        };

        // If no workflow parameters, nothing to inherit
        let Some(wf_params) = workflow_params else {
            return None;
        };

        // Filter workflow parameters to only those specified in use_parameters
        let mut filtered = HashMap::new();
        for name in param_names {
            if let Some(value) = wf_params.get(name) {
                filtered.insert(name.clone(), value.clone());
            }
            // Silently ignore parameters that don't exist in workflow
            // (could add validation here if desired)
        }
        if filtered.is_empty() {
            None
        } else {
            Some(filtered)
        }
    }

    /// Validate workflow actions
    pub fn validate_actions(&self) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(ref actions) = self.actions {
            for action in actions {
                // Validate schedule_nodes actions
                if action.action_type == "schedule_nodes" {
                    // Ensure scheduler_type is provided
                    let scheduler_type = action
                        .scheduler_type
                        .as_ref()
                        .ok_or("schedule_nodes action requires scheduler_type")?;

                    // Ensure scheduler is provided
                    let scheduler = action
                        .scheduler
                        .as_ref()
                        .ok_or("schedule_nodes action requires scheduler")?;

                    // If scheduler_type is slurm, verify that a slurm_scheduler with that name exists
                    if scheduler_type == "slurm" {
                        let slurm_schedulers = self
                            .slurm_schedulers
                            .as_ref()
                            .ok_or("schedule_nodes action with scheduler_type=slurm requires slurm_schedulers to be defined")?;

                        let scheduler_exists = slurm_schedulers
                            .iter()
                            .any(|s| s.name.as_ref() == Some(scheduler));

                        if !scheduler_exists {
                            return Err(format!(
                                "schedule_nodes action references slurm_scheduler '{}' which does not exist",
                                scheduler
                            )
                            .into());
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Validate that multi-node schedulers are properly utilized.
    ///
    /// This validation ensures that when a scheduler allocates multiple nodes (nodes > 1),
    /// jobs using it have consistent node requirements. Both patterns are valid:
    ///
    /// 1. **Single-node jobs in a multi-node allocation** — a single worker tracks
    ///    per-node resources and places each job step on a specific node via
    ///    `srun --nodelist=<node> --exact` (job `num_nodes=1` or unset).
    /// 2. **True multi-node jobs** — jobs span the full allocation (job `num_nodes` matches
    ///    scheduler `nodes`).
    ///
    /// The validation rejects the case where jobs request a different multi-node count
    /// than the scheduler provides (e.g., scheduler allocates 4 nodes but jobs request 2).
    pub fn validate_scheduler_node_requirements(&self) -> Result<(), Box<dyn std::error::Error>> {
        // Build lookup maps for resource requirements and schedulers
        let resource_req_map: HashMap<&str, &ResourceRequirementsSpec> = self
            .resource_requirements
            .as_ref()
            .map(|reqs| reqs.iter().map(|r| (r.name.as_str(), r)).collect())
            .unwrap_or_default();

        let scheduler_map: HashMap<&str, &SlurmSchedulerSpec> = self
            .slurm_schedulers
            .as_ref()
            .map(|schedulers| {
                schedulers
                    .iter()
                    .filter_map(|s| s.name.as_ref().map(|n| (n.as_str(), s)))
                    .collect()
            })
            .unwrap_or_default();

        // If no schedulers or no actions, skip validation
        if scheduler_map.is_empty() {
            return Ok(());
        }

        let actions = match &self.actions {
            Some(actions) => actions,
            None => return Ok(()),
        };

        let mut errors: Vec<String> = Vec::new();

        // Check each schedule_nodes action
        for action in actions {
            if action.action_type != "schedule_nodes" {
                continue;
            }

            // Get scheduler name from action
            let scheduler_name = match &action.scheduler {
                Some(name) => name,
                None => continue, // Validation of required fields is done elsewhere
            };

            // Only validate slurm schedulers
            let scheduler_type = action.scheduler_type.as_deref().unwrap_or("");
            if scheduler_type != "slurm" {
                continue;
            }

            // Get the scheduler spec
            let scheduler = match scheduler_map.get(scheduler_name.as_str()) {
                Some(s) => s,
                None => continue, // Missing scheduler is validated elsewhere
            };

            // If scheduler only allocates 1 node, no special validation needed
            if scheduler.nodes <= 1 {
                continue;
            }

            // Find jobs that reference this scheduler
            let jobs_using_scheduler: Vec<&JobSpec> = self
                .jobs
                .iter()
                .filter(|job| job.scheduler.as_ref() == Some(scheduler_name))
                .collect();

            // If no jobs explicitly reference this scheduler, skip
            if jobs_using_scheduler.is_empty() {
                continue;
            }

            // Check for mismatched multi-node requirements: reject jobs that request
            // a different multi-node count than the scheduler provides.
            // Single-node jobs (num_nodes=1 or unset) are always valid in any allocation.
            let mismatched_jobs: Vec<&str> = jobs_using_scheduler
                .iter()
                .filter(|job| {
                    let job_num_nodes = job
                        .resource_requirements
                        .as_ref()
                        .and_then(|name| resource_req_map.get(name.as_str()))
                        .map(|req| req.num_nodes)
                        .unwrap_or(1);
                    // Mismatch: job wants >1 node but not the same count as scheduler
                    job_num_nodes > 1 && job_num_nodes != scheduler.nodes
                })
                .map(|j| j.name.as_str())
                .collect();

            if !mismatched_jobs.is_empty() {
                errors.push(format!(
                    "Scheduler '{}' allocates {} nodes but jobs ({}) request a different \
                     multi-node count in their resource requirements. Set num_nodes={} \
                     on job resource requirements to match the scheduler, or use \
                     num_nodes=1 for single-node jobs.",
                    scheduler_name,
                    scheduler.nodes,
                    mismatched_jobs.join(", "),
                    scheduler.nodes,
                ));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(format!(
                "Scheduler node validation failed:\n  - {}",
                errors.join("\n  - ")
            )
            .into())
        }
    }

    /// Check if the workflow spec has an on_workflow_start action with schedule_nodes
    /// Returns true if such an action exists, false otherwise
    pub fn has_schedule_nodes_action(&self) -> bool {
        if let Some(ref actions) = self.actions {
            actions.iter().any(|action| {
                action.trigger_type == "on_workflow_start" && action.action_type == "schedule_nodes"
            })
        } else {
            false
        }
    }

    /// Validate a workflow specification without creating anything (dry-run mode)
    ///
    /// This method performs all validation steps that would occur during `create_workflow_from_spec`
    /// but without actually creating the workflow. It returns a detailed validation result including:
    /// - Whether validation passed
    /// - Any errors that would prevent creation
    /// - Any warnings about potential issues
    /// - A summary of what would be created (job count, file count, etc.)
    ///
    /// # Arguments
    /// * `path` - Path to the workflow specification file
    ///
    /// # Returns
    /// A `ValidationResult` containing validation status and summary
    pub fn validate_spec<P: AsRef<Path>>(path: P) -> ValidationResult {
        let mut errors = Vec::new();
        let mut warnings = Vec::new();

        // Step 1: Try to parse the spec file
        let mut spec = match Self::from_spec_file(&path) {
            Ok(spec) => spec,
            Err(e) => {
                return ValidationResult {
                    valid: false,
                    errors: vec![format!("Failed to parse specification file: {}", e)],
                    warnings: vec![],
                    summary: ValidationSummary {
                        workflow_name: String::new(),
                        workflow_description: None,
                        job_count: 0,
                        job_count_before_expansion: 0,
                        file_count: 0,
                        file_count_before_expansion: 0,
                        user_data_count: 0,
                        resource_requirements_count: 0,
                        slurm_scheduler_count: 0,
                        action_count: 0,
                        has_schedule_nodes_action: false,
                        job_names: vec![],
                        scheduler_names: vec![],
                    },
                };
            }
        };

        // Capture counts before expansion
        let job_count_before_expansion = spec.jobs.len();
        let file_count_before_expansion = spec.files.as_ref().map(|f| f.len()).unwrap_or(0);

        // Step 2: Expand parameters
        if let Err(e) = spec.expand_parameters() {
            errors.push(format!("Parameter expansion failed: {}", e));
        }

        // Step 3: Validate actions (basic structure validation)
        if let Err(e) = spec.validate_actions() {
            errors.push(format!("Action validation failed: {}", e));
        }

        // Step 4: Validate scheduler node requirements
        // This is an error by default (same as create_workflow_from_spec with skip_checks=false)
        if let Err(e) = spec.validate_scheduler_node_requirements() {
            errors.push(format!("{}", e));
        }

        // Step 5: Validate variable substitution
        if let Err(e) = spec.substitute_variables() {
            errors.push(format!("Variable substitution failed: {}", e));
        }

        // Step 6: Check for duplicate names
        // Check duplicate job names
        let mut job_names_set = HashSet::new();
        for job in &spec.jobs {
            if !job_names_set.insert(job.name.clone()) {
                errors.push(format!("Duplicate job name: '{}'", job.name));
            }
        }

        // Check duplicate file names
        if let Some(ref files) = spec.files {
            let mut file_names_set = HashSet::new();
            for file in files {
                if !file_names_set.insert(file.name.clone()) {
                    errors.push(format!("Duplicate file name: '{}'", file.name));
                }
            }
        }

        // Check duplicate user_data names
        if let Some(ref user_data_list) = spec.user_data {
            let mut user_data_names_set = HashSet::new();
            for ud in user_data_list {
                if let Some(ref name) = ud.name
                    && !user_data_names_set.insert(name.clone())
                {
                    errors.push(format!("Duplicate user_data name: '{}'", name));
                }
            }
        }

        // Check duplicate resource_requirements names
        if let Some(ref resource_reqs) = spec.resource_requirements {
            let mut rr_names_set = HashSet::new();
            for rr in resource_reqs {
                if !rr_names_set.insert(rr.name.clone()) {
                    errors.push(format!(
                        "Duplicate resource_requirements name: '{}'",
                        rr.name
                    ));
                }
            }
        }

        // Check duplicate slurm_scheduler names
        if let Some(ref schedulers) = spec.slurm_schedulers {
            let mut scheduler_names_set = HashSet::new();
            for sched in schedulers {
                if let Some(ref name) = sched.name
                    && !scheduler_names_set.insert(name.clone())
                {
                    errors.push(format!("Duplicate slurm_scheduler name: '{}'", name));
                }
            }
        }

        // Step 7: Build lookup sets for reference validation
        let job_names: HashSet<String> = spec.jobs.iter().map(|j| j.name.clone()).collect();
        let file_names: HashSet<String> = spec
            .files
            .as_ref()
            .map(|files| files.iter().map(|f| f.name.clone()).collect())
            .unwrap_or_default();
        let user_data_names: HashSet<String> = spec
            .user_data
            .as_ref()
            .map(|uds| uds.iter().filter_map(|ud| ud.name.clone()).collect())
            .unwrap_or_default();
        let resource_req_names: HashSet<String> = spec
            .resource_requirements
            .as_ref()
            .map(|rrs| rrs.iter().map(|rr| rr.name.clone()).collect())
            .unwrap_or_default();
        let scheduler_names_set: HashSet<String> = spec
            .slurm_schedulers
            .as_ref()
            .map(|scheds| scheds.iter().filter_map(|s| s.name.clone()).collect())
            .unwrap_or_default();

        // Step 8: Validate job references and build dependency graph
        let mut dependencies: HashMap<String, Vec<String>> = HashMap::new();

        for job in &spec.jobs {
            let mut job_deps = Vec::new();

            // Validate depends_on references
            if let Some(ref deps) = job.depends_on {
                for dep_name in deps {
                    if !job_names.contains(dep_name) {
                        errors.push(format!(
                            "Job '{}' depends_on non-existent job '{}'",
                            job.name, dep_name
                        ));
                    } else {
                        job_deps.push(dep_name.clone());
                    }
                }
            }

            // Validate depends_on_regexes
            if let Some(ref regexes) = job.depends_on_regexes {
                for regex_str in regexes {
                    match Regex::new(regex_str) {
                        Ok(re) => {
                            let mut found_match = false;
                            for other_name in &job_names {
                                if re.is_match(other_name) && !job_deps.contains(other_name) {
                                    job_deps.push(other_name.clone());
                                    found_match = true;
                                }
                            }
                            if !found_match {
                                errors.push(format!(
                                    "Job '{}' depends_on_regexes '{}' did not match any jobs",
                                    job.name, regex_str
                                ));
                            }
                        }
                        Err(e) => {
                            errors.push(format!(
                                "Job '{}' has invalid depends_on_regexes '{}': {}",
                                job.name, regex_str, e
                            ));
                        }
                    }
                }
            }

            dependencies.insert(job.name.clone(), job_deps);

            // Validate resource_requirements reference
            if let Some(ref rr_name) = job.resource_requirements
                && !resource_req_names.contains(rr_name)
            {
                errors.push(format!(
                    "Job '{}' references non-existent resource_requirements '{}'",
                    job.name, rr_name
                ));
            }

            // Validate scheduler reference
            if let Some(ref sched_name) = job.scheduler
                && !scheduler_names_set.contains(sched_name)
            {
                errors.push(format!(
                    "Job '{}' references non-existent scheduler '{}'",
                    job.name, sched_name
                ));
            }

            // Validate input_files references
            if let Some(ref files) = job.input_files {
                for file_name in files {
                    if !file_names.contains(file_name) {
                        errors.push(format!(
                            "Job '{}' input_files references non-existent file '{}'",
                            job.name, file_name
                        ));
                    }
                }
            }

            // Validate input_file_regexes
            if let Some(ref regexes) = job.input_file_regexes {
                for regex_str in regexes {
                    if let Err(e) = Regex::new(regex_str) {
                        errors.push(format!(
                            "Job '{}' has invalid input_file_regexes '{}': {}",
                            job.name, regex_str, e
                        ));
                    }
                }
            }

            // Validate output_files references
            if let Some(ref files) = job.output_files {
                for file_name in files {
                    if !file_names.contains(file_name) {
                        errors.push(format!(
                            "Job '{}' output_files references non-existent file '{}'",
                            job.name, file_name
                        ));
                    }
                }
            }

            // Validate output_file_regexes
            if let Some(ref regexes) = job.output_file_regexes {
                for regex_str in regexes {
                    if let Err(e) = Regex::new(regex_str) {
                        errors.push(format!(
                            "Job '{}' has invalid output_file_regexes '{}': {}",
                            job.name, regex_str, e
                        ));
                    }
                }
            }

            // Validate input_user_data references
            if let Some(ref uds) = job.input_user_data {
                for ud_name in uds {
                    if !user_data_names.contains(ud_name) {
                        errors.push(format!(
                            "Job '{}' input_user_data references non-existent user_data '{}'",
                            job.name, ud_name
                        ));
                    }
                }
            }

            // Validate input_user_data_regexes
            if let Some(ref regexes) = job.input_user_data_regexes {
                for regex_str in regexes {
                    if let Err(e) = Regex::new(regex_str) {
                        errors.push(format!(
                            "Job '{}' has invalid input_user_data_regexes '{}': {}",
                            job.name, regex_str, e
                        ));
                    }
                }
            }

            // Validate output_user_data references
            if let Some(ref uds) = job.output_user_data {
                for ud_name in uds {
                    if !user_data_names.contains(ud_name) {
                        errors.push(format!(
                            "Job '{}' output_user_data references non-existent user_data '{}'",
                            job.name, ud_name
                        ));
                    }
                }
            }

            // Validate output_user_data_regexes
            if let Some(ref regexes) = job.output_user_data_regexes {
                for regex_str in regexes {
                    if let Err(e) = Regex::new(regex_str) {
                        errors.push(format!(
                            "Job '{}' has invalid output_user_data_regexes '{}': {}",
                            job.name, regex_str, e
                        ));
                    }
                }
            }
        }

        // Step 9: Check for circular dependencies using topological sort
        {
            let mut remaining: HashSet<String> = job_names.clone();
            let mut processed = HashSet::new();

            while !remaining.is_empty() {
                let mut current_level = Vec::new();

                for job_name in &remaining {
                    if let Some(deps) = dependencies.get(job_name)
                        && deps.iter().all(|d| processed.contains(d))
                    {
                        current_level.push(job_name.clone());
                    }
                }

                if current_level.is_empty() {
                    // Find jobs involved in cycle for better error message
                    let cycle_jobs: Vec<&String> = remaining.iter().collect();
                    errors.push(format!(
                        "Circular dependency detected involving jobs: {}",
                        cycle_jobs
                            .iter()
                            .map(|s| format!("'{}'", s))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ));
                    break;
                }

                for job_name in current_level {
                    remaining.remove(&job_name);
                    processed.insert(job_name);
                }
            }
        }

        // Step 10: Validate action references
        if let Some(ref actions) = spec.actions {
            for (idx, action) in actions.iter().enumerate() {
                let action_desc = format!("Action #{} ({})", idx + 1, action.action_type);

                // Validate job references in actions
                if let Some(ref job_refs) = action.jobs {
                    for job_name in job_refs {
                        if !job_names.contains(job_name) {
                            errors.push(format!(
                                "{} references non-existent job '{}'",
                                action_desc, job_name
                            ));
                        }
                    }
                }

                // Validate job_name_regexes in actions
                if let Some(ref regexes) = action.job_name_regexes {
                    for regex_str in regexes {
                        if let Err(e) = Regex::new(regex_str) {
                            errors.push(format!(
                                "{} has invalid job_name_regexes '{}': {}",
                                action_desc, regex_str, e
                            ));
                        }
                    }
                }

                // Validate scheduler reference in schedule_nodes actions
                if action.action_type == "schedule_nodes"
                    && let Some(ref sched_name) = action.scheduler
                {
                    let sched_type = action.scheduler_type.as_deref().unwrap_or("");
                    if sched_type == "slurm" && !scheduler_names_set.contains(sched_name) {
                        errors.push(format!(
                            "{} references non-existent slurm scheduler '{}'",
                            action_desc, sched_name
                        ));
                    }
                }
            }
        }

        // Step 11: Warn about heterogeneous schedulers without jobs_sort_method
        // This helps users avoid suboptimal job-to-node matching
        if let Some(ref schedulers) = spec.slurm_schedulers
            && schedulers.len() > 1
            && spec.jobs_sort_method.is_none()
        {
            // Check if schedulers have different resource profiles
            let has_different_gres = schedulers
                .iter()
                .map(|s| &s.gres)
                .collect::<HashSet<_>>()
                .len()
                > 1;
            let has_different_mem = schedulers
                .iter()
                .map(|s| &s.mem)
                .collect::<HashSet<_>>()
                .len()
                > 1;
            let has_different_walltime = schedulers
                .iter()
                .map(|s| &s.walltime)
                .collect::<HashSet<_>>()
                .len()
                > 1;
            let has_different_partition = schedulers
                .iter()
                .map(|s| &s.partition)
                .collect::<HashSet<_>>()
                .len()
                > 1;

            let has_heterogeneous_schedulers = has_different_gres
                || has_different_mem
                || has_different_walltime
                || has_different_partition;

            // Check if any jobs don't have explicit scheduler assignments
            let jobs_without_scheduler = spec.jobs.iter().filter(|j| j.scheduler.is_none()).count();

            if has_heterogeneous_schedulers && jobs_without_scheduler > 0 {
                let mut differences = Vec::new();
                if has_different_gres {
                    differences.push("GPUs (gres)");
                }
                if has_different_mem {
                    differences.push("memory (mem)");
                }
                if has_different_walltime {
                    differences.push("walltime");
                }
                if has_different_partition {
                    differences.push("partition");
                }

                warnings.push(format!(
                        "Workflow has {} schedulers with different {} but {} job(s) have no explicit \
                        scheduler assignment and jobs_sort_method is not set. The default sort method \
                        'gpus_runtime_memory' will be used (jobs sorted by GPUs, then runtime, then \
                        memory). If this doesn't match your workload, consider setting jobs_sort_method \
                        explicitly to 'gpus_memory_runtime' (prioritize memory over runtime) or 'none' \
                        (no sorting).",
                        schedulers.len(),
                        differences.join(", "),
                        jobs_without_scheduler
                    ));
            }
        }

        // Collect scheduler names for summary
        let scheduler_names: Vec<String> = spec
            .slurm_schedulers
            .as_ref()
            .map(|schedulers| schedulers.iter().filter_map(|s| s.name.clone()).collect())
            .unwrap_or_default();

        // Build summary
        let summary = ValidationSummary {
            workflow_name: spec.name.clone(),
            workflow_description: spec.description.clone(),
            job_count: spec.jobs.len(),
            job_count_before_expansion,
            file_count: spec.files.as_ref().map(|f| f.len()).unwrap_or(0),
            file_count_before_expansion,
            user_data_count: spec.user_data.as_ref().map(|u| u.len()).unwrap_or(0),
            resource_requirements_count: spec
                .resource_requirements
                .as_ref()
                .map(|r| r.len())
                .unwrap_or(0),
            slurm_scheduler_count: spec.slurm_schedulers.as_ref().map(|s| s.len()).unwrap_or(0),
            action_count: spec.actions.as_ref().map(|a| a.len()).unwrap_or(0),
            has_schedule_nodes_action: spec.has_schedule_nodes_action(),
            job_names: spec.jobs.iter().map(|j| j.name.clone()).collect(),
            scheduler_names,
        };

        ValidationResult {
            valid: errors.is_empty(),
            errors,
            warnings,
            summary,
        }
    }

    /// Create a WorkflowModel on the server from a JSON file
    /// Create a workflow from a specification file (JSON, JSON5, or YAML) with all associated data
    ///
    /// This function will create the workflow and all associated models (files, user data, etc.)
    /// If any errors occur, the workflow will be deleted (which cascades to all other objects)
    ///
    /// # Arguments
    /// * `config` - Server configuration
    /// * `path` - Path to the workflow specification file
    /// * `user` - User that owns the workflow
    /// * `enable_resource_monitoring` - Whether to enable resource monitoring by default
    /// * `skip_checks` - Skip validation checks (use with caution)
    pub fn create_workflow_from_spec<P: AsRef<Path>>(
        config: &Configuration,
        path: P,
        user: &str,
        enable_resource_monitoring: bool,
        skip_checks: bool,
    ) -> Result<i64, Box<dyn std::error::Error>> {
        // Step 1: Deserialize the WorkflowSpecification from spec file
        let mut spec = Self::from_spec_file(path)?;
        spec.user = Some(user.to_string());

        // Apply default resource monitoring if enabled and not already configured
        if enable_resource_monitoring && spec.resource_monitor.is_none() {
            spec.resource_monitor = Some(crate::client::resource_monitor::ResourceMonitorConfig {
                enabled: true,
                granularity: crate::client::resource_monitor::MonitorGranularity::Summary,
                sample_interval_seconds: 10,
                generate_plots: false,
            });
        }

        // Step 1.25: Expand parameterized jobs and files
        spec.expand_parameters()?;

        // Step 1.4: Validate workflow actions
        spec.validate_actions()?;

        // Step 1.45: Validate scheduler node requirements
        if !skip_checks {
            spec.validate_scheduler_node_requirements()?;
        }

        // Step 1.5: Perform variable substitution in commands
        spec.substitute_variables()?;

        // Step 1.6: Collect per-job stdio overrides into execution_config
        {
            let overrides: HashMap<String, StdioConfig> = spec
                .jobs
                .iter()
                .filter_map(|job| {
                    job.stdio
                        .as_ref()
                        .map(|stdio| (job.name.clone(), stdio.clone()))
                })
                .collect();
            if !overrides.is_empty() {
                let ec = spec
                    .execution_config
                    .get_or_insert_with(ExecutionConfig::default);
                ec.job_stdio_overrides = Some(overrides);
            }
        }

        // Step 2: Create WorkflowModel
        let workflow_id = Self::create_workflow(config, &spec)?;

        // If any step fails, delete the workflow (which cascades to all other objects)
        let rollback = |workflow_id: i64| {
            let _ = default_api::delete_workflow(config, workflow_id, None);
        };

        // Step 3: Create supporting models and build name-to-id mappings
        let file_name_to_id = match Self::create_files(config, workflow_id, &spec) {
            Ok(mapping) => mapping,
            Err(e) => {
                rollback(workflow_id);
                return Err(e);
            }
        };

        let user_data_name_to_id = match Self::create_user_data(config, workflow_id, &spec) {
            Ok(mapping) => mapping,
            Err(e) => {
                rollback(workflow_id);
                return Err(e);
            }
        };

        let resource_req_name_to_id =
            match Self::create_resource_requirements(config, workflow_id, &spec) {
                Ok(mapping) => mapping,
                Err(e) => {
                    rollback(workflow_id);
                    return Err(e);
                }
            };

        let slurm_scheduler_to_id = match Self::create_slurm_schedulers(config, workflow_id, &spec)
        {
            Ok(mapping) => mapping,
            Err(e) => {
                rollback(workflow_id);
                return Err(e);
            }
        };

        let failure_handler_name_to_id =
            match Self::create_failure_handlers(config, workflow_id, &spec) {
                Ok(mapping) => mapping,
                Err(e) => {
                    rollback(workflow_id);
                    return Err(e);
                }
            };

        // Step 4: Create JobModels (with dependencies set during creation)
        let (job_name_to_id, _created_jobs) = match Self::create_jobs(
            config,
            workflow_id,
            &spec,
            &file_name_to_id,
            &user_data_name_to_id,
            &resource_req_name_to_id,
            &slurm_scheduler_to_id,
            &failure_handler_name_to_id,
        ) {
            Ok((mapping, jobs)) => (mapping, jobs),
            Err(e) => {
                rollback(workflow_id);
                return Err(e);
            }
        };

        // Step 5: Create workflow actions
        match Self::create_actions(
            config,
            workflow_id,
            &spec,
            &slurm_scheduler_to_id,
            &job_name_to_id,
        ) {
            Ok(_) => {}
            Err(e) => {
                rollback(workflow_id);
                return Err(e);
            }
        }

        Ok(workflow_id)
    }

    /// Create the workflow on the server
    fn create_workflow(
        config: &Configuration,
        spec: &WorkflowSpec,
    ) -> Result<i64, Box<dyn std::error::Error>> {
        let user = spec.user.clone().unwrap_or_else(|| "unknown".to_string());
        let mut workflow_model = models::WorkflowModel::new(spec.name.clone(), user);
        workflow_model.description = spec.description.clone();

        // Set compute node configuration fields if present
        if spec.compute_node_expiration_buffer_seconds.is_some() {
            log::warn!(
                "compute_node_expiration_buffer_seconds is deprecated and will be ignored. \
                 Slurm manages job termination signals via srun --time."
            );
        }
        if let Some(value) = spec.compute_node_wait_for_new_jobs_seconds {
            workflow_model.compute_node_wait_for_new_jobs_seconds = Some(value);
        } else {
            // Default must be >= completion_check_interval_secs + job_completion_poll_interval
            // to avoid exiting before dependent jobs are unblocked. See ComputeNodeRules.
            workflow_model.compute_node_wait_for_new_jobs_seconds = Some(90);
        }
        if let Some(value) = spec.compute_node_ignore_workflow_completion {
            workflow_model.compute_node_ignore_workflow_completion = Some(value);
        }
        if let Some(value) = spec.compute_node_wait_for_healthy_database_minutes {
            workflow_model.compute_node_wait_for_healthy_database_minutes = Some(value);
        }
        if let Some(ref value) = spec.jobs_sort_method {
            workflow_model.jobs_sort_method = Some(*value);
        }

        // Serialize resource_monitor config if present
        if let Some(ref resource_monitor) = spec.resource_monitor {
            let config_json = serde_json::to_string(resource_monitor)
                .map_err(|e| format!("Failed to serialize resource monitor config: {}", e))?;
            workflow_model.resource_monitor_config = Some(config_json);
        }

        // Validate and serialize slurm_defaults if present
        if let Some(ref slurm_defaults) = spec.slurm_defaults {
            // Validate that no excluded parameters are present
            slurm_defaults.validate()?;
            let config_json = serde_json::to_string(slurm_defaults)
                .map_err(|e| format!("Failed to serialize slurm_defaults config: {}", e))?;
            workflow_model.slurm_defaults = Some(config_json);
        }

        // Set use_pending_failed if present
        if let Some(value) = spec.use_pending_failed {
            workflow_model.use_pending_failed = Some(value);
        }

        // Store execution_config as JSON if any non-default settings are configured
        if let Some(ref execution_config) = spec.execution_config {
            // Validate and warn about potential issues
            for warning in execution_config.validate() {
                log::warn!("{}", warning);
            }

            if *execution_config != ExecutionConfig::default() {
                let execution_config_json = serde_json::to_string(execution_config)
                    .map_err(|e| format!("Failed to serialize execution_config: {}", e))?;
                workflow_model.execution_config = Some(execution_config_json);
            }
        }

        // Validate that execution_config fields match the effective mode.
        // For mode=auto, infer from slurm_schedulers presence.
        if let Some(ref ec) = spec.execution_config {
            let will_use_slurm = match ec.mode {
                ExecutionMode::Slurm => true,
                ExecutionMode::Auto => spec
                    .slurm_schedulers
                    .as_ref()
                    .is_some_and(|s| !s.is_empty()),
                ExecutionMode::Direct => false,
            };
            let will_use_direct = match ec.mode {
                ExecutionMode::Direct => true,
                ExecutionMode::Auto => !will_use_slurm,
                ExecutionMode::Slurm => false,
            };

            let mut errors = Vec::new();

            if will_use_slurm {
                if ec.limit_resources == Some(false) {
                    errors.push(
                        "limit_resources: false is only supported in direct mode. \
                        Slurm mode requires resource limits for correct srun behavior."
                            .to_string(),
                    );
                }
                if ec.termination_signal.is_some() {
                    errors.push(
                        "termination_signal is only supported in direct mode. \
                        In slurm mode, use srun_termination_signal instead."
                            .to_string(),
                    );
                }
                if ec.sigterm_lead_seconds.is_some() {
                    errors.push(
                        "sigterm_lead_seconds is only supported in direct mode. \
                        In slurm mode, termination timing is controlled by \
                        srun_termination_signal."
                            .to_string(),
                    );
                }
                if ec.oom_exit_code.is_some() {
                    errors.push(
                        "oom_exit_code is only supported in direct mode. \
                        In slurm mode, Slurm manages OOM detection."
                            .to_string(),
                    );
                }
            }

            if will_use_direct {
                if ec.srun_termination_signal.is_some() {
                    errors.push(
                        "srun_termination_signal is only supported in slurm mode. \
                        In direct mode, use termination_signal instead."
                            .to_string(),
                    );
                }
                if ec.enable_cpu_bind == Some(true) {
                    errors.push(
                        "enable_cpu_bind is only supported in slurm mode. \
                        It has no effect in direct mode."
                            .to_string(),
                    );
                }
            }

            if !errors.is_empty() {
                return Err(errors.join(" ").into());
            }
        }

        if spec.actions.as_ref().is_some_and(|actions| {
            actions.iter().any(|action| {
                action.action_type == "schedule_nodes"
                    && action.start_one_worker_per_node == Some(true)
            })
        }) {
            let mode = spec
                .execution_config
                .as_ref()
                .map(|config| &config.mode)
                .unwrap_or(&ExecutionMode::Auto);
            if *mode != ExecutionMode::Direct {
                return Err(
                    "start_one_worker_per_node requires execution_config.mode to be 'direct'"
                        .into(),
                );
            }
        }

        // Set enable_ro_crate if present
        if let Some(value) = spec.enable_ro_crate {
            workflow_model.enable_ro_crate = Some(value);
        }

        // Set project if present
        if let Some(ref value) = spec.project {
            workflow_model.project = Some(value.clone());
        }

        // Set metadata if present
        if let Some(ref value) = spec.metadata {
            workflow_model.metadata = Some(value.clone());
        }

        let created_workflow = default_api::create_workflow(config, workflow_model)
            .map_err(|e| format!("Failed to create workflow: {:?}", e))?;

        created_workflow
            .id
            .ok_or("Created workflow missing ID".into())
    }

    /// Create FileModels and build name-to-id mapping
    fn create_files(
        config: &Configuration,
        workflow_id: i64,
        spec: &WorkflowSpec,
    ) -> Result<HashMap<String, i64>, Box<dyn std::error::Error>> {
        let mut file_name_to_id = HashMap::new();

        if let Some(files) = &spec.files {
            for file_spec in files {
                // Check for duplicate names
                if file_name_to_id.contains_key(&file_spec.name) {
                    return Err(format!("Duplicate file name: {}", file_spec.name).into());
                }

                // Determine st_mtime: use spec value if provided, otherwise check filesystem
                let st_mtime = match file_spec.st_mtime {
                    Some(t) => Some(t), // User explicitly specified a timestamp
                    None => {
                        // Check if file exists on disk and get its modification time
                        std::fs::metadata(&file_spec.path)
                            .and_then(|m| m.modified())
                            .ok()
                            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                            .map(|d| d.as_secs_f64())
                    }
                };

                let file_model = models::FileModel {
                    id: None, // Server will assign ID
                    workflow_id,
                    name: file_spec.name.clone(),
                    path: file_spec.path.clone(),
                    st_mtime,
                };

                let created_file = default_api::create_file(config, file_model)
                    .map_err(|e| format!("Failed to create file {}: {:?}", file_spec.name, e))?;

                let file_id = created_file.id.ok_or("Created file missing ID")?;
                file_name_to_id.insert(file_spec.name.clone(), file_id);
            }
        }

        Ok(file_name_to_id)
    }

    /// Create UserDataModels and build name-to-id mapping
    fn create_user_data(
        config: &Configuration,
        workflow_id: i64,
        spec: &WorkflowSpec,
    ) -> Result<HashMap<String, i64>, Box<dyn std::error::Error>> {
        let mut user_data_name_to_id = HashMap::new();

        if let Some(user_data_list) = &spec.user_data {
            for user_data_spec in user_data_list {
                if let Some(name) = &user_data_spec.name {
                    // Check for duplicate names
                    if user_data_name_to_id.contains_key(name) {
                        return Err(format!("Duplicate user data name: {}", name).into());
                    }

                    let user_data_model = models::UserDataModel {
                        id: None, // Server will assign ID
                        workflow_id,
                        is_ephemeral: user_data_spec.is_ephemeral,
                        name: name.clone(),
                        data: user_data_spec.data.clone(),
                    };

                    let created_user_data =
                        default_api::create_user_data(config, user_data_model, None, None)
                            .map_err(|e| format!("Failed to create user data {}: {:?}", name, e))?;

                    let user_data_id =
                        created_user_data.id.ok_or("Created user data missing ID")?;
                    user_data_name_to_id.insert(name.clone(), user_data_id);
                }
            }
        }

        Ok(user_data_name_to_id)
    }

    /// Create ResourceRequirementsModels and build name-to-id mapping
    fn create_resource_requirements(
        config: &Configuration,
        workflow_id: i64,
        spec: &WorkflowSpec,
    ) -> Result<HashMap<String, i64>, Box<dyn std::error::Error>> {
        let mut resource_req_name_to_id = HashMap::new();

        if let Some(resource_requirements) = &spec.resource_requirements {
            for resource_req_spec in resource_requirements {
                // Check for duplicate names
                if resource_req_name_to_id.contains_key(&resource_req_spec.name) {
                    return Err(format!(
                        "Duplicate resource requirements name: {}",
                        resource_req_spec.name
                    )
                    .into());
                }

                let resource_req_model = models::ResourceRequirementsModel {
                    id: None, // Server will assign ID
                    workflow_id,
                    name: resource_req_spec.name.clone(),
                    num_cpus: resource_req_spec.num_cpus,
                    num_gpus: resource_req_spec.num_gpus,
                    num_nodes: resource_req_spec.num_nodes,
                    memory: resource_req_spec.memory.clone(),
                    runtime: resource_req_spec.runtime.clone(),
                };

                let created_resource_req =
                    default_api::create_resource_requirements(config, resource_req_model).map_err(
                        |e| {
                            format!(
                                "Failed to create resource requirements {}: {:?}",
                                resource_req_spec.name, e
                            )
                        },
                    )?;

                let resource_req_id = created_resource_req
                    .id
                    .ok_or("Created resource requirements missing ID")?;
                resource_req_name_to_id.insert(resource_req_spec.name.clone(), resource_req_id);
            }
        }

        Ok(resource_req_name_to_id)
    }

    /// Create SlurmSchedulerModels and build name-to-id mapping
    fn create_slurm_schedulers(
        config: &Configuration,
        workflow_id: i64,
        spec: &WorkflowSpec,
    ) -> Result<HashMap<String, i64>, Box<dyn std::error::Error>> {
        let mut slurm_scheduler_to_id = HashMap::new();

        if let Some(slurm_schedulers) = &spec.slurm_schedulers {
            for scheduler_spec in slurm_schedulers {
                if let Some(name) = &scheduler_spec.name {
                    // Check for duplicate names
                    if slurm_scheduler_to_id.contains_key(name) {
                        return Err(format!("Duplicate slurm scheduler name: {}", name).into());
                    }

                    let scheduler_model = models::SlurmSchedulerModel {
                        id: None, // Server will assign ID
                        workflow_id,
                        name: scheduler_spec.name.clone(),
                        account: scheduler_spec.account.clone(),
                        gres: scheduler_spec.gres.clone(),
                        mem: scheduler_spec.mem.clone(),
                        nodes: scheduler_spec.nodes,
                        ntasks_per_node: scheduler_spec.ntasks_per_node,
                        partition: scheduler_spec.partition.clone(),
                        qos: scheduler_spec.qos.clone(),
                        tmp: scheduler_spec.tmp.clone(),
                        walltime: scheduler_spec.walltime.clone(),
                        extra: scheduler_spec.extra.clone(),
                    };

                    let created_scheduler =
                        default_api::create_slurm_scheduler(config, scheduler_model).map_err(
                            |e| format!("Failed to create slurm scheduler {}: {:?}", name, e),
                        )?;

                    let scheduler_id = created_scheduler
                        .id
                        .ok_or("Created slurm scheduler missing ID")?;
                    slurm_scheduler_to_id.insert(name.clone(), scheduler_id);
                }
            }
        }

        Ok(slurm_scheduler_to_id)
    }

    /// Create failure handlers and build name-to-id mapping
    fn create_failure_handlers(
        config: &Configuration,
        workflow_id: i64,
        spec: &WorkflowSpec,
    ) -> Result<HashMap<String, i64>, Box<dyn std::error::Error>> {
        let mut failure_handler_name_to_id = HashMap::new();

        if let Some(failure_handlers) = &spec.failure_handlers {
            for handler_spec in failure_handlers {
                // Check for duplicate names
                if failure_handler_name_to_id.contains_key(&handler_spec.name) {
                    return Err(
                        format!("Duplicate failure handler name: {}", handler_spec.name).into(),
                    );
                }

                // Serialize the rules to JSON
                let rules_json = serde_json::to_string(&handler_spec.rules)
                    .map_err(|e| format!("Failed to serialize failure handler rules: {}", e))?;

                let handler_model = models::FailureHandlerModel::new(
                    workflow_id,
                    handler_spec.name.clone(),
                    rules_json,
                );

                let created_handler = default_api::create_failure_handler(config, handler_model)
                    .map_err(|e| {
                        format!(
                            "Failed to create failure handler {}: {:?}",
                            handler_spec.name, e
                        )
                    })?;

                let handler_id = created_handler
                    .id
                    .ok_or("Created failure handler missing ID")?;
                failure_handler_name_to_id.insert(handler_spec.name.clone(), handler_id);
            }
        }

        Ok(failure_handler_name_to_id)
    }

    /// Create workflow actions
    fn create_actions(
        config: &Configuration,
        workflow_id: i64,
        spec: &WorkflowSpec,
        slurm_scheduler_to_id: &HashMap<String, i64>,
        job_name_to_id: &HashMap<String, i64>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(actions) = &spec.actions {
            for action_spec in actions {
                // Resolve job_names and job_name_regexes to job_ids
                let job_ids =
                    if action_spec.jobs.is_some() || action_spec.job_name_regexes.is_some() {
                        let mut matched_job_ids = Vec::new();

                        // Match exact job names
                        if let Some(ref patterns) = action_spec.jobs {
                            for pattern in patterns {
                                if let Some(job_id) = job_name_to_id.get(pattern) {
                                    matched_job_ids.push(*job_id);
                                } else {
                                    return Err(format!(
                                        "Action references job '{}' which does not exist",
                                        pattern
                                    )
                                    .into());
                                }
                            }
                        }

                        // Match job names using regexes
                        if let Some(ref regexes) = action_spec.job_name_regexes {
                            use regex::Regex;
                            for regex_str in regexes {
                                let re = Regex::new(regex_str)
                                    .map_err(|e| format!("Invalid regex '{}': {}", regex_str, e))?;

                                for (job_name, job_id) in job_name_to_id {
                                    if re.is_match(job_name) && !matched_job_ids.contains(job_id) {
                                        matched_job_ids.push(*job_id);
                                    }
                                }
                            }
                        }

                        if matched_job_ids.is_empty() {
                            return Err("Action did not match any jobs".into());
                        }

                        Some(matched_job_ids)
                    } else {
                        None
                    };

                // Build action_config JSON based on action_type
                let action_config = match action_spec.action_type.as_str() {
                    "run_commands" => {
                        let commands = action_spec
                            .commands
                            .as_ref()
                            .ok_or("run_commands action requires 'commands' field")?;
                        serde_json::json!({
                            "commands": commands
                        })
                    }
                    "schedule_nodes" => {
                        let scheduler_type = action_spec
                            .scheduler_type
                            .as_ref()
                            .ok_or("schedule_nodes action requires 'scheduler_type' field")?;
                        let scheduler = action_spec
                            .scheduler
                            .as_ref()
                            .ok_or("schedule_nodes action requires 'scheduler' field")?;

                        // Translate scheduler to scheduler_id
                        let scheduler_id = if scheduler_type == "slurm" {
                            slurm_scheduler_to_id
                                .get(scheduler)
                                .ok_or(format!("Slurm scheduler '{}' not found", scheduler))?
                        } else {
                            // For other scheduler types, we might need a different lookup
                            // For now, just use 0 as placeholder
                            &0
                        };

                        let mut config = serde_json::json!({
                            "scheduler_type": scheduler_type,
                            "scheduler_id": scheduler_id,
                            "num_allocations": action_spec.num_allocations.unwrap_or(1),
                            "start_one_worker_per_node": action_spec.start_one_worker_per_node.unwrap_or(false),
                        });
                        // Only include max_parallel_jobs if explicitly specified
                        if let Some(max_parallel_jobs) = action_spec.max_parallel_jobs {
                            config["max_parallel_jobs"] = serde_json::json!(max_parallel_jobs);
                        }
                        config
                    }
                    _ => {
                        return Err(
                            format!("Unknown action_type: {}", action_spec.action_type).into()
                        );
                    }
                };

                // Create the action via API
                let action_body = serde_json::json!({
                    "workflow_id": workflow_id,
                    "trigger_type": action_spec.trigger_type,
                    "action_type": action_spec.action_type,
                    "action_config": action_config,
                    "job_ids": job_ids,
                    "persistent": action_spec.persistent.unwrap_or(false),
                });

                default_api::create_workflow_action(config, workflow_id, action_body)
                    .map_err(|e| format!("Failed to create workflow action: {:?}", e))?;
            }
        }

        Ok(())
    }

    /// Helper function to resolve names and regex patterns to IDs
    /// Returns a vector of IDs matching either the exact names or the regex patterns
    fn resolve_names_and_regexes(
        exact_names: &Option<Vec<String>>,
        regex_patterns: &Option<Vec<String>>,
        name_to_id: &HashMap<String, i64>,
        resource_type: &str, // e.g., "Input file", "Job dependency"
        job_name: &str,      // The job that needs this resource
    ) -> Result<Vec<i64>, Box<dyn std::error::Error>> {
        let mut ids = Vec::new();

        // Add IDs for exact name matches
        if let Some(names) = exact_names {
            for name in names {
                match name_to_id.get(name) {
                    Some(&id) => ids.push(id),
                    None => {
                        return Err(format!(
                            "{} '{}' not found for job '{}'",
                            resource_type, name, job_name
                        )
                        .into());
                    }
                }
            }
        }

        // Add IDs for regex pattern matches
        if let Some(patterns) = regex_patterns {
            for pattern_str in patterns {
                let re = Regex::new(pattern_str).map_err(|e| {
                    format!(
                        "Invalid regex '{}' for {} in job '{}': {}",
                        pattern_str,
                        resource_type.to_lowercase(),
                        job_name,
                        e
                    )
                })?;

                let mut found_match = false;
                for (name, &id) in name_to_id {
                    if re.is_match(name) && !ids.contains(&id) {
                        ids.push(id);
                        found_match = true;
                    }
                }

                // Error if regex didn't match anything
                if !found_match {
                    return Err(format!(
                        "{} regex '{}' did not match any names for job '{}'",
                        resource_type, pattern_str, job_name
                    )
                    .into());
                }
            }
        }

        Ok(ids)
    }

    /// Topologically sort jobs into levels based on dependencies
    /// Returns a vector of levels, where each level contains jobs that can be created together
    fn topological_sort_jobs<'a>(
        jobs: &'a [JobSpec],
        dependencies: &HashMap<String, Vec<String>>,
    ) -> Result<Vec<Vec<&'a JobSpec>>, Box<dyn std::error::Error>> {
        let mut levels = Vec::new();
        let mut remaining: HashSet<String> = jobs.iter().map(|j| j.name.clone()).collect();
        let mut processed = HashSet::new();

        while !remaining.is_empty() {
            let mut current_level = Vec::new();

            // Find all jobs whose dependencies are satisfied
            for job in jobs {
                if remaining.contains(&job.name) {
                    let deps = dependencies.get(&job.name).unwrap();
                    if deps.iter().all(|d| processed.contains(d)) {
                        current_level.push(job);
                    }
                }
            }

            if current_level.is_empty() {
                return Err("Circular dependency detected in job graph".into());
            }

            // Mark these jobs as processed
            for job in &current_level {
                remaining.remove(&job.name);
                processed.insert(job.name.clone());
            }

            levels.push(current_level);
        }

        Ok(levels)
    }

    /// Create JobModels with proper ID mapping using bulk API in batches
    /// Jobs are created in dependency order with depends_on_job_ids set during initial creation
    #[allow(clippy::type_complexity, clippy::too_many_arguments)]
    fn create_jobs(
        config: &Configuration,
        workflow_id: i64,
        spec: &WorkflowSpec,
        file_name_to_id: &HashMap<String, i64>,
        user_data_name_to_id: &HashMap<String, i64>,
        resource_req_name_to_id: &HashMap<String, i64>,
        slurm_scheduler_to_id: &HashMap<String, i64>,
        failure_handler_name_to_id: &HashMap<String, i64>,
    ) -> Result<(HashMap<String, i64>, HashMap<String, models::JobModel>), Box<dyn std::error::Error>>
    {
        let mut job_name_to_id = HashMap::new();
        let mut created_jobs = HashMap::new();

        // Step 1: Build a set of all job names for validation
        let all_job_names: std::collections::HashSet<String> =
            spec.jobs.iter().map(|j| j.name.clone()).collect();

        // Step 2: Build dependency graph (job_name -> Vec<dependency_job_names>)
        let mut dependencies: HashMap<String, Vec<String>> = HashMap::new();

        for job_spec in &spec.jobs {
            let mut deps = Vec::new();

            // Add explicit dependencies
            if let Some(ref names) = job_spec.depends_on {
                for dep_name in names {
                    // Validate that the dependency exists
                    if !all_job_names.contains(dep_name) {
                        return Err(format!(
                            "Blocking job '{}' not found for job '{}'",
                            dep_name, job_spec.name
                        )
                        .into());
                    }
                    deps.push(dep_name.clone());
                }
            }

            // Resolve regex dependencies
            if let Some(ref regexes) = job_spec.depends_on_regexes {
                for regex_str in regexes {
                    let re = Regex::new(regex_str).map_err(|e| {
                        format!(
                            "Invalid regex '{}' in job '{}': {}",
                            regex_str, job_spec.name, e
                        )
                    })?;
                    let mut found_match = false;
                    for other_job in &spec.jobs {
                        if re.is_match(&other_job.name) && !deps.contains(&other_job.name) {
                            deps.push(other_job.name.clone());
                            found_match = true;
                        }
                    }
                    // Error if regex didn't match anything
                    if !found_match {
                        return Err(format!(
                            "Blocking job regex '{}' did not match any jobs for job '{}'",
                            regex_str, job_spec.name
                        )
                        .into());
                    }
                }
            }

            dependencies.insert(job_spec.name.clone(), deps);
        }

        // Step 3: Topologically sort jobs into levels
        let levels = Self::topological_sort_jobs(&spec.jobs, &dependencies)?;

        // Step 4: Create jobs level by level
        let batch_size = crate::MAX_RECORD_TRANSFER_COUNT as usize;

        for level in levels {
            // Create job models for this level with depends_on_job_ids resolved
            let mut job_models = Vec::new();
            let mut job_spec_mapping = Vec::new();

            for job_spec in level {
                let mut job_model = models::JobModel::new(
                    workflow_id,
                    job_spec.name.clone(),
                    job_spec.command.clone(),
                );

                // Set optional fields
                job_model.invocation_script = job_spec.invocation_script.clone();
                // Only override cancel_on_blocking_job_failure if explicitly set in spec
                // (JobModel::new() defaults to Some(true))
                if job_spec.cancel_on_blocking_job_failure.is_some() {
                    job_model.cancel_on_blocking_job_failure =
                        job_spec.cancel_on_blocking_job_failure;
                }
                // supports_termination is deprecated — Slurm manages termination
                // signals via srun --time and KillWait. Accept the field silently
                // to avoid breaking existing specs.

                // Map file names and regexes to IDs
                let input_file_ids = Self::resolve_names_and_regexes(
                    &job_spec.input_files,
                    &job_spec.input_file_regexes,
                    file_name_to_id,
                    "Input file",
                    &job_spec.name,
                )?;
                if !input_file_ids.is_empty() {
                    job_model.input_file_ids = Some(input_file_ids);
                }

                let output_file_ids = Self::resolve_names_and_regexes(
                    &job_spec.output_files,
                    &job_spec.output_file_regexes,
                    file_name_to_id,
                    "Output file",
                    &job_spec.name,
                )?;
                if !output_file_ids.is_empty() {
                    job_model.output_file_ids = Some(output_file_ids);
                }

                // Map user data names and regexes to IDs
                let input_user_data_ids = Self::resolve_names_and_regexes(
                    &job_spec.input_user_data,
                    &job_spec.input_user_data_regexes,
                    user_data_name_to_id,
                    "Input user data",
                    &job_spec.name,
                )?;
                if !input_user_data_ids.is_empty() {
                    job_model.input_user_data_ids = Some(input_user_data_ids);
                }

                let output_user_data_ids = Self::resolve_names_and_regexes(
                    &job_spec.output_user_data,
                    &job_spec.output_user_data_regexes,
                    user_data_name_to_id,
                    "Output user data",
                    &job_spec.name,
                )?;
                if !output_user_data_ids.is_empty() {
                    job_model.output_user_data_ids = Some(output_user_data_ids);
                }

                // Map resource requirements name to ID
                if let Some(resource_req_name) = &job_spec.resource_requirements {
                    match resource_req_name_to_id.get(resource_req_name) {
                        Some(&resource_req_id) => {
                            job_model.resource_requirements_id = Some(resource_req_id)
                        }
                        None => {
                            return Err(format!(
                                "Resource requirements '{}' not found for job '{}'",
                                resource_req_name, job_spec.name
                            )
                            .into());
                        }
                    }
                }

                // Map scheduler name to ID
                if let Some(scheduler) = &job_spec.scheduler {
                    match slurm_scheduler_to_id.get(scheduler) {
                        Some(&scheduler_id) => job_model.scheduler_id = Some(scheduler_id),
                        None => {
                            return Err(format!(
                                "Scheduler '{}' not found for job '{}'",
                                scheduler, job_spec.name
                            )
                            .into());
                        }
                    }
                }

                // Map failure handler name to ID
                if let Some(failure_handler) = &job_spec.failure_handler {
                    match failure_handler_name_to_id.get(failure_handler) {
                        Some(&handler_id) => job_model.failure_handler_id = Some(handler_id),
                        None => {
                            return Err(format!(
                                "Failure handler '{}' not found for job '{}'",
                                failure_handler, job_spec.name
                            )
                            .into());
                        }
                    }
                }

                // NEW: Resolve depends_on_job_ids using accumulated job_name_to_id
                let dep_names = dependencies.get(&job_spec.name).unwrap();
                if !dep_names.is_empty() {
                    let mut depends_on_ids = Vec::new();
                    for dep_name in dep_names {
                        let dep_id = job_name_to_id.get(dep_name).ok_or_else(|| {
                            format!(
                                "Dependency '{}' not found for job '{}' (not yet created)",
                                dep_name, job_spec.name
                            )
                        })?;
                        depends_on_ids.push(*dep_id);
                    }
                    job_model.depends_on_job_ids = Some(depends_on_ids);
                }

                job_models.push(job_model);
                job_spec_mapping.push(job_spec);
            }

            // Create this level's jobs in batches
            for (batch_index, batch) in job_models.chunks(batch_size).enumerate() {
                let jobs_model = models::JobsModel::new(batch.to_vec());

                let response = default_api::create_jobs(config, jobs_model).map_err(|e| {
                    format!(
                        "Failed to create batch {} of jobs: {:?}",
                        batch_index + 1,
                        e
                    )
                })?;

                let created_batch = response.jobs.ok_or("Create jobs response missing items")?;

                if created_batch.len() != batch.len() {
                    return Err(format!(
                        "Batch {} returned {} jobs but expected {}",
                        batch_index + 1,
                        created_batch.len(),
                        batch.len()
                    )
                    .into());
                }

                // Update mappings
                let batch_start = batch_index * batch_size;
                for (i, created_job) in created_batch.iter().enumerate() {
                    let job_spec = job_spec_mapping[batch_start + i];
                    let job_id = created_job.id.ok_or("Created job missing ID")?;
                    job_name_to_id.insert(job_spec.name.clone(), job_id);
                    created_jobs.insert(job_spec.name.clone(), created_job.clone());
                }
            }
        }

        Ok((job_name_to_id, created_jobs))
    }

    /// Convert a byte offset to (line, column) for error reporting
    #[cfg(feature = "client")]
    fn offset_to_line_col(content: &str, offset: usize) -> (usize, usize) {
        let mut line = 1;
        let mut col = 1;
        for (i, ch) in content.char_indices() {
            if i >= offset {
                break;
            }
            if ch == '\n' {
                line += 1;
                col = 1;
            } else {
                col += 1;
            }
        }
        (line, col)
    }

    /// Convert a KDL parameters block to a JSON object
    #[cfg(feature = "client")]
    fn kdl_parameters_to_json(
        node: &KdlNode,
    ) -> Result<Option<serde_json::Value>, Box<dyn std::error::Error>> {
        let Some(children) = node.children() else {
            return Ok(None);
        };

        let mut params = serde_json::Map::new();
        for child in children.nodes() {
            let param_name = child.name().value().to_string();
            let param_value = child
                .entries()
                .first()
                .and_then(|e| e.value().as_string())
                .ok_or_else(|| format!("Parameter '{}' must have a string value", param_name))?
                .to_string();
            params.insert(param_name, serde_json::Value::String(param_value));
        }

        if params.is_empty() {
            Ok(None)
        } else {
            Ok(Some(serde_json::Value::Object(params)))
        }
    }

    /// Convert a KDL job node to a JSON object
    #[cfg(feature = "client")]
    fn kdl_job_to_json(node: &KdlNode) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let name = node
            .entries()
            .first()
            .and_then(|e| e.value().as_string())
            .ok_or("job must have a name")?
            .to_string();

        let mut obj = serde_json::Map::new();
        obj.insert("name".to_string(), serde_json::Value::String(name));

        // Collect array fields
        let mut depends_on: Vec<serde_json::Value> = Vec::new();
        let mut depends_on_regexes: Vec<serde_json::Value> = Vec::new();
        let mut input_files: Vec<serde_json::Value> = Vec::new();
        let mut output_files: Vec<serde_json::Value> = Vec::new();
        let mut input_user_data: Vec<serde_json::Value> = Vec::new();
        let mut output_user_data: Vec<serde_json::Value> = Vec::new();

        if let Some(children) = node.children() {
            for child in children.nodes() {
                match child.name().value() {
                    "command" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "command".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "invocation_script" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "invocation_script".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "cancel_on_blocking_job_failure" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_bool()) {
                            obj.insert(
                                "cancel_on_blocking_job_failure".to_string(),
                                serde_json::Value::Bool(v),
                            );
                        }
                    }
                    "supports_termination" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_bool()) {
                            obj.insert(
                                "supports_termination".to_string(),
                                serde_json::Value::Bool(v),
                            );
                        }
                    }
                    "resource_requirements" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "resource_requirements".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "failure_handler" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "failure_handler".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "depends_on" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            depends_on.push(serde_json::Value::String(v.to_string()));
                        }
                    }
                    "depends_on_regexes" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            depends_on_regexes.push(serde_json::Value::String(v.to_string()));
                        }
                    }
                    "input_file" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            input_files.push(serde_json::Value::String(v.to_string()));
                        }
                    }
                    "output_file" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            output_files.push(serde_json::Value::String(v.to_string()));
                        }
                    }
                    "input_user_data" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            input_user_data.push(serde_json::Value::String(v.to_string()));
                        }
                    }
                    "output_user_data" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            output_user_data.push(serde_json::Value::String(v.to_string()));
                        }
                    }
                    "scheduler" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "scheduler".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "parameters" => {
                        if let Some(params) = Self::kdl_parameters_to_json(child)? {
                            obj.insert("parameters".to_string(), params);
                        }
                    }
                    "parameter_mode" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "parameter_mode".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "use_parameters" => {
                        let param_names: Vec<serde_json::Value> = child
                            .entries()
                            .iter()
                            .filter_map(|e| {
                                e.value()
                                    .as_string()
                                    .map(|s| serde_json::Value::String(s.to_string()))
                            })
                            .collect();
                        if !param_names.is_empty() {
                            obj.insert(
                                "use_parameters".to_string(),
                                serde_json::Value::Array(param_names),
                            );
                        }
                    }
                    "stdio" => {
                        let stdio_obj = Self::kdl_stdio_config_to_json(child)?;
                        obj.insert("stdio".to_string(), stdio_obj);
                    }
                    _ => {}
                }
            }
        }

        // Add collected arrays if non-empty
        if !depends_on.is_empty() {
            obj.insert(
                "depends_on".to_string(),
                serde_json::Value::Array(depends_on),
            );
        }
        if !depends_on_regexes.is_empty() {
            obj.insert(
                "depends_on_regexes".to_string(),
                serde_json::Value::Array(depends_on_regexes),
            );
        }
        if !input_files.is_empty() {
            obj.insert(
                "input_files".to_string(),
                serde_json::Value::Array(input_files),
            );
        }
        if !output_files.is_empty() {
            obj.insert(
                "output_files".to_string(),
                serde_json::Value::Array(output_files),
            );
        }
        if !input_user_data.is_empty() {
            obj.insert(
                "input_user_data".to_string(),
                serde_json::Value::Array(input_user_data),
            );
        }
        if !output_user_data.is_empty() {
            obj.insert(
                "output_user_data".to_string(),
                serde_json::Value::Array(output_user_data),
            );
        }

        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL file node to a JSON object
    #[cfg(feature = "client")]
    fn kdl_file_to_json(node: &KdlNode) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let name = node
            .entries()
            .first()
            .and_then(|e| e.value().as_string())
            .ok_or("file must have a name")?
            .to_string();

        let mut obj = serde_json::Map::new();
        obj.insert("name".to_string(), serde_json::Value::String(name));

        // Path can be specified as a property (file "name" path="/path")
        if let Some(path) = node.get("path").and_then(|e| e.as_string()) {
            obj.insert(
                "path".to_string(),
                serde_json::Value::String(path.to_string()),
            );
        }

        // Check for child nodes
        if let Some(children) = node.children() {
            for child in children.nodes() {
                match child.name().value() {
                    "path" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "path".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "parameters" => {
                        if let Some(params) = Self::kdl_parameters_to_json(child)? {
                            obj.insert("parameters".to_string(), params);
                        }
                    }
                    "parameter_mode" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "parameter_mode".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "use_parameters" => {
                        let param_names: Vec<serde_json::Value> = child
                            .entries()
                            .iter()
                            .filter_map(|e| {
                                e.value()
                                    .as_string()
                                    .map(|s| serde_json::Value::String(s.to_string()))
                            })
                            .collect();
                        if !param_names.is_empty() {
                            obj.insert(
                                "use_parameters".to_string(),
                                serde_json::Value::Array(param_names),
                            );
                        }
                    }
                    _ => {}
                }
            }
        }

        // Validate required path field
        if !obj.contains_key("path") {
            return Err("file must have a path property".into());
        }

        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL user_data node to a JSON object
    #[cfg(feature = "client")]
    fn kdl_user_data_to_json(
        node: &KdlNode,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let mut obj = serde_json::Map::new();

        // Name is optional
        if let Some(name) = node.entries().first().and_then(|e| e.value().as_string()) {
            obj.insert(
                "name".to_string(),
                serde_json::Value::String(name.to_string()),
            );
        }

        let mut data_str: Option<&str> = None;

        if let Some(children) = node.children() {
            for child in children.nodes() {
                match child.name().value() {
                    "is_ephemeral" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_bool()) {
                            obj.insert("is_ephemeral".to_string(), serde_json::Value::Bool(v));
                        }
                    }
                    "data" => {
                        data_str = child.entries().first().and_then(|e| e.value().as_string());
                    }
                    _ => {}
                }
            }
        }

        // Parse data string as JSON
        let data_str = data_str.ok_or("user_data must have a data property")?;
        let data: serde_json::Value = serde_json::from_str(data_str)?;
        obj.insert("data".to_string(), data);

        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL resource_requirements node to a JSON object
    #[cfg(feature = "client")]
    fn kdl_resource_requirements_to_json(
        node: &KdlNode,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let name = node
            .entries()
            .first()
            .and_then(|e| e.value().as_string())
            .ok_or("resource_requirements must have a name")?
            .to_string();

        let mut obj = serde_json::Map::new();
        obj.insert("name".to_string(), serde_json::Value::String(name));

        if let Some(children) = node.children() {
            for child in children.nodes() {
                match child.name().value() {
                    "num_cpus" => {
                        if let Some(v) =
                            child.entries().first().and_then(|e| e.value().as_integer())
                        {
                            obj.insert(
                                "num_cpus".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(v as i64)),
                            );
                        }
                    }
                    "num_gpus" => {
                        if let Some(v) =
                            child.entries().first().and_then(|e| e.value().as_integer())
                        {
                            obj.insert(
                                "num_gpus".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(v as i64)),
                            );
                        }
                    }
                    "num_nodes" => {
                        if let Some(v) =
                            child.entries().first().and_then(|e| e.value().as_integer())
                        {
                            obj.insert(
                                "num_nodes".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(v as i64)),
                            );
                        }
                    }
                    "memory" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "memory".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "runtime" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "runtime".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    _ => {}
                }
            }
        }

        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL slurm_scheduler node to a JSON object
    #[cfg(feature = "client")]
    fn kdl_slurm_scheduler_to_json(
        node: &KdlNode,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let mut obj = serde_json::Map::new();

        // Name is optional
        if let Some(name) = node.entries().first().and_then(|e| e.value().as_string()) {
            obj.insert(
                "name".to_string(),
                serde_json::Value::String(name.to_string()),
            );
        }

        if let Some(children) = node.children() {
            for child in children.nodes() {
                match child.name().value() {
                    "account" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "account".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "gres" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "gres".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "mem" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert("mem".to_string(), serde_json::Value::String(v.to_string()));
                        }
                    }
                    "nodes" => {
                        if let Some(v) =
                            child.entries().first().and_then(|e| e.value().as_integer())
                        {
                            obj.insert(
                                "nodes".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(v as i64)),
                            );
                        }
                    }
                    "ntasks_per_node" => {
                        if let Some(v) =
                            child.entries().first().and_then(|e| e.value().as_integer())
                        {
                            obj.insert(
                                "ntasks_per_node".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(v as i64)),
                            );
                        }
                    }
                    "partition" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "partition".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "qos" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert("qos".to_string(), serde_json::Value::String(v.to_string()));
                        }
                    }
                    "tmp" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert("tmp".to_string(), serde_json::Value::String(v.to_string()));
                        }
                    }
                    "walltime" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "walltime".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "extra" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "extra".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    _ => {}
                }
            }
        }

        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL action node to a JSON object
    #[cfg(feature = "client")]
    fn kdl_action_to_json(node: &KdlNode) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let mut obj = serde_json::Map::new();

        // Collect array fields
        let mut job_names: Vec<serde_json::Value> = Vec::new();
        let mut job_name_regexes: Vec<serde_json::Value> = Vec::new();
        let mut commands: Vec<serde_json::Value> = Vec::new();

        if let Some(children) = node.children() {
            for child in children.nodes() {
                match child.name().value() {
                    "trigger_type" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "trigger_type".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "action_type" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "action_type".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "job" => {
                        // Collect individual job entries: job "prep_a" / job "prep_b"
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            job_names.push(serde_json::Value::String(v.to_string()));
                        }
                    }
                    "jobs" => {
                        // Parse jobs as multiple string arguments: jobs "job1" "job2" "job3"
                        for e in child.entries().iter() {
                            if let Some(s) = e.value().as_string() {
                                job_names.push(serde_json::Value::String(s.to_string()));
                            }
                        }
                    }
                    "job_name_regexes" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            job_name_regexes.push(serde_json::Value::String(v.to_string()));
                        }
                    }
                    "command" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            commands.push(serde_json::Value::String(v.to_string()));
                        }
                    }
                    "scheduler" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "scheduler".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "scheduler_type" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "scheduler_type".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "num_allocations" => {
                        if let Some(v) =
                            child.entries().first().and_then(|e| e.value().as_integer())
                        {
                            obj.insert(
                                "num_allocations".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(v as i64)),
                            );
                        }
                    }
                    "start_one_worker_per_node" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_bool()) {
                            obj.insert(
                                "start_one_worker_per_node".to_string(),
                                serde_json::Value::Bool(v),
                            );
                        }
                    }
                    "max_parallel_jobs" => {
                        if let Some(v) =
                            child.entries().first().and_then(|e| e.value().as_integer())
                        {
                            obj.insert(
                                "max_parallel_jobs".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(v as i64)),
                            );
                        }
                    }
                    "persistent" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_bool()) {
                            obj.insert("persistent".to_string(), serde_json::Value::Bool(v));
                        }
                    }
                    _ => {}
                }
            }
        }

        // Add collected arrays if non-empty
        if !job_names.is_empty() {
            obj.insert("jobs".to_string(), serde_json::Value::Array(job_names));
        }
        if !job_name_regexes.is_empty() {
            obj.insert(
                "job_name_regexes".to_string(),
                serde_json::Value::Array(job_name_regexes),
            );
        }
        if !commands.is_empty() {
            obj.insert("commands".to_string(), serde_json::Value::Array(commands));
        }

        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL resource_monitor node to a JSON object
    #[cfg(feature = "client")]
    fn kdl_resource_monitor_to_json(
        node: &KdlNode,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let mut obj = serde_json::Map::new();

        if let Some(children) = node.children() {
            for child in children.nodes() {
                match child.name().value() {
                    "enabled" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_bool()) {
                            obj.insert("enabled".to_string(), serde_json::Value::Bool(v));
                        }
                    }
                    "granularity" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_string())
                        {
                            obj.insert(
                                "granularity".to_string(),
                                serde_json::Value::String(v.to_string()),
                            );
                        }
                    }
                    "sample_interval_seconds" => {
                        if let Some(v) =
                            child.entries().first().and_then(|e| e.value().as_integer())
                        {
                            obj.insert(
                                "sample_interval_seconds".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(v as i64)),
                            );
                        }
                    }
                    "generate_plots" => {
                        if let Some(v) = child.entries().first().and_then(|e| e.value().as_bool()) {
                            obj.insert("generate_plots".to_string(), serde_json::Value::Bool(v));
                        }
                    }
                    _ => {}
                }
            }
        }

        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL execution_config node to a JSON object
    ///
    /// Parses execution_config block with mode and various settings for job execution.
    #[cfg(feature = "client")]
    fn kdl_execution_config_to_json(
        node: &KdlNode,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let mut obj = serde_json::Map::new();

        if let Some(children) = node.children() {
            for child in children.nodes() {
                let key = child.name().value();
                // Handle child blocks (no entry value, only children)
                if key == "stdio" {
                    let stdio_obj = Self::kdl_stdio_config_to_json(child)?;
                    obj.insert("stdio".to_string(), stdio_obj);
                    continue;
                }
                if let Some(entry) = child.entries().first() {
                    let value = entry.value();
                    match key {
                        "mode" => {
                            if let Some(s) = value.as_string() {
                                obj.insert(
                                    "mode".to_string(),
                                    serde_json::Value::String(s.to_string()),
                                );
                            }
                        }
                        "limit_resources" | "enable_cpu_bind" => {
                            if let Some(b) = value.as_bool() {
                                obj.insert(key.to_string(), serde_json::Value::Bool(b));
                            }
                        }
                        "termination_signal" | "srun_termination_signal" => {
                            if let Some(s) = value.as_string() {
                                obj.insert(
                                    key.to_string(),
                                    serde_json::Value::String(s.to_string()),
                                );
                            }
                        }
                        "sigterm_lead_seconds" | "sigkill_headroom_seconds" => {
                            if let Some(i) = value.as_integer() {
                                obj.insert(
                                    key.to_string(),
                                    serde_json::Value::Number(serde_json::Number::from(i as i64)),
                                );
                            }
                        }
                        "timeout_exit_code" | "oom_exit_code" => {
                            if let Some(i) = value.as_integer() {
                                obj.insert(
                                    key.to_string(),
                                    serde_json::Value::Number(serde_json::Number::from(i as i64)),
                                );
                            }
                        }
                        _ => {
                            log::warn!("Unknown execution_config field '{}' will be ignored", key);
                        }
                    }
                }
            }
        }

        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL stdio config node to a JSON object.
    ///
    /// Handles blocks like:
    /// ```kdl
    /// stdio {
    ///     mode "combined"
    ///     delete_on_success #true
    /// }
    /// ```
    #[cfg(feature = "client")]
    fn kdl_stdio_config_to_json(
        node: &KdlNode,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let mut obj = serde_json::Map::new();

        if let Some(children) = node.children() {
            for child in children.nodes() {
                let key = child.name().value();
                if let Some(entry) = child.entries().first() {
                    match key {
                        "mode" => {
                            if let Some(s) = entry.value().as_string() {
                                obj.insert(
                                    "mode".to_string(),
                                    serde_json::Value::String(s.to_string()),
                                );
                            }
                        }
                        "delete_on_success" => {
                            if let Some(b) = entry.value().as_bool() {
                                obj.insert(
                                    "delete_on_success".to_string(),
                                    serde_json::Value::Bool(b),
                                );
                            }
                        }
                        _ => {
                            log::warn!("Unknown stdio field '{}' will be ignored", key);
                        }
                    }
                }
            }
        }

        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL slurm_defaults node to a JSON object
    ///
    /// Parses slurm_defaults block containing arbitrary key-value pairs for Slurm parameters.
    /// Values can be strings, integers, or booleans.
    #[cfg(feature = "client")]
    fn kdl_slurm_defaults_to_json(
        node: &KdlNode,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let mut obj = serde_json::Map::new();

        if let Some(children) = node.children() {
            for child in children.nodes() {
                let key = child.name().value().to_string();
                if let Some(entry) = child.entries().first() {
                    let value = entry.value();
                    if let Some(s) = value.as_string() {
                        obj.insert(key, serde_json::Value::String(s.to_string()));
                    } else if let Some(i) = value.as_integer() {
                        obj.insert(
                            key,
                            serde_json::Value::Number(serde_json::Number::from(i as i64)),
                        );
                    } else if let Some(b) = value.as_bool() {
                        obj.insert(key, serde_json::Value::Bool(b));
                    }
                }
            }
        }

        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL failure_handler node to a JSON object
    #[cfg(feature = "client")]
    fn kdl_failure_handler_to_json(
        node: &KdlNode,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let name = node
            .entries()
            .first()
            .and_then(|e| e.value().as_string())
            .ok_or("failure_handler must have a name")?
            .to_string();

        let mut obj = serde_json::Map::new();
        obj.insert("name".to_string(), serde_json::Value::String(name));

        let mut rules: Vec<serde_json::Value> = Vec::new();

        if let Some(children) = node.children() {
            for child in children.nodes() {
                if child.name().value() == "rule" {
                    let mut rule_obj = serde_json::Map::new();

                    if let Some(rule_children) = child.children() {
                        for rule_child in rule_children.nodes() {
                            match rule_child.name().value() {
                                "exit_codes" => {
                                    let codes: Vec<serde_json::Value> = rule_child
                                        .entries()
                                        .iter()
                                        .filter_map(|e| {
                                            e.value().as_integer().map(|i| {
                                                serde_json::Value::Number((i as i64).into())
                                            })
                                        })
                                        .collect();
                                    if !codes.is_empty() {
                                        rule_obj.insert(
                                            "exit_codes".to_string(),
                                            serde_json::Value::Array(codes),
                                        );
                                    }
                                }
                                "match_all_exit_codes" => {
                                    if let Some(v) = rule_child
                                        .entries()
                                        .first()
                                        .and_then(|e| e.value().as_bool())
                                    {
                                        rule_obj.insert(
                                            "match_all_exit_codes".to_string(),
                                            serde_json::Value::Bool(v),
                                        );
                                    }
                                }
                                "recovery_script" => {
                                    if let Some(v) = rule_child
                                        .entries()
                                        .first()
                                        .and_then(|e| e.value().as_string())
                                    {
                                        rule_obj.insert(
                                            "recovery_script".to_string(),
                                            serde_json::Value::String(v.to_string()),
                                        );
                                    }
                                }
                                "max_retries" => {
                                    if let Some(v) = rule_child
                                        .entries()
                                        .first()
                                        .and_then(|e| e.value().as_integer())
                                    {
                                        rule_obj.insert(
                                            "max_retries".to_string(),
                                            serde_json::Value::Number((v as i64).into()),
                                        );
                                    }
                                }
                                _ => {}
                            }
                        }
                    }

                    rules.push(serde_json::Value::Object(rule_obj));
                }
            }
        }

        obj.insert("rules".to_string(), serde_json::Value::Array(rules));
        Ok(serde_json::Value::Object(obj))
    }

    /// Convert a KDL document string to a serde_json::Value
    /// This is the intermediate representation used by all file formats
    #[cfg(feature = "client")]
    fn kdl_to_json_value(content: &str) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let doc: KdlDocument = content.parse().map_err(|e: kdl::KdlError| {
            // Extract detailed diagnostic information from KDL parse errors
            let mut error_msg = String::from("Failed to parse KDL document:\n");
            for diag in e.diagnostics.iter() {
                let offset = diag.span.offset();
                let (line, col) = Self::offset_to_line_col(content, offset);

                if let Some(msg) = &diag.message {
                    error_msg.push_str(&format!("  Line {}, column {}: {}", line, col, msg));
                } else {
                    error_msg.push_str(&format!("  Line {}, column {}: syntax error", line, col));
                }
                if let Some(label) = &diag.label {
                    error_msg.push_str(&format!(" ({})", label));
                }
                error_msg.push('\n');
                if let Some(help) = &diag.help {
                    error_msg.push_str(&format!("    Help: {}\n", help));
                }
            }
            // Show the problematic line if we can
            if let Some(first_diag) = e.diagnostics.first() {
                let offset = first_diag.span.offset();
                let (line_num, col) = Self::offset_to_line_col(content, offset);
                if let Some(line_content) = content.lines().nth(line_num.saturating_sub(1)) {
                    error_msg.push_str(&format!("\n  {} | {}\n", line_num, line_content));
                    error_msg.push_str(&format!(
                        "  {} | {}^\n",
                        " ".repeat(line_num.to_string().len()),
                        " ".repeat(col.saturating_sub(1))
                    ));
                }
            }
            error_msg
        })?;

        let mut obj = serde_json::Map::new();
        let mut jobs: Vec<serde_json::Value> = Vec::new();
        let mut files: Vec<serde_json::Value> = Vec::new();
        let mut user_data: Vec<serde_json::Value> = Vec::new();
        let mut resource_requirements: Vec<serde_json::Value> = Vec::new();
        let mut failure_handlers: Vec<serde_json::Value> = Vec::new();
        let mut slurm_schedulers: Vec<serde_json::Value> = Vec::new();
        let mut actions: Vec<serde_json::Value> = Vec::new();

        for node in doc.nodes() {
            match node.name().value() {
                "name" => {
                    if let Some(v) = node.entries().first().and_then(|e| e.value().as_string()) {
                        obj.insert("name".to_string(), serde_json::Value::String(v.to_string()));
                    }
                }
                "user" => {
                    if let Some(v) = node.entries().first().and_then(|e| e.value().as_string()) {
                        obj.insert("user".to_string(), serde_json::Value::String(v.to_string()));
                    }
                }
                "description" => {
                    if let Some(v) = node.entries().first().and_then(|e| e.value().as_string()) {
                        obj.insert(
                            "description".to_string(),
                            serde_json::Value::String(v.to_string()),
                        );
                    }
                }
                "compute_node_expiration_buffer_seconds" => {
                    if let Some(v) = node.entries().first().and_then(|e| e.value().as_integer()) {
                        obj.insert(
                            "compute_node_expiration_buffer_seconds".to_string(),
                            serde_json::Value::Number(serde_json::Number::from(v as i64)),
                        );
                    }
                }
                "compute_node_wait_for_new_jobs_seconds" => {
                    if let Some(v) = node.entries().first().and_then(|e| e.value().as_integer()) {
                        obj.insert(
                            "compute_node_wait_for_new_jobs_seconds".to_string(),
                            serde_json::Value::Number(serde_json::Number::from(v as i64)),
                        );
                    }
                }
                "compute_node_ignore_workflow_completion" => {
                    if let Some(v) = node.entries().first().and_then(|e| e.value().as_bool()) {
                        obj.insert(
                            "compute_node_ignore_workflow_completion".to_string(),
                            serde_json::Value::Bool(v),
                        );
                    }
                }
                "compute_node_wait_for_healthy_database_minutes" => {
                    if let Some(v) = node.entries().first().and_then(|e| e.value().as_integer()) {
                        obj.insert(
                            "compute_node_wait_for_healthy_database_minutes".to_string(),
                            serde_json::Value::Number(serde_json::Number::from(v as i64)),
                        );
                    }
                }
                "jobs_sort_method" => {
                    if let Some(v) = node.entries().first().and_then(|e| e.value().as_string()) {
                        obj.insert(
                            "jobs_sort_method".to_string(),
                            serde_json::Value::String(v.to_string()),
                        );
                    }
                }
                "parameters" => {
                    if let Some(params) = Self::kdl_parameters_to_json(node)? {
                        obj.insert("parameters".to_string(), params);
                    }
                }
                "job" => {
                    jobs.push(Self::kdl_job_to_json(node)?);
                }
                "file" => {
                    files.push(Self::kdl_file_to_json(node)?);
                }
                "user_data" => {
                    user_data.push(Self::kdl_user_data_to_json(node)?);
                }
                "resource_requirements" => {
                    resource_requirements.push(Self::kdl_resource_requirements_to_json(node)?);
                }
                "failure_handler" => {
                    failure_handlers.push(Self::kdl_failure_handler_to_json(node)?);
                }
                "slurm_scheduler" => {
                    slurm_schedulers.push(Self::kdl_slurm_scheduler_to_json(node)?);
                }
                "action" => {
                    actions.push(Self::kdl_action_to_json(node)?);
                }
                "resource_monitor" => {
                    obj.insert(
                        "resource_monitor".to_string(),
                        Self::kdl_resource_monitor_to_json(node)?,
                    );
                }
                "slurm_defaults" => {
                    obj.insert(
                        "slurm_defaults".to_string(),
                        Self::kdl_slurm_defaults_to_json(node)?,
                    );
                }
                "execution_config" => {
                    obj.insert(
                        "execution_config".to_string(),
                        Self::kdl_execution_config_to_json(node)?,
                    );
                }
                "use_pending_failed" => {
                    if let Some(v) = node.entries().first().and_then(|e| e.value().as_bool()) {
                        obj.insert("use_pending_failed".to_string(), serde_json::Value::Bool(v));
                    }
                }
                _ => {
                    // Ignore unknown nodes
                }
            }
        }

        // Add collected arrays - jobs is required (can be empty), others are optional
        obj.insert("jobs".to_string(), serde_json::Value::Array(jobs));
        if !files.is_empty() {
            obj.insert("files".to_string(), serde_json::Value::Array(files));
        }
        if !user_data.is_empty() {
            obj.insert("user_data".to_string(), serde_json::Value::Array(user_data));
        }
        if !resource_requirements.is_empty() {
            obj.insert(
                "resource_requirements".to_string(),
                serde_json::Value::Array(resource_requirements),
            );
        }
        if !failure_handlers.is_empty() {
            obj.insert(
                "failure_handlers".to_string(),
                serde_json::Value::Array(failure_handlers),
            );
        }
        if !slurm_schedulers.is_empty() {
            obj.insert(
                "slurm_schedulers".to_string(),
                serde_json::Value::Array(slurm_schedulers),
            );
        }
        if !actions.is_empty() {
            obj.insert("actions".to_string(), serde_json::Value::Array(actions));
        }

        Ok(serde_json::Value::Object(obj))
    }

    /// Serialize WorkflowSpec to KDL format
    #[cfg(feature = "client")]
    pub fn to_kdl_str(&self) -> String {
        let mut lines = Vec::new();

        // Helper to escape strings for KDL
        fn kdl_escape(s: &str) -> String {
            // Use raw strings for multi-line or strings with special chars
            if s.contains('\n') || s.contains('"') || s.contains('\\') {
                // Count the number of # needed for raw string
                let mut hashes = 0;
                loop {
                    let delimiter: String = std::iter::repeat_n('#', hashes).collect();
                    if !s.contains(&format!("\"{}", delimiter)) {
                        break;
                    }
                    hashes += 1;
                }
                let delimiter: String = std::iter::repeat_n('#', hashes).collect();
                // KDL raw string format: r#"..."# where # count can vary
                format!("r{}\"{}\"{}", delimiter, s, delimiter)
            } else {
                format!("\"{}\"", s)
            }
        }

        // Top-level fields
        lines.push(format!("name {}", kdl_escape(&self.name)));
        if let Some(ref user) = self.user {
            lines.push(format!("user {}", kdl_escape(user)));
        }
        if let Some(ref desc) = self.description {
            lines.push(format!("description {}", kdl_escape(desc)));
        }
        if let Some(val) = self.compute_node_expiration_buffer_seconds {
            lines.push(format!("compute_node_expiration_buffer_seconds {}", val));
        }
        if let Some(val) = self.compute_node_wait_for_new_jobs_seconds {
            lines.push(format!("compute_node_wait_for_new_jobs_seconds {}", val));
        }
        if let Some(val) = self.compute_node_ignore_workflow_completion {
            lines.push(format!(
                "compute_node_ignore_workflow_completion {}",
                if val { "#true" } else { "#false" }
            ));
        }
        if let Some(val) = self.compute_node_wait_for_healthy_database_minutes {
            lines.push(format!(
                "compute_node_wait_for_healthy_database_minutes {}",
                val
            ));
        }
        if let Some(ref method) = self.jobs_sort_method {
            let method_str = match method {
                models::ClaimJobsSortMethod::GpusRuntimeMemory => "gpus_runtime_memory",
                models::ClaimJobsSortMethod::GpusMemoryRuntime => "gpus_memory_runtime",
                models::ClaimJobsSortMethod::None => "none",
            };
            lines.push(format!("jobs_sort_method \"{}\"", method_str));
        }

        // Parameters
        if let Some(ref params) = self.parameters
            && !params.is_empty()
        {
            lines.push("parameters {".to_string());
            for (key, value) in params {
                lines.push(format!("    {} {}", key, kdl_escape(value)));
            }
            lines.push("}".to_string());
        }

        lines.push(String::new()); // Empty line for readability

        // Files
        if let Some(ref files) = self.files {
            for file in files {
                Self::file_spec_to_kdl(&mut lines, file, &kdl_escape);
            }
            if !files.is_empty() {
                lines.push(String::new());
            }
        }

        // User data
        if let Some(ref user_data) = self.user_data {
            for ud in user_data {
                Self::user_data_spec_to_kdl(&mut lines, ud, &kdl_escape);
            }
            if !user_data.is_empty() {
                lines.push(String::new());
            }
        }

        // Resource requirements
        if let Some(ref reqs) = self.resource_requirements {
            for req in reqs {
                Self::resource_requirements_spec_to_kdl(&mut lines, req, &kdl_escape);
            }
            if !reqs.is_empty() {
                lines.push(String::new());
            }
        }

        // Resource monitor
        if let Some(ref monitor) = self.resource_monitor {
            lines.push("resource_monitor {".to_string());
            lines.push(format!(
                "    enabled {}",
                if monitor.enabled { "#true" } else { "#false" }
            ));
            let granularity = match monitor.granularity {
                crate::client::resource_monitor::MonitorGranularity::Summary => "summary",
                crate::client::resource_monitor::MonitorGranularity::TimeSeries => "time_series",
            };
            lines.push(format!("    granularity \"{}\"", granularity));
            lines.push(format!(
                "    sample_interval_seconds {}",
                monitor.sample_interval_seconds
            ));
            lines.push(format!(
                "    generate_plots {}",
                if monitor.generate_plots {
                    "#true"
                } else {
                    "#false"
                }
            ));
            lines.push("}".to_string());
            lines.push(String::new());
        }

        // Execution config
        if let Some(ref exec_config) = self.execution_config {
            lines.push("execution_config {".to_string());
            match exec_config.mode {
                ExecutionMode::Direct => lines.push("    mode \"direct\"".to_string()),
                ExecutionMode::Slurm => lines.push("    mode \"slurm\"".to_string()),
                ExecutionMode::Auto => lines.push("    mode \"auto\"".to_string()),
            }
            if let Some(limit) = exec_config.limit_resources {
                lines.push(format!(
                    "    limit_resources {}",
                    if limit { "#true" } else { "#false" }
                ));
            }
            if let Some(ref signal) = exec_config.termination_signal {
                lines.push(format!("    termination_signal {}", kdl_escape(signal)));
            }
            if let Some(secs) = exec_config.sigterm_lead_seconds {
                lines.push(format!("    sigterm_lead_seconds {}", secs));
            }
            if let Some(secs) = exec_config.sigkill_headroom_seconds {
                lines.push(format!("    sigkill_headroom_seconds {}", secs));
            }
            if let Some(code) = exec_config.timeout_exit_code {
                lines.push(format!("    timeout_exit_code {}", code));
            }
            if let Some(code) = exec_config.oom_exit_code {
                lines.push(format!("    oom_exit_code {}", code));
            }
            if let Some(ref signal) = exec_config.srun_termination_signal {
                lines.push(format!(
                    "    srun_termination_signal {}",
                    kdl_escape(signal)
                ));
            }
            if let Some(bind) = exec_config.enable_cpu_bind {
                lines.push(format!(
                    "    enable_cpu_bind {}",
                    if bind { "#true" } else { "#false" }
                ));
            }
            if let Some(ref stdio) = exec_config.stdio {
                Self::stdio_config_to_kdl(&mut lines, stdio, "    ");
            }
            lines.push("}".to_string());
            lines.push(String::new());
        }

        // Jobs
        for job in &self.jobs {
            Self::job_spec_to_kdl(&mut lines, job, &kdl_escape);
        }
        if !self.jobs.is_empty() {
            lines.push(String::new());
        }

        // Slurm schedulers (placed after jobs since they may be auto-generated)
        if let Some(ref schedulers) = self.slurm_schedulers {
            for sched in schedulers {
                Self::slurm_scheduler_spec_to_kdl(&mut lines, sched, &kdl_escape);
            }
            if !schedulers.is_empty() {
                lines.push(String::new());
            }
        }

        // Actions (placed last since they may be auto-generated)
        if let Some(ref actions) = self.actions {
            for action in actions {
                Self::action_spec_to_kdl(&mut lines, action, &kdl_escape);
            }
        }

        lines.join("\n")
    }

    /// Serialize a `StdioConfig` to KDL lines with a given indent prefix.
    #[cfg(feature = "client")]
    fn stdio_config_to_kdl(lines: &mut Vec<String>, stdio: &StdioConfig, indent: &str) {
        lines.push(format!("{}stdio {{", indent));
        let mode_str = match stdio.mode {
            StdioMode::Separate => "separate",
            StdioMode::Combined => "combined",
            StdioMode::NoStdout => "no_stdout",
            StdioMode::NoStderr => "no_stderr",
            StdioMode::None => "none",
        };
        lines.push(format!("{}    mode \"{}\"", indent, mode_str));
        if let Some(delete) = stdio.delete_on_success {
            lines.push(format!(
                "{}    delete_on_success {}",
                indent,
                if delete { "#true" } else { "#false" }
            ));
        }
        lines.push(format!("{}}}", indent));
    }

    #[cfg(feature = "client")]
    fn file_spec_to_kdl(lines: &mut Vec<String>, file: &FileSpec, escape: &dyn Fn(&str) -> String) {
        let has_params = file
            .parameters
            .as_ref()
            .map(|p| !p.is_empty())
            .unwrap_or(false);
        let has_mode = file.parameter_mode.is_some();
        let has_use_params = file.use_parameters.is_some();

        if !has_params && !has_mode && !has_use_params {
            // Simple form: file "name" path="value"
            lines.push(format!(
                "file {} path={}",
                escape(&file.name),
                escape(&file.path)
            ));
        } else {
            lines.push(format!("file {} {{", escape(&file.name)));
            lines.push(format!("    path {}", escape(&file.path)));
            if let Some(ref params) = file.parameters
                && !params.is_empty()
            {
                lines.push("    parameters {".to_string());
                for (key, value) in params {
                    lines.push(format!("        {} {}", key, escape(value)));
                }
                lines.push("    }".to_string());
            }
            if let Some(ref mode) = file.parameter_mode {
                lines.push(format!("    parameter_mode {}", escape(mode)));
            }
            if let Some(ref use_params) = file.use_parameters {
                for param in use_params {
                    lines.push(format!("    use_parameter {}", escape(param)));
                }
            }
            lines.push("}".to_string());
        }
    }

    #[cfg(feature = "client")]
    fn user_data_spec_to_kdl(
        lines: &mut Vec<String>,
        ud: &UserDataSpec,
        escape: &dyn Fn(&str) -> String,
    ) {
        let name = ud.name.as_deref().unwrap_or("unnamed");
        lines.push(format!("user_data {} {{", escape(name)));
        if ud.is_ephemeral.unwrap_or(false) {
            lines.push("    is_ephemeral #true".to_string());
        }
        if let Some(ref data) = ud.data {
            // Serialize JSON value to string
            let data_str = serde_json::to_string(data).unwrap_or_default();
            lines.push(format!("    data {}", escape(&data_str)));
        }
        lines.push("}".to_string());
    }

    #[cfg(feature = "client")]
    fn resource_requirements_spec_to_kdl(
        lines: &mut Vec<String>,
        req: &ResourceRequirementsSpec,
        escape: &dyn Fn(&str) -> String,
    ) {
        lines.push(format!("resource_requirements {} {{", escape(&req.name)));
        lines.push(format!("    num_cpus {}", req.num_cpus));
        lines.push(format!("    num_gpus {}", req.num_gpus));
        lines.push(format!("    num_nodes {}", req.num_nodes));
        lines.push(format!("    memory {}", escape(&req.memory)));
        lines.push(format!("    runtime {}", escape(&req.runtime)));
        lines.push("}".to_string());
    }

    #[cfg(feature = "client")]
    fn slurm_scheduler_spec_to_kdl(
        lines: &mut Vec<String>,
        sched: &SlurmSchedulerSpec,
        escape: &dyn Fn(&str) -> String,
    ) {
        if let Some(ref name) = sched.name {
            lines.push(format!("slurm_scheduler {} {{", escape(name)));
        } else {
            lines.push("slurm_scheduler {".to_string());
        }
        lines.push(format!("    account {}", escape(&sched.account)));
        if let Some(ref gres) = sched.gres {
            lines.push(format!("    gres {}", escape(gres)));
        }
        if let Some(ref mem) = sched.mem {
            lines.push(format!("    mem {}", escape(mem)));
        }
        lines.push(format!("    nodes {}", sched.nodes));
        if let Some(ntasks) = sched.ntasks_per_node {
            lines.push(format!("    ntasks_per_node {}", ntasks));
        }
        if let Some(ref partition) = sched.partition {
            lines.push(format!("    partition {}", escape(partition)));
        }
        if let Some(ref qos) = sched.qos {
            lines.push(format!("    qos {}", escape(qos)));
        }
        if let Some(ref tmp) = sched.tmp {
            lines.push(format!("    tmp {}", escape(tmp)));
        }
        lines.push(format!("    walltime {}", escape(&sched.walltime)));
        if let Some(ref extra) = sched.extra {
            lines.push(format!("    extra {}", escape(extra)));
        }
        lines.push("}".to_string());
    }

    #[cfg(feature = "client")]
    fn action_spec_to_kdl(
        lines: &mut Vec<String>,
        action: &WorkflowActionSpec,
        escape: &dyn Fn(&str) -> String,
    ) {
        lines.push("action {".to_string());
        lines.push(format!("    trigger_type {}", escape(&action.trigger_type)));
        lines.push(format!("    action_type {}", escape(&action.action_type)));
        if let Some(ref jobs) = action.jobs {
            for job in jobs {
                lines.push(format!("    job {}", escape(job)));
            }
        }
        if let Some(ref regexes) = action.job_name_regexes {
            for regex in regexes {
                lines.push(format!("    job_name_regexes {}", escape(regex)));
            }
        }
        if let Some(ref commands) = action.commands {
            for cmd in commands {
                lines.push(format!("    command {}", escape(cmd)));
            }
        }
        if let Some(ref scheduler) = action.scheduler {
            lines.push(format!("    scheduler {}", escape(scheduler)));
        }
        if let Some(ref scheduler_type) = action.scheduler_type {
            lines.push(format!("    scheduler_type {}", escape(scheduler_type)));
        }
        if let Some(count) = action.num_allocations {
            lines.push(format!("    num_allocations {}", count));
        }
        if let Some(val) = action.start_one_worker_per_node {
            lines.push(format!(
                "    start_one_worker_per_node {}",
                if val { "#true" } else { "#false" }
            ));
        }
        if let Some(max) = action.max_parallel_jobs {
            lines.push(format!("    max_parallel_jobs {}", max));
        }
        if let Some(val) = action.persistent {
            lines.push(format!(
                "    persistent {}",
                if val { "#true" } else { "#false" }
            ));
        }
        lines.push("}".to_string());
    }

    #[cfg(feature = "client")]
    fn job_spec_to_kdl(lines: &mut Vec<String>, job: &JobSpec, escape: &dyn Fn(&str) -> String) {
        lines.push(format!("job {} {{", escape(&job.name)));
        lines.push(format!("    command {}", escape(&job.command)));
        if let Some(ref script) = job.invocation_script {
            lines.push(format!("    invocation_script {}", escape(script)));
        }
        if let Some(val) = job.cancel_on_blocking_job_failure {
            lines.push(format!(
                "    cancel_on_blocking_job_failure {}",
                if val { "#true" } else { "#false" }
            ));
        }
        if let Some(val) = job.supports_termination {
            lines.push(format!(
                "    supports_termination {}",
                if val { "#true" } else { "#false" }
            ));
        }
        if let Some(ref req) = job.resource_requirements {
            lines.push(format!("    resource_requirements {}", escape(req)));
        }
        if let Some(ref deps) = job.depends_on {
            for dep in deps {
                lines.push(format!("    depends_on {}", escape(dep)));
            }
        }
        if let Some(ref regexes) = job.depends_on_regexes {
            for regex in regexes {
                lines.push(format!("    depends_on_regexes {}", escape(regex)));
            }
        }
        if let Some(ref files) = job.input_files {
            for file in files {
                lines.push(format!("    input_file {}", escape(file)));
            }
        }
        if let Some(ref files) = job.output_files {
            for file in files {
                lines.push(format!("    output_file {}", escape(file)));
            }
        }
        if let Some(ref ud) = job.input_user_data {
            for name in ud {
                lines.push(format!("    input_user_data {}", escape(name)));
            }
        }
        if let Some(ref ud) = job.output_user_data {
            for name in ud {
                lines.push(format!("    output_user_data {}", escape(name)));
            }
        }
        if let Some(ref sched) = job.scheduler {
            lines.push(format!("    scheduler {}", escape(sched)));
        }
        if let Some(ref params) = job.parameters
            && !params.is_empty()
        {
            lines.push("    parameters {".to_string());
            for (key, value) in params {
                lines.push(format!("        {} {}", key, escape(value)));
            }
            lines.push("    }".to_string());
        }
        if let Some(ref stdio) = job.stdio {
            Self::stdio_config_to_kdl(lines, stdio, "    ");
        }
        lines.push("}".to_string());
    }

    /// Deserialize a WorkflowSpec from a specification file (JSON, JSON5, YAML, or KDL)
    /// All formats are first converted to serde_json::Value, then to WorkflowSpec,
    /// ensuring consistent behavior across all file formats.
    pub fn from_spec_file<P: AsRef<Path>>(
        path: P,
    ) -> Result<WorkflowSpec, Box<dyn std::error::Error>> {
        let path_ref = path.as_ref();
        let file_content = fs::read_to_string(path_ref)?;

        // Determine file type based on extension
        let extension = path_ref
            .extension()
            .and_then(|ext| ext.to_str())
            .unwrap_or("");

        // Parse to JSON Value first, then convert to WorkflowSpec
        // This ensures consistent behavior across all formats
        let json_value: serde_json::Value = match extension.to_lowercase().as_str() {
            "json" => serde_json::from_str(&file_content)?,
            "json5" => json5::from_str(&file_content)?,
            "yaml" | "yml" => serde_yaml::from_str(&file_content)?,
            #[cfg(feature = "client")]
            "kdl" => Self::kdl_to_json_value(&file_content)?,
            _ => {
                // Try to parse as JSON first, then JSON5, then YAML, then KDL
                if let Ok(value) = serde_json::from_str::<serde_json::Value>(&file_content) {
                    value
                } else if let Ok(value) = json5::from_str::<serde_json::Value>(&file_content) {
                    value
                } else if let Ok(value) = serde_yaml::from_str::<serde_json::Value>(&file_content) {
                    value
                } else {
                    #[cfg(feature = "client")]
                    {
                        Self::kdl_to_json_value(&file_content)?
                    }
                    #[cfg(not(feature = "client"))]
                    {
                        return Err("Unable to parse workflow spec file".into());
                    }
                }
            }
        };

        Self::from_json_value(json_value)
    }

    /// Deserialize a WorkflowSpec from string content with a specified format
    /// Useful for testing or when content is already loaded
    /// All formats are first converted to serde_json::Value, then to WorkflowSpec,
    /// ensuring consistent behavior across all file formats.
    ///
    /// # Arguments
    /// * `content` - The workflow spec content as a string
    /// * `format` - The format type: "json", "json5", "yaml", "yml", or "kdl"
    pub fn from_spec_file_content(
        content: &str,
        format: &str,
    ) -> Result<WorkflowSpec, Box<dyn std::error::Error>> {
        // Parse to JSON Value first, then convert to WorkflowSpec
        let json_value: serde_json::Value = match format.to_lowercase().as_str() {
            "json" => serde_json::from_str(content)?,
            "json5" => json5::from_str(content)?,
            "yaml" | "yml" => serde_yaml::from_str(content)?,
            #[cfg(feature = "client")]
            "kdl" => Self::kdl_to_json_value(content)?,
            #[cfg(not(feature = "client"))]
            "kdl" => return Err("KDL format requires 'client' feature".into()),
            _ => return Err(format!("Unknown format: {}", format).into()),
        };

        Self::from_json_value(json_value)
    }

    /// Perform variable substitution on job commands and invocation scripts
    /// Supported variables:
    /// - ${files.input.NAME} - input file (automatically adds to input_files)
    /// - ${files.output.NAME} - output file (automatically adds to output_files)
    /// - ${user_data.input.NAME} - input user data (automatically adds to input_user_data)
    /// - ${user_data.output.NAME} - output user data (automatically adds to output_user_data)
    pub fn substitute_variables(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        // Build file name to path mapping
        let mut file_name_to_path = HashMap::new();
        if let Some(files) = &self.files {
            for file_spec in files {
                file_name_to_path.insert(file_spec.name.clone(), file_spec.path.clone());
            }
        }

        // Build user data name to data mapping
        let mut user_data_name_to_data = HashMap::new();
        if let Some(user_data_list) = &self.user_data {
            for user_data_spec in user_data_list {
                if let Some(name) = &user_data_spec.name
                    && let Some(data) = &user_data_spec.data
                {
                    user_data_name_to_data.insert(name.clone(), data.clone());
                }
            }
        }

        // Substitute variables in each job and extract dependencies
        for job in &mut self.jobs {
            let (new_command, input_files, output_files, input_user_data, output_user_data) =
                Self::substitute_and_extract(
                    &job.command,
                    &file_name_to_path,
                    &user_data_name_to_data,
                )?;
            job.command = new_command;

            // Set input/output file names from extracted dependencies
            if !input_files.is_empty() {
                job.input_files = Some(input_files);
            }
            if !output_files.is_empty() {
                job.output_files = Some(output_files);
            }
            if !input_user_data.is_empty() {
                job.input_user_data = Some(input_user_data);
            }
            if !output_user_data.is_empty() {
                job.output_user_data = Some(output_user_data);
            }

            // Process invocation script if present
            if let Some(script) = &job.invocation_script {
                let (
                    new_script,
                    script_input_files,
                    script_output_files,
                    script_input_user_data,
                    script_output_user_data,
                ) = Self::substitute_and_extract(
                    script,
                    &file_name_to_path,
                    &user_data_name_to_data,
                )?;
                job.invocation_script = Some(new_script);

                // Merge dependencies from invocation script
                if !script_input_files.is_empty() {
                    let mut combined = job.input_files.clone().unwrap_or_default();
                    combined.extend(script_input_files);
                    combined.sort();
                    combined.dedup();
                    job.input_files = Some(combined);
                }
                if !script_output_files.is_empty() {
                    let mut combined = job.output_files.clone().unwrap_or_default();
                    combined.extend(script_output_files);
                    combined.sort();
                    combined.dedup();
                    job.output_files = Some(combined);
                }
                if !script_input_user_data.is_empty() {
                    let mut combined = job.input_user_data.clone().unwrap_or_default();
                    combined.extend(script_input_user_data);
                    combined.sort();
                    combined.dedup();
                    job.input_user_data = Some(combined);
                }
                if !script_output_user_data.is_empty() {
                    let mut combined = job.output_user_data.clone().unwrap_or_default();
                    combined.extend(script_output_user_data);
                    combined.sort();
                    combined.dedup();
                    job.output_user_data = Some(combined);
                }
            }
        }

        Ok(())
    }

    /// Substitute variables and extract input/output dependencies
    /// Returns: (substituted_string, input_files, output_files, input_user_data, output_user_data)
    #[allow(clippy::type_complexity)]
    fn substitute_and_extract(
        input: &str,
        file_name_to_path: &HashMap<String, String>,
        user_data_name_to_data: &HashMap<String, serde_json::Value>,
    ) -> Result<
        (String, Vec<String>, Vec<String>, Vec<String>, Vec<String>),
        Box<dyn std::error::Error>,
    > {
        let mut result = input.to_string();
        let mut input_files = Vec::new();
        let mut output_files = Vec::new();
        let mut input_user_data = Vec::new();
        let mut output_user_data = Vec::new();

        // Extract and replace ${files.input.NAME}
        for (name, path) in file_name_to_path {
            let input_pattern = format!("${{files.input.{}}}", name);
            if result.contains(&input_pattern) {
                result = result.replace(&input_pattern, path);
                input_files.push(name.clone());
            }
        }

        // Extract and replace ${files.output.NAME}
        for (name, path) in file_name_to_path {
            let output_pattern = format!("${{files.output.{}}}", name);
            if result.contains(&output_pattern) {
                result = result.replace(&output_pattern, path);
                output_files.push(name.clone());
            }
        }

        // Extract and replace ${user_data.input.NAME}
        for (name, data) in user_data_name_to_data {
            let input_pattern = format!("${{user_data.input.{}}}", name);
            if result.contains(&input_pattern) {
                let data_str = serde_json::to_string(data)?;
                result = result.replace(&input_pattern, &data_str);
                input_user_data.push(name.clone());
            }
        }

        // Extract and replace ${user_data.output.NAME}
        for (name, data) in user_data_name_to_data {
            let output_pattern = format!("${{user_data.output.{}}}", name);
            if result.contains(&output_pattern) {
                let data_str = serde_json::to_string(data)?;
                result = result.replace(&output_pattern, &data_str);
                output_user_data.push(name.clone());
            }
        }

        Ok((
            result,
            input_files,
            output_files,
            input_user_data,
            output_user_data,
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_kdl_job_parameterization() {
        let kdl_content = r#"
name "test_parameterized"
description "Test parameterized jobs in KDL format"

job "job_{i:03d}" {
    command "echo hello {i}"
    parameters {
        i "1:5"
    }
}
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(kdl_content, "kdl")
            .expect("Failed to parse KDL workflow spec");

        // Before expansion, should have 1 job with parameters
        assert_eq!(spec.jobs.len(), 1);
        assert!(spec.jobs[0].parameters.is_some());

        // Expand parameters
        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // After expansion, should have 5 jobs
        assert_eq!(spec.jobs.len(), 5);
        assert_eq!(spec.jobs[0].name, "job_001");
        assert_eq!(spec.jobs[0].command, "echo hello 1");
        assert_eq!(spec.jobs[4].name, "job_005");
        assert_eq!(spec.jobs[4].command, "echo hello 5");

        // Parameters should be removed from expanded jobs
        for job in &spec.jobs {
            assert!(job.parameters.is_none());
        }
    }

    #[test]
    fn test_kdl_file_parameterization() {
        let kdl_content = r#"
name "test_parameterized_files"
description "Test parameterized files in KDL format"

file "output_{run_id}" {
    path "/data/output_{run_id}.txt"
    parameters {
        run_id "1:3"
    }
}

job "process" {
    command "echo test"
}
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(kdl_content, "kdl")
            .expect("Failed to parse KDL workflow spec");

        // Before expansion, should have 1 file with parameters
        assert_eq!(spec.files.as_ref().unwrap().len(), 1);
        assert!(spec.files.as_ref().unwrap()[0].parameters.is_some());

        // Expand parameters
        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // After expansion, should have 3 files
        let files = spec.files.as_ref().unwrap();
        assert_eq!(files.len(), 3);
        assert_eq!(files[0].name, "output_1");
        assert_eq!(files[0].path, "/data/output_1.txt");
        assert_eq!(files[2].name, "output_3");
        assert_eq!(files[2].path, "/data/output_3.txt");

        // Parameters should be removed from expanded files
        for file in files {
            assert!(file.parameters.is_none());
        }
    }

    #[test]
    fn test_kdl_multi_dimensional_parameterization() {
        let kdl_content = r#"
name "test_multi_param"
description "Test multi-dimensional parameterization in KDL format"

job "train_lr{lr:.4f}_bs{batch_size}" {
    command "python train.py --lr={lr} --batch-size={batch_size}"
    parameters {
        lr "[0.001,0.01]"
        batch_size "[16,32]"
    }
}
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(kdl_content, "kdl")
            .expect("Failed to parse KDL workflow spec");

        // Expand parameters
        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have 2 * 2 = 4 jobs
        assert_eq!(spec.jobs.len(), 4);

        // Verify all expected combinations exist
        let names: Vec<&str> = spec.jobs.iter().map(|j| j.name.as_str()).collect();
        assert!(names.contains(&"train_lr0.0010_bs16"));
        assert!(names.contains(&"train_lr0.0010_bs32"));
        assert!(names.contains(&"train_lr0.0100_bs16"));
        assert!(names.contains(&"train_lr0.0100_bs32"));
    }

    #[test]
    fn test_kdl_example_file_hundred_jobs() {
        // Test parsing the actual KDL example file
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        let path = PathBuf::from(manifest_dir).join("examples/kdl/hundred_jobs_parameterized.kdl");

        let mut spec =
            WorkflowSpec::from_spec_file(&path).expect("Failed to parse KDL example file");

        assert_eq!(spec.name, "hundred_jobs_parameterized");
        // 2 jobs before expansion: parameterized job template + postprocess
        assert_eq!(spec.jobs.len(), 2);
        assert!(spec.jobs[0].parameters.is_some());

        // Expand parameters
        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have 101 jobs after expansion: 100 parameterized + 1 postprocess
        assert_eq!(spec.jobs.len(), 101);
        assert_eq!(spec.jobs[0].name, "job_001");
        assert_eq!(spec.jobs[99].name, "job_100");
        assert_eq!(spec.jobs[100].name, "postprocess");
    }

    #[test]
    fn test_kdl_example_file_hyperparameter_sweep() {
        // Test parsing the actual KDL hyperparameter sweep example
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        let path = PathBuf::from(manifest_dir).join("examples/kdl/hyperparameter_sweep.kdl");

        let mut spec = WorkflowSpec::from_spec_file(&path)
            .expect("Failed to parse KDL hyperparameter sweep file");

        assert_eq!(spec.name, "hyperparameter_sweep");

        // Before expansion: 4 jobs (prepare_train, prepare_val, train template, aggregate template)
        assert_eq!(spec.jobs.len(), 4);

        // Before expansion: 4 files (train_data, val_data, model template, metrics template)
        assert_eq!(spec.files.as_ref().unwrap().len(), 4);

        // Expand parameters
        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // After expansion:
        // - 2 prepare jobs (unchanged)
        // - 18 training jobs (3 lr * 3 batch_size * 2 optimizer)
        // - 18 aggregate jobs (expanded from template)
        // Total: 2 + 18 + 18 = 38 jobs
        assert_eq!(spec.jobs.len(), 38);

        // Files after expansion:
        // - 2 data files (unchanged)
        // - 18 model files (parameterized)
        // - 18 metrics files (parameterized)
        // Total: 2 + 18 + 18 = 38 files
        assert_eq!(spec.files.as_ref().unwrap().len(), 38);
    }

    #[test]
    fn test_integer_range_expansion() {
        let mut job = JobSpec::new("job_{i}".to_string(), "echo {i}".to_string());

        let mut params = HashMap::new();
        params.insert("i".to_string(), "1:5".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(expanded.len(), 5);
        assert_eq!(expanded[0].name, "job_1");
        assert_eq!(expanded[0].command, "echo 1");
        assert_eq!(expanded[4].name, "job_5");
        assert_eq!(expanded[4].command, "echo 5");
    }

    #[test]
    fn test_integer_range_with_step() {
        let mut job = JobSpec::new("job_{i}".to_string(), "echo {i}".to_string());

        let mut params = HashMap::new();
        params.insert("i".to_string(), "0:10:2".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(expanded.len(), 6);
        assert_eq!(expanded[0].name, "job_0");
        assert_eq!(expanded[1].name, "job_2");
        assert_eq!(expanded[5].name, "job_10");
    }

    #[test]
    fn test_float_range_expansion() {
        let mut job = JobSpec::new("job_{lr}".to_string(), "train.py --lr={lr}".to_string());

        let mut params = HashMap::new();
        params.insert("lr".to_string(), "0.0:1.0:0.5".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(expanded.len(), 3);
        assert_eq!(expanded[0].command, "train.py --lr=0");
        assert_eq!(expanded[1].command, "train.py --lr=0.5");
        assert_eq!(expanded[2].command, "train.py --lr=1");
    }

    #[test]
    fn test_list_expansion() {
        let mut job = JobSpec::new(
            "job_{dataset}".to_string(),
            "process.sh {dataset}".to_string(),
        );

        let mut params = HashMap::new();
        params.insert(
            "dataset".to_string(),
            "['train','test','validation']".to_string(),
        );
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(expanded.len(), 3);
        assert_eq!(expanded[0].name, "job_train");
        assert_eq!(expanded[0].command, "process.sh train");
        assert_eq!(expanded[2].name, "job_validation");
    }

    #[test]
    fn test_multi_dimensional_parameter_sweep() {
        let mut job = JobSpec::new(
            "job_lr{lr}_bs{batch_size}".to_string(),
            "train.py --lr={lr} --batch-size={batch_size}".to_string(),
        );

        let mut params = HashMap::new();
        params.insert("lr".to_string(), "[0.001,0.01,0.1]".to_string());
        params.insert("batch_size".to_string(), "[16,32,64]".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        // Should generate 3 * 3 = 9 combinations
        assert_eq!(expanded.len(), 9);

        // Check a few combinations
        let names: Vec<&str> = expanded.iter().map(|j| j.name.as_str()).collect();
        assert!(names.contains(&"job_lr0.001_bs16"));
        assert!(names.contains(&"job_lr0.1_bs64"));

        let commands: Vec<&str> = expanded.iter().map(|j| j.command.as_str()).collect();
        assert!(commands.contains(&"train.py --lr=0.001 --batch-size=16"));
        assert!(commands.contains(&"train.py --lr=0.1 --batch-size=64"));
    }

    #[test]
    fn test_format_specifier_zero_padding() {
        let mut job = JobSpec::new("job_{i:03d}".to_string(), "echo {i:03d}".to_string());

        let mut params = HashMap::new();
        params.insert("i".to_string(), "1:5".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(expanded[0].name, "job_001");
        assert_eq!(expanded[0].command, "echo 001");
        assert_eq!(expanded[4].name, "job_005");
    }

    #[test]
    fn test_format_specifier_float_precision() {
        let mut job = JobSpec::new(
            "job_{lr:.2f}".to_string(),
            "train.py --lr={lr:.2f}".to_string(),
        );

        let mut params = HashMap::new();
        params.insert("lr".to_string(), "0.0:0.3:0.1".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(expanded[0].name, "job_0.00");
        assert_eq!(expanded[1].name, "job_0.10");
        assert_eq!(expanded[2].name, "job_0.20");
    }

    #[test]
    fn test_file_parameterization() {
        let mut file = FileSpec::new(
            "output_{run_id}".to_string(),
            "/data/output_{run_id}.txt".to_string(),
        );

        let mut params = HashMap::new();
        params.insert("run_id".to_string(), "1:3".to_string());
        file.parameters = Some(params);

        let expanded = file.expand().expect("Failed to expand file");

        assert_eq!(expanded.len(), 3);
        assert_eq!(expanded[0].name, "output_1");
        assert_eq!(expanded[0].path, "/data/output_1.txt");
        assert_eq!(expanded[2].name, "output_3");
        assert_eq!(expanded[2].path, "/data/output_3.txt");
    }

    #[test]
    fn test_job_with_input_output_files() {
        let mut job = JobSpec::new(
            "process_{i}".to_string(),
            "process.sh input_{i}.txt output_{i}.txt".to_string(),
        );
        job.input_files = Some(vec!["input_{i}".to_string()]);
        job.output_files = Some(vec!["output_{i}".to_string()]);

        let mut params = HashMap::new();
        params.insert("i".to_string(), "1:3".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(expanded.len(), 3);

        assert_eq!(expanded[0].name, "process_1");
        assert_eq!(expanded[0].input_files, Some(vec!["input_1".to_string()]));
        assert_eq!(expanded[0].output_files, Some(vec!["output_1".to_string()]));

        assert_eq!(expanded[2].name, "process_3");
        assert_eq!(expanded[2].input_files, Some(vec!["input_3".to_string()]));
        assert_eq!(expanded[2].output_files, Some(vec!["output_3".to_string()]));
    }

    #[test]
    fn test_job_with_depends_on_names() {
        let mut job = JobSpec::new(
            "dependent_{i}".to_string(),
            "echo dependent {i}".to_string(),
        );
        job.depends_on = Some(vec!["upstream_{i}".to_string()]);

        let mut params = HashMap::new();
        params.insert("i".to_string(), "1:3".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(expanded.len(), 3);
        assert_eq!(expanded[0].name, "dependent_1");
        assert_eq!(expanded[0].depends_on, Some(vec!["upstream_1".to_string()]));
        assert_eq!(expanded[2].name, "dependent_3");
        assert_eq!(expanded[2].depends_on, Some(vec!["upstream_3".to_string()]));
    }

    #[test]
    fn test_no_parameters_returns_original() {
        let job = JobSpec::new("simple_job".to_string(), "echo hello".to_string());

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(expanded.len(), 1);
        assert_eq!(expanded[0].name, "simple_job");
        assert_eq!(expanded[0].command, "echo hello");
    }

    #[test]
    fn test_invalid_range_format() {
        let mut job = JobSpec::new("job_{i}".to_string(), "echo {i}".to_string());

        let mut params = HashMap::new();
        params.insert("i".to_string(), "invalid:range:format:too:many".to_string());
        job.parameters = Some(params);

        let result = job.expand();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Invalid range format"));
    }

    #[test]
    fn test_zero_step_error() {
        let mut job = JobSpec::new("job_{i}".to_string(), "echo {i}".to_string());

        let mut params = HashMap::new();
        params.insert("i".to_string(), "1:10:0".to_string());
        job.parameters = Some(params);

        let result = job.expand();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Step cannot be zero"));
    }

    #[test]
    fn test_workflow_spec_expand_parameters() {
        let mut spec = WorkflowSpec {
            name: "test_workflow".to_string(),
            description: Some("Test workflow with parameters".to_string()),
            user: Some("test_user".to_string()),
            compute_node_expiration_buffer_seconds: None,
            compute_node_wait_for_healthy_database_minutes: None,
            compute_node_ignore_workflow_completion: None,
            compute_node_wait_for_new_jobs_seconds: None,
            jobs_sort_method: None,
            parameters: None,
            jobs: vec![JobSpec {
                name: "job_{i}".to_string(),
                command: "echo {i}".to_string(),
                invocation_script: None,
                cancel_on_blocking_job_failure: Some(false),
                supports_termination: Some(false),
                resource_requirements: None,
                scheduler: None,
                depends_on: None,
                depends_on_regexes: None,
                input_files: None,
                input_file_regexes: None,
                output_files: None,
                output_file_regexes: None,
                input_user_data: None,
                input_user_data_regexes: None,
                output_user_data: None,
                output_user_data_regexes: None,
                parameters: Some({
                    let mut params = HashMap::new();
                    params.insert("i".to_string(), "1:3".to_string());
                    params
                }),
                parameter_mode: None,
                use_parameters: None,
                failure_handler: None,
                stdio: None,
            }],
            files: Some(vec![{
                let mut file =
                    FileSpec::new("file_{i}".to_string(), "/data/file_{i}.txt".to_string());
                file.parameters = Some({
                    let mut params = HashMap::new();
                    params.insert("i".to_string(), "1:3".to_string());
                    params
                });
                file
            }]),
            user_data: None,
            resource_requirements: None,
            slurm_schedulers: None,
            slurm_defaults: None,
            resource_monitor: None,
            actions: None,
            failure_handlers: None,
            use_pending_failed: None,
            enable_ro_crate: None,
            project: None,
            metadata: None,
            execution_config: None,
        };

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Jobs should be expanded
        assert_eq!(spec.jobs.len(), 3);
        assert_eq!(spec.jobs[0].name, "job_1");
        assert_eq!(spec.jobs[2].name, "job_3");

        // Files should be expanded
        assert_eq!(spec.files.as_ref().unwrap().len(), 3);
        assert_eq!(spec.files.as_ref().unwrap()[0].name, "file_1");
        assert_eq!(spec.files.as_ref().unwrap()[2].name, "file_3");
    }

    #[test]
    fn test_complex_multi_param_with_dependencies() {
        let mut job = JobSpec::new(
            "train_lr{lr}_bs{bs}_epoch{epoch}".to_string(),
            "train.py --lr={lr} --bs={bs} --epochs={epoch}".to_string(),
        );
        job.input_files = Some(vec!["data_{bs}".to_string()]);
        job.output_files = Some(vec!["model_lr{lr}_bs{bs}_epoch{epoch}.pt".to_string()]);

        let mut params = HashMap::new();
        params.insert("lr".to_string(), "[0.001,0.01]".to_string());
        params.insert("bs".to_string(), "[16,32]".to_string());
        params.insert("epoch".to_string(), "[10,20]".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        // Should generate 2 * 2 * 2 = 8 combinations
        assert_eq!(expanded.len(), 8);

        // Check one specific combination
        let job_001_16_10 = expanded
            .iter()
            .find(|j| j.name == "train_lr0.001_bs16_epoch10")
            .expect("Expected job not found");

        assert_eq!(
            job_001_16_10.command,
            "train.py --lr=0.001 --bs=16 --epochs=10"
        );
        assert_eq!(job_001_16_10.input_files, Some(vec!["data_16".to_string()]));
        assert_eq!(
            job_001_16_10.output_files,
            Some(vec!["model_lr0.001_bs16_epoch10.pt".to_string()])
        );
    }

    #[test]
    fn test_invocation_script_substitution() {
        let mut job = JobSpec::new("job_{i}".to_string(), "python train.py".to_string());
        job.invocation_script = Some("#!/bin/bash\nexport RUN_ID={i}\n".to_string());

        let mut params = HashMap::new();
        params.insert("i".to_string(), "1:2".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(
            expanded[0].invocation_script,
            Some("#!/bin/bash\nexport RUN_ID=1\n".to_string())
        );
        assert_eq!(
            expanded[1].invocation_script,
            Some("#!/bin/bash\nexport RUN_ID=2\n".to_string())
        );
    }

    #[test]
    fn test_user_data_name_substitution() {
        let mut job = JobSpec::new("job_{stage}".to_string(), "process.sh {stage}".to_string());
        job.input_user_data = Some(vec!["config_{stage}".to_string()]);
        job.output_user_data = Some(vec!["results_{stage}".to_string()]);

        let mut params = HashMap::new();
        params.insert("stage".to_string(), "['train','test']".to_string());
        job.parameters = Some(params);

        let expanded = job.expand().expect("Failed to expand job");

        assert_eq!(expanded.len(), 2);
        assert_eq!(
            expanded[0].input_user_data,
            Some(vec!["config_train".to_string()])
        );
        assert_eq!(
            expanded[0].output_user_data,
            Some(vec!["results_train".to_string()])
        );
        assert_eq!(
            expanded[1].input_user_data,
            Some(vec!["config_test".to_string()])
        );
        assert_eq!(
            expanded[1].output_user_data,
            Some(vec!["results_test".to_string()])
        );
    }

    // ==================== Shared Parameters Tests ====================

    #[test]
    fn test_shared_parameters_yaml() {
        let yaml_content = r#"
name: shared_params_test
description: Test workflow-level shared parameters

parameters:
  i: "1:3"
  prefix: "['a','b']"

jobs:
  - name: job_{i}_{prefix}
    command: echo {i} {prefix}
    use_parameters:
      - i
      - prefix
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(yaml_content, "yaml")
            .expect("Failed to parse YAML workflow spec");

        // Verify workflow-level parameters were parsed
        assert!(spec.parameters.is_some());
        let params = spec.parameters.as_ref().unwrap();
        assert_eq!(params.get("i").unwrap(), "1:3");
        assert_eq!(params.get("prefix").unwrap(), "['a','b']");

        // Verify job has use_parameters
        assert!(spec.jobs[0].use_parameters.is_some());
        assert_eq!(spec.jobs[0].use_parameters.as_ref().unwrap().len(), 2);

        // Expand parameters
        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have 3 * 2 = 6 jobs
        assert_eq!(spec.jobs.len(), 6);

        // Check that all combinations exist
        let names: Vec<&str> = spec.jobs.iter().map(|j| j.name.as_str()).collect();
        assert!(names.contains(&"job_1_a"));
        assert!(names.contains(&"job_1_b"));
        assert!(names.contains(&"job_2_a"));
        assert!(names.contains(&"job_2_b"));
        assert!(names.contains(&"job_3_a"));
        assert!(names.contains(&"job_3_b"));
    }

    #[test]
    fn test_shared_parameters_kdl() {
        let kdl_content = r#"
name "shared_params_test"
description "Test workflow-level shared parameters in KDL"

parameters {
    i "1:3"
    prefix "['a','b']"
}

job "job_{i}_{prefix}" {
    command "echo {i} {prefix}"
    use_parameters "i" "prefix"
}
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(kdl_content, "kdl")
            .expect("Failed to parse KDL workflow spec");

        // Verify workflow-level parameters were parsed
        assert!(spec.parameters.is_some());
        let params = spec.parameters.as_ref().unwrap();
        assert_eq!(params.get("i").unwrap(), "1:3");
        assert_eq!(params.get("prefix").unwrap(), "['a','b']");

        // Verify job has use_parameters
        assert!(spec.jobs[0].use_parameters.is_some());

        // Expand parameters
        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have 3 * 2 = 6 jobs
        assert_eq!(spec.jobs.len(), 6);

        // Check that all combinations exist
        let names: Vec<&str> = spec.jobs.iter().map(|j| j.name.as_str()).collect();
        assert!(names.contains(&"job_1_a"));
        assert!(names.contains(&"job_3_b"));
    }

    #[test]
    fn test_shared_parameters_json5() {
        let json5_content = r#"
{
    name: "shared_params_test",
    description: "Test workflow-level shared parameters in JSON5",

    parameters: {
        i: "1:3",
        prefix: "['a','b']"
    },

    jobs: [
        {
            name: "job_{i}_{prefix}",
            command: "echo {i} {prefix}",
            use_parameters: ["i", "prefix"]
        }
    ]
}
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(json5_content, "json5")
            .expect("Failed to parse JSON5 workflow spec");

        // Verify workflow-level parameters were parsed
        assert!(spec.parameters.is_some());

        // Expand parameters
        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have 3 * 2 = 6 jobs
        assert_eq!(spec.jobs.len(), 6);
    }

    #[test]
    fn test_shared_parameters_selective_inheritance() {
        // Test that use_parameters only inherits specified parameters
        let yaml_content = r#"
name: selective_params_test
description: Test selective parameter inheritance

parameters:
  a: "1:2"
  b: "3:4"
  c: "5:6"

jobs:
  # This job should only use parameters a and b (4 jobs)
  - name: job_{a}_{b}
    command: echo {a} {b}
    use_parameters:
      - a
      - b
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(yaml_content, "yaml")
            .expect("Failed to parse YAML workflow spec");

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have 2 * 2 = 4 jobs (not using parameter c)
        assert_eq!(spec.jobs.len(), 4);

        // Check that only a and b were used
        let names: Vec<&str> = spec.jobs.iter().map(|j| j.name.as_str()).collect();
        assert!(names.contains(&"job_1_3"));
        assert!(names.contains(&"job_1_4"));
        assert!(names.contains(&"job_2_3"));
        assert!(names.contains(&"job_2_4"));
    }

    #[test]
    fn test_shared_parameters_with_files() {
        let yaml_content = r#"
name: file_params_test
description: Test shared parameters with files

parameters:
  i: "1:2"

files:
  - name: file_{i}
    path: /data/file_{i}.txt
    use_parameters:
      - i

jobs:
  - name: job_{i}
    command: process /data/file_{i}.txt
    input_files:
      - file_{i}
    use_parameters:
      - i
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(yaml_content, "yaml")
            .expect("Failed to parse YAML workflow spec");

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have 2 files
        assert_eq!(spec.files.as_ref().unwrap().len(), 2);
        let file_names: Vec<&str> = spec
            .files
            .as_ref()
            .unwrap()
            .iter()
            .map(|f| f.name.as_str())
            .collect();
        assert!(file_names.contains(&"file_1"));
        assert!(file_names.contains(&"file_2"));

        // Should have 2 jobs
        assert_eq!(spec.jobs.len(), 2);
    }

    #[test]
    fn test_local_parameters_override_shared() {
        // Test that local parameters take precedence over shared parameters
        let yaml_content = r#"
name: override_params_test
description: Test local parameters override shared

parameters:
  i: "1:5"

jobs:
  # This job uses local parameters (overrides shared)
  - name: job_{i}
    command: echo {i}
    parameters:
      i: "10:12"
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(yaml_content, "yaml")
            .expect("Failed to parse YAML workflow spec");

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have 3 jobs (from local 10:12), not 5 (from shared 1:5)
        assert_eq!(spec.jobs.len(), 3);

        // Check that local parameters were used
        let names: Vec<&str> = spec.jobs.iter().map(|j| j.name.as_str()).collect();
        assert!(names.contains(&"job_10"));
        assert!(names.contains(&"job_11"));
        assert!(names.contains(&"job_12"));
    }

    #[test]
    fn test_example_file_hyperparameter_sweep_shared_params_yaml() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("examples/yaml/hyperparameter_sweep_shared_params.yaml");

        let mut spec = WorkflowSpec::from_spec_file(&path)
            .expect("Failed to load hyperparameter_sweep_shared_params.yaml");

        // Verify workflow-level parameters were parsed
        assert!(spec.parameters.is_some());
        let params = spec.parameters.as_ref().unwrap();
        assert_eq!(params.len(), 3);
        assert!(params.contains_key("lr"));
        assert!(params.contains_key("batch_size"));
        assert!(params.contains_key("optimizer"));

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have same structure as non-shared version (hyperparameter_sweep.yaml):
        // - 2 prepare jobs (no parameters)
        // - 18 training jobs (3 lr * 3 batch_size * 2 optimizer)
        // - 18 aggregate jobs (expanded from template)
        // Total: 2 + 18 + 18 = 38 jobs
        assert_eq!(spec.jobs.len(), 38);

        // Files after expansion:
        // - 2 data files (no parameters)
        // - 18 model files (parameterized)
        // - 18 metrics files (parameterized)
        // Total: 2 + 18 + 18 = 38 files
        assert_eq!(spec.files.as_ref().unwrap().len(), 38);
    }

    #[test]
    fn test_example_file_hyperparameter_sweep_shared_params_kdl() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("examples/kdl/hyperparameter_sweep_shared_params.kdl");

        let mut spec = WorkflowSpec::from_spec_file(&path)
            .expect("Failed to load hyperparameter_sweep_shared_params.kdl");

        // Verify workflow-level parameters were parsed
        assert!(spec.parameters.is_some());

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have same structure as YAML version: 38 jobs, 38 files
        assert_eq!(spec.jobs.len(), 38);
        assert_eq!(spec.files.as_ref().unwrap().len(), 38);
    }

    #[test]
    fn test_example_file_hyperparameter_sweep_shared_params_json5() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("examples/json/hyperparameter_sweep_shared_params.json5");

        let mut spec = WorkflowSpec::from_spec_file(&path)
            .expect("Failed to load hyperparameter_sweep_shared_params.json5");

        // Verify workflow-level parameters were parsed
        assert!(spec.parameters.is_some());

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Should have same structure as YAML/KDL versions: 38 jobs, 38 files
        assert_eq!(spec.jobs.len(), 38);
        assert_eq!(spec.files.as_ref().unwrap().len(), 38);
    }

    // ==================== Zip Parameter Mode Tests ====================

    #[test]
    fn test_zip_parameter_mode_yaml() {
        let yaml_content = r#"
name: test_zip_parameters
description: Test zip parameter mode in YAML

jobs:
  - name: train_{dataset}_{model}
    command: python train.py --dataset={dataset} --model={model}
    parameters:
      dataset: "['cifar10', 'mnist', 'imagenet']"
      model: "['resnet', 'vgg', 'transformer']"
    parameter_mode: zip
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(yaml_content, "yaml")
            .expect("Failed to parse YAML workflow spec");

        // Before expansion, should have 1 job
        assert_eq!(spec.jobs.len(), 1);
        assert_eq!(spec.jobs[0].parameter_mode, Some("zip".to_string()));

        // Expand parameters
        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // With zip mode: 3 zipped pairs, not 9 combinations
        assert_eq!(spec.jobs.len(), 3);
        assert_eq!(spec.jobs[0].name, "train_cifar10_resnet");
        assert_eq!(spec.jobs[1].name, "train_mnist_vgg");
        assert_eq!(spec.jobs[2].name, "train_imagenet_transformer");

        // Parameters and parameter_mode should be removed from expanded jobs
        for job in &spec.jobs {
            assert!(job.parameters.is_none());
            assert!(job.parameter_mode.is_none());
        }
    }

    #[test]
    fn test_zip_parameter_mode_json() {
        let json_content = r#"
{
    "name": "test_zip_parameters",
    "jobs": [
        {
            "name": "process_{input}_{output}",
            "command": "convert {input} {output}",
            "parameters": {
                "input": "['a.txt', 'b.txt']",
                "output": "['a.out', 'b.out']"
            },
            "parameter_mode": "zip"
        }
    ]
}
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(json_content, "json")
            .expect("Failed to parse JSON workflow spec");

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // With zip mode: 2 zipped pairs
        assert_eq!(spec.jobs.len(), 2);
        assert_eq!(spec.jobs[0].name, "process_a.txt_a.out");
        assert_eq!(spec.jobs[1].name, "process_b.txt_b.out");
    }

    #[test]
    fn test_zip_parameter_mode_kdl() {
        let kdl_content = r#"
name "test_zip_parameters"
description "Test zip parameter mode in KDL"

job "run_{stage}_{config}" {
    command "execute --stage={stage} --config={config}"
    parameters {
        stage "[1, 2, 3]"
        config "['a', 'b', 'c']"
    }
    parameter_mode "zip"
}
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(kdl_content, "kdl")
            .expect("Failed to parse KDL workflow spec");

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // With zip mode: 3 zipped pairs
        assert_eq!(spec.jobs.len(), 3);
        assert_eq!(spec.jobs[0].name, "run_1_a");
        assert_eq!(spec.jobs[1].name, "run_2_b");
        assert_eq!(spec.jobs[2].name, "run_3_c");
    }

    #[test]
    fn test_zip_parameter_mode_file_spec() {
        let yaml_content = r#"
name: test_zip_file_parameters
description: Test zip parameter mode for files

jobs:
  - name: dummy_job
    command: echo dummy

files:
  - name: data_{dataset}_{split}
    path: /data/{dataset}/{split}.csv
    parameters:
      dataset: "['train', 'test', 'val']"
      split: "['2023', '2024', '2025']"
    parameter_mode: zip
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(yaml_content, "yaml")
            .expect("Failed to parse YAML workflow spec");

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // With zip mode: 3 zipped pairs
        let files = spec.files.as_ref().unwrap();
        assert_eq!(files.len(), 3);
        assert_eq!(files[0].name, "data_train_2023");
        assert_eq!(files[0].path, "/data/train/2023.csv");
        assert_eq!(files[1].name, "data_test_2024");
        assert_eq!(files[2].name, "data_val_2025");
    }

    #[test]
    fn test_zip_parameter_mode_mismatched_lengths_error() {
        let yaml_content = r#"
name: test_zip_mismatched
jobs:
  - name: job_{a}_{b}
    command: echo {a} {b}
    parameters:
      a: "[1, 2, 3]"
      b: "['x', 'y']"
    parameter_mode: zip
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(yaml_content, "yaml")
            .expect("Failed to parse YAML workflow spec");

        // Expansion should fail due to mismatched lengths
        let result = spec.expand_parameters();
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("same number of values"));
    }

    #[test]
    fn test_product_parameter_mode_explicit() {
        // Test that explicit "product" mode works the same as default
        let yaml_content = r#"
name: test_product_explicit
jobs:
  - name: job_{a}_{b}
    command: echo {a} {b}
    parameters:
      a: "[1, 2]"
      b: "['x', 'y']"
    parameter_mode: product
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(yaml_content, "yaml")
            .expect("Failed to parse YAML workflow spec");

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // With product mode: 2 * 2 = 4 combinations
        assert_eq!(spec.jobs.len(), 4);
    }

    #[test]
    fn test_default_parameter_mode_is_product() {
        // Test that default mode (no parameter_mode specified) is Cartesian product
        let yaml_content = r#"
name: test_default_mode
jobs:
  - name: job_{a}_{b}
    command: echo {a} {b}
    parameters:
      a: "[1, 2]"
      b: "['x', 'y']"
"#;

        let mut spec = WorkflowSpec::from_spec_file_content(yaml_content, "yaml")
            .expect("Failed to parse YAML workflow spec");

        spec.expand_parameters()
            .expect("Failed to expand parameters");

        // Default should be product mode: 2 * 2 = 4 combinations
        assert_eq!(spec.jobs.len(), 4);
    }

    // ========== ExecutionConfig Tests ==========

    #[test]
    fn test_execution_config_defaults() {
        let config = ExecutionConfig::default();
        assert_eq!(config.mode, ExecutionMode::Auto);
        assert!(config.limit_resources.is_none());
        assert!(config.termination_signal.is_none());
        assert!(config.sigterm_lead_seconds.is_none());
        assert!(config.sigkill_headroom_seconds.is_none());
        assert!(config.timeout_exit_code.is_none());
        assert!(config.oom_exit_code.is_none());
    }

    #[test]
    fn test_execution_config_default_getters() {
        let config = ExecutionConfig::default();
        assert!(config.limit_resources());
        assert_eq!(config.termination_signal(), "SIGTERM");
        assert_eq!(config.sigterm_lead_seconds(), 30);
        assert_eq!(config.sigkill_headroom_seconds(), 60);
        assert_eq!(config.timeout_exit_code(), 152);
        assert_eq!(config.oom_exit_code(), 137);
    }

    #[test]
    fn test_execution_config_custom_values() {
        let config = ExecutionConfig {
            mode: ExecutionMode::Direct,
            limit_resources: Some(false),
            termination_signal: Some("SIGUSR1".to_string()),
            sigterm_lead_seconds: Some(60),
            sigkill_headroom_seconds: Some(120),
            timeout_exit_code: Some(200),
            oom_exit_code: Some(201),
            srun_termination_signal: None,
            enable_cpu_bind: None,
            staggered_start: None,
            stdio: None,
            job_stdio_overrides: None,
        };
        assert!(!config.limit_resources());
        assert_eq!(config.termination_signal(), "SIGUSR1");
        assert_eq!(config.sigterm_lead_seconds(), 60);
        assert_eq!(config.sigkill_headroom_seconds(), 120);
        assert_eq!(config.timeout_exit_code(), 200);
        assert_eq!(config.oom_exit_code(), 201);
    }

    #[test]
    fn test_execution_mode_serialization() {
        let config = ExecutionConfig {
            mode: ExecutionMode::Direct,
            ..Default::default()
        };
        let json = serde_json::to_string(&config).expect("Failed to serialize");
        assert!(json.contains("\"mode\":\"direct\""));

        let config = ExecutionConfig {
            mode: ExecutionMode::Slurm,
            ..Default::default()
        };
        let json = serde_json::to_string(&config).expect("Failed to serialize");
        assert!(json.contains("\"mode\":\"slurm\""));

        let config = ExecutionConfig {
            mode: ExecutionMode::Auto,
            ..Default::default()
        };
        let json = serde_json::to_string(&config).expect("Failed to serialize");
        assert!(json.contains("\"mode\":\"auto\""));
    }

    #[test]
    fn test_execution_mode_deserialization() {
        let json = r#"{"mode":"direct"}"#;
        let config: ExecutionConfig = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(config.mode, ExecutionMode::Direct);

        let json = r#"{"mode":"slurm"}"#;
        let config: ExecutionConfig = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(config.mode, ExecutionMode::Slurm);

        let json = r#"{"mode":"auto"}"#;
        let config: ExecutionConfig = serde_json::from_str(json).expect("Failed to deserialize");
        assert_eq!(config.mode, ExecutionMode::Auto);
    }

    #[test]
    fn test_execution_config_use_srun_by_mode() {
        // Direct mode: use_srun = false
        let config = ExecutionConfig {
            mode: ExecutionMode::Direct,
            ..Default::default()
        };
        assert!(!config.use_srun());

        // Slurm mode: use_srun = true
        let config = ExecutionConfig {
            mode: ExecutionMode::Slurm,
            ..Default::default()
        };
        assert!(config.use_srun());
    }

    #[test]
    fn test_execution_config_yaml_parsing() {
        let yaml = r#"
name: test_workflow
jobs:
  - name: test_job
    command: echo hello
execution_config:
  mode: direct
  limit_resources: false
  termination_signal: SIGUSR2
  sigterm_lead_seconds: 45
  sigkill_headroom_seconds: 90
  timeout_exit_code: 200
  oom_exit_code: 201
"#;
        let spec: WorkflowSpec = serde_yaml::from_str(yaml).expect("Failed to parse YAML");
        let config = spec
            .execution_config
            .expect("execution_config should be present");
        assert_eq!(config.mode, ExecutionMode::Direct);
        assert_eq!(config.limit_resources, Some(false));
        assert_eq!(config.termination_signal, Some("SIGUSR2".to_string()));
        assert_eq!(config.sigterm_lead_seconds, Some(45));
        assert_eq!(config.sigkill_headroom_seconds, Some(90));
        assert_eq!(config.timeout_exit_code, Some(200));
        assert_eq!(config.oom_exit_code, Some(201));
    }

    #[test]
    fn test_execution_config_with_slurm_settings() {
        let yaml = r#"
name: test_workflow
jobs:
  - name: test_job
    command: echo hello
execution_config:
  mode: slurm
  srun_termination_signal: "TERM@120"
  enable_cpu_bind: true
"#;
        let spec: WorkflowSpec = serde_yaml::from_str(yaml).expect("Failed to parse YAML");
        let config = spec
            .execution_config
            .expect("execution_config should be present");
        assert_eq!(config.mode, ExecutionMode::Slurm);
        assert_eq!(config.srun_termination_signal, Some("TERM@120".to_string()));
        assert_eq!(config.enable_cpu_bind, Some(true));
    }
}