swf-runtime 1.0.0-alpha9

Runtime engine for Serverless Workflow DSL — execute, validate, and orchestrate workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
use crate::error::{WorkflowError, WorkflowResult};
use crate::listener::WorkflowEvent;
use crate::status::StatusPhase;
use crate::task_runner::{create_task_runner, TaskRunner, TaskSupport};
use crate::tasks::task_name_impl;

use serde_json::Value;
use std::collections::HashMap;
use swf_core::models::map::Map;
use swf_core::models::task::{
    DoTaskDefinition, SwitchTaskDefinition, TaskDefinition, TaskDefinitionFields,
};
use swf_core::models::workflow::WorkflowDefinition;

/// Flow directive returned after running a task
enum FlowDirective {
    /// Continue to the next task in sequence
    Continue,
    /// Jump to a specific task by name
    Goto(String),
    /// End the workflow (stop executing tasks)
    End,
    /// Exit the current composite task
    Exit,
}

impl FlowDirective {
    fn from_then(then: &str) -> Self {
        match then {
            "end" => FlowDirective::End,
            "exit" => FlowDirective::Exit,
            "continue" => FlowDirective::Continue,
            task_name => FlowDirective::Goto(task_name.to_string()),
        }
    }
}

/// Runner for Do tasks - executes subtasks sequentially
pub struct DoTaskRunner {
    name: String,
    tasks: Map<String, TaskDefinition>,
}

impl DoTaskRunner {
    /// Creates a new DoTaskRunner from a DoTaskDefinition
    pub fn new(name: &str, task: &DoTaskDefinition) -> WorkflowResult<Self> {
        Ok(Self {
            name: name.to_string(),
            tasks: task.do_.clone(),
        })
    }

    /// Creates a DoTaskRunner from the workflow's top-level do tasks
    pub fn new_from_workflow(workflow: &WorkflowDefinition) -> WorkflowResult<Self> {
        let name = workflow.document.name.clone();
        Ok(Self {
            name,
            tasks: workflow.do_.clone(),
        })
    }

    /// Runs all tasks with flow directive support (then/switch jump)
    pub async fn run_tasks(
        &self,
        input: Value,
        support: &mut TaskSupport<'_>,
    ) -> WorkflowResult<Value> {
        let mut output = input;
        let mut index: usize = 0;

        while index < self.tasks.entries.len() {
            let (name, task) = &self.tasks.entries[index];

            // Set task context
            let task_value = crate::error::serialize_to_value(task, "task", name)?;
            support.set_task_def(&task_value);
            support.set_task_reference_from_name(name)?;

            // Check if condition
            let if_condition = get_if_condition(task);
            if !support.should_run_task(if_condition, &output)? {
                index += 1;
                continue;
            }

            // Suspend check: wait if workflow is suspended
            if support.context.is_suspended() {
                support.set_task_status(name, StatusPhase::Suspended);
                support.emit_event(WorkflowEvent::TaskSuspended {
                    instance_id: support.context.instance_id().to_string(),
                    task_name: name.to_string(),
                });
                support.context.wait_for_resume().await;
                if support.context.is_cancelled() {
                    return Err(WorkflowError::runtime_simple(
                        "workflow cancelled while suspended",
                        name,
                    ));
                }
            }

            support.set_task_status(name, StatusPhase::Pending);

            let task_type = task_type_str(task);
            let task_span = tracing::info_span!(
                "task",
                name = %name,
                type = %task_type,
            );
            let _task_enter = task_span.enter();

            // Run extension before tasks
            run_extension_before_tasks(task, &output, support).await?;

            // Restore main task context after before extensions
            let task_value =
                crate::error::serialize_to_value(task, "task", name)?;
            support.set_task_def(&task_value);
            support.set_task_reference_from_name(name)?;

            // Determine flow directive from task execution
            let directive = if let TaskDefinition::Switch(switch_task) = task {
                // Switch tasks: evaluate conditions to get then directive
                let common = &switch_task.common;
                support.set_task_status(name, StatusPhase::Running);

                // Process input for switch
                let task_input =
                    support.process_task_input(common.input.as_ref(), &output, name)?;

                // Evaluate switch conditions
                let then_str = self
                    .evaluate_switch(&task_input, support, name, switch_task)
                    .await?;

                // Switch output is the input (switch doesn't transform data)
                output = support
                    .execute_task_lifecycle(name, common, &output, task_input)
                    .await?;

                FlowDirective::from_then(&then_str)
            } else {
                // Regular tasks: run the task, then check its `then` field
                let runner = create_task_runner(name, task, support.workflow)?;
                support.set_task_status(name, StatusPhase::Running);

                let common = task.common_fields();
                output = self
                    .run_single_task(&output, support, &*runner, common)
                    .await?;

                support.set_task_status(name, StatusPhase::Completed);
                tracing::debug!(task = %name, type = %task_type, "task completed");

                // Check the task's `then` directive
                match common.then.as_deref() {
                    Some(then) => FlowDirective::from_then(then),
                    None => FlowDirective::Continue,
                }
            };

            // Run extension after tasks
            run_extension_after_tasks(task, &output, support).await?;

            // Apply flow directive
            match directive {
                FlowDirective::Continue => {
                    index += 1;
                }
                FlowDirective::End | FlowDirective::Exit => {
                    break;
                }
                FlowDirective::Goto(target) => match self.find_task_index(&target) {
                    Some(target_index) => {
                        index = target_index;
                    }
                    None => {
                        return Err(WorkflowError::runtime_simple(
                            format!("switch/goto target '{}' not found in task list", target),
                            &self.name,
                        ));
                    }
                },
            }
        }

        Ok(output)
    }

    /// Finds the index of a task by name in the task list
    fn find_task_index(&self, target: &str) -> Option<usize> {
        self.tasks
            .entries
            .iter()
            .position(|(name, _)| name == target)
    }

    /// Runs a single task with input/output/export/timeout processing
    async fn run_single_task(
        &self,
        input: &Value,
        support: &mut TaskSupport<'_>,
        runner: &dyn TaskRunner,
        common: &TaskDefinitionFields,
    ) -> WorkflowResult<Value> {
        let raw_output = support
            .run_task_with_input_and_timeout(runner.task_name(), common, input, runner)
            .await?;
        support
            .execute_task_lifecycle(runner.task_name(), common, input, raw_output)
            .await
    }

    /// Evaluates a switch task and returns the matched then directive
    async fn evaluate_switch(
        &self,
        input: &Value,
        support: &TaskSupport<'_>,
        task_name: &str,
        switch_task: &SwitchTaskDefinition,
    ) -> WorkflowResult<String> {
        let mut default_then: Option<String> = None;

        for (_case_name, case_def) in &switch_task.switch.entries {
            match &case_def.when {
                None => {
                    // Default case
                    if let Some(ref then) = case_def.then {
                        default_then = Some(then.clone());
                    }
                }
                Some(when_expr) => {
                    let result = support
                        .eval_bool(when_expr, input)
                        .map_err(|e| WorkflowError::expression(format!("{}", e), task_name))?;
                    if result {
                        return case_def.then.clone().ok_or_else(|| {
                            WorkflowError::expression(
                                "missing 'then' directive in matched switch case",
                                task_name,
                            )
                        });
                    }
                }
            }
        }

        // No matching case and no default: pass through (continue to next task)
        Ok(default_then.unwrap_or_else(|| "continue".to_string()))
    }
}

#[async_trait::async_trait]
impl TaskRunner for DoTaskRunner {
    async fn run(&self, input: Value, support: &mut TaskSupport<'_>) -> WorkflowResult<Value> {
        self.run_tasks(input, support).await
    }

    task_name_impl!();
}

/// Extracts the `if` condition from a TaskDefinition
fn get_if_condition(task: &TaskDefinition) -> Option<&str> {
    task.common_fields().if_.as_deref()
}

/// Returns the task type strings that this task matches for extension purposes.
/// Every task matches "all"; composite tasks also match "composite".
fn task_type_str(task: &TaskDefinition) -> &'static str {
    match task {
        TaskDefinition::Call(_) => "call",
        TaskDefinition::Set(_) => "set",
        TaskDefinition::Wait(_) => "wait",
        TaskDefinition::Raise(_) => "raise",
        TaskDefinition::Emit(_) => "emit",
        TaskDefinition::Listen(_) => "listen",
        TaskDefinition::Run(_) => "run",
        TaskDefinition::Switch(_) => "switch",
        TaskDefinition::Try(_) => "try",
        TaskDefinition::For(_) => "for",
        TaskDefinition::Do(_) => "do",
        TaskDefinition::Fork(_) => "fork",
        TaskDefinition::Custom(_) => "custom",
    }
}

/// Returns the task type strings that this task matches for extension purposes.
/// Every task matches "all"; composite tasks also match "composite".
fn task_extension_types(task: &TaskDefinition) -> Vec<String> {
    let mut types = match task {
        TaskDefinition::Call(_) => vec!["call".to_string()],
        TaskDefinition::Set(_) => vec!["set".to_string()],
        TaskDefinition::Wait(_) => vec!["wait".to_string()],
        TaskDefinition::Raise(_) => vec!["raise".to_string()],
        TaskDefinition::Emit(_) => vec!["emit".to_string()],
        TaskDefinition::Listen(_) => vec!["listen".to_string()],
        TaskDefinition::Run(_) => vec!["run".to_string()],
        TaskDefinition::Switch(_) => vec!["switch".to_string(), "composite".to_string()],
        TaskDefinition::Try(_) => vec!["try".to_string(), "composite".to_string()],
        TaskDefinition::For(_) => vec!["for".to_string(), "composite".to_string()],
        TaskDefinition::Do(_) => vec!["do".to_string(), "composite".to_string()],
        TaskDefinition::Fork(_) => vec!["fork".to_string(), "composite".to_string()],
        TaskDefinition::Custom(t) => {
            let mut v = vec!["custom".to_string()];
            if let Some(ref type_name) = t.type_ {
                v.push(type_name.clone());
            }
            v
        }
    };
    types.push("all".to_string());
    types
}

/// Runs a list of extension tasks sequentially, preserving side effects (export, events)
/// but discarding their output so the main data flow is not affected.
async fn run_extension_task_list(
    tasks: &[HashMap<String, TaskDefinition>],
    input: &Value,
    support: &mut TaskSupport<'_>,
) -> WorkflowResult<()> {
    for task_map in tasks {
        for (name, task_def) in task_map {
            let runner = create_task_runner(name, task_def, support.workflow)?;
            let common = task_def.common_fields();
            let raw_output = support
                .run_task_with_input_and_timeout(name, common, input, &*runner)
                .await?;
            let _ = support
                .execute_task_lifecycle(name, common, input, raw_output)
                .await?;
        }
    }
    Ok(())
}

/// Runs extension before tasks for matching extensions.
/// Before tasks' output is discarded — the main task receives the original input.
async fn run_extension_before_tasks(
    task: &TaskDefinition,
    input: &Value,
    support: &mut TaskSupport<'_>,
) -> WorkflowResult<()> {
    let extensions = match support
        .workflow
        .use_
        .as_ref()
        .and_then(|u| u.extensions.as_ref())
    {
        Some(exts) => exts,
        None => return Ok(()),
    };

    let task_types = task_extension_types(task);

    for ext_map in extensions {
        for ext in ext_map.values() {
            if !task_types.iter().any(|t| t == &ext.extend) {
                continue;
            }
            if let Some(ref when) = ext.when {
                if !support.eval_bool(when, input).unwrap_or(false) {
                    continue;
                }
            }
            if let Some(ref before) = ext.before {
                run_extension_task_list(before, input, support).await?;
            }
        }
    }
    Ok(())
}

/// Runs extension after tasks for matching extensions.
/// After tasks receive the main task's output but their output is discarded.
async fn run_extension_after_tasks(
    task: &TaskDefinition,
    output: &Value,
    support: &mut TaskSupport<'_>,
) -> WorkflowResult<()> {
    let extensions = match support
        .workflow
        .use_
        .as_ref()
        .and_then(|u| u.extensions.as_ref())
    {
        Some(exts) => exts,
        None => return Ok(()),
    };

    let task_types = task_extension_types(task);

    for ext_map in extensions {
        for ext in ext_map.values() {
            if !task_types.iter().any(|t| t == &ext.extend) {
                continue;
            }
            if let Some(ref when) = ext.when {
                if !support.eval_bool(when, output).unwrap_or(false) {
                    continue;
                }
            }
            if let Some(ref after) = ext.after {
                run_extension_task_list(after, output, support).await?;
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::default_support;
    use crate::test_utils::test_helpers::make_set_task;
    use serde_json::json;
    use std::collections::HashMap;
    use swf_core::models::map::Map;
    use swf_core::models::task::{
        SetTaskDefinition, SetValue, SwitchCaseDefinition, SwitchTaskDefinition,
        TaskDefinitionFields,
    };
    use swf_core::models::workflow::WorkflowDefinition;

    fn make_do_runner(tasks: Vec<(&str, TaskDefinition)>) -> DoTaskRunner {
        let entries: Vec<(String, TaskDefinition)> = tasks
            .into_iter()
            .map(|(name, task)| (name.to_string(), task))
            .collect();
        let do_def = swf_core::models::task::DoTaskDefinition::new(Map { entries });
        DoTaskRunner::new("testDo", &do_def).unwrap()
    }

    #[tokio::test]
    async fn test_do_sequential_execution() {
        // Set tasks replace the output; chain via expressions referencing prior values
        let runner = make_do_runner(vec![
            ("task1", make_set_task("a", json!(1))),
            ("task2", make_set_task("b", json!("${ .a + 1 }"))),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({}), &mut support).await.unwrap();
        // task2 output replaces task1 output, but references .a from task1
        assert_eq!(output["b"], json!(2));
    }

    #[tokio::test]
    async fn test_do_with_if_condition_skip() {
        let mut skip_task = make_set_task("skipped", json!(true));
        if let TaskDefinition::Set(ref mut s) = skip_task {
            s.common.if_ = Some("${ .run == true }".to_string());
        }

        let runner = make_do_runner(vec![
            ("task1", make_set_task("a", json!(1))),
            ("task2", skip_task),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // run=false (in input), so task2 should be skipped; output stays from task1
        let output = runner
            .run(json!({"run": false}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["a"], json!(1));
        assert!(output.get("skipped").is_none());
    }

    #[tokio::test]
    async fn test_do_with_if_condition_execute() {
        let mut exec_task = make_set_task("executed", json!(true));
        if let TaskDefinition::Set(ref mut s) = exec_task {
            s.common.if_ = Some("${ .run == true }".to_string());
        }

        let runner = make_do_runner(vec![
            ("task1", make_set_task("run", json!(true))),
            ("task2", exec_task),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // task1 sets run=true, so task2 should execute
        let output = runner.run(json!({}), &mut support).await.unwrap();
        assert_eq!(output["executed"], json!(true));
    }

    #[tokio::test]
    async fn test_do_with_then_end() {
        let mut end_task = make_set_task("final", json!(42));
        if let TaskDefinition::Set(ref mut s) = end_task {
            s.common.then = Some("end".to_string());
        }

        let runner = make_do_runner(vec![
            ("task1", end_task),
            ("task2", make_set_task("skipped", json!(true))),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({}), &mut support).await.unwrap();
        assert_eq!(output["final"], json!(42));
        assert!(output.get("skipped").is_none());
    }

    #[tokio::test]
    async fn test_do_with_then_goto() {
        let mut goto_task = make_set_task("start", json!(1));
        if let TaskDefinition::Set(ref mut s) = goto_task {
            s.common.then = Some("task3".to_string());
        }

        let runner = make_do_runner(vec![
            ("task1", goto_task),
            ("task2", make_set_task("skipped", json!(true))),
            ("task3", make_set_task("end", json!(99))),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({}), &mut support).await.unwrap();
        // Set replaces output, so task3's set overwrites task1's set
        assert!(output.get("skipped").is_none());
        assert_eq!(output["end"], json!(99));
    }

    // --- Switch tests matching Java/Go SDK patterns ---

    #[tokio::test]
    async fn test_switch_then_loop() {
        // Matches Java SDK's switch-then-loop.yaml
        // inc: set count+1, then goto looping
        // looping: switch - if count<6 goto inc, else "exit" (flow directive)
        let mut inc_task = make_set_task("count", json!("${ .count + 1 }"));
        if let TaskDefinition::Set(ref mut s) = inc_task {
            s.common.then = Some("looping".to_string());
        }

        let switch_task = TaskDefinition::Switch(SwitchTaskDefinition {
            switch: Map {
                entries: vec![
                    (
                        "loopCount".to_string(),
                        SwitchCaseDefinition {
                            when: Some(".count < 6".to_string()),
                            then: Some("inc".to_string()),
                        },
                    ),
                    (
                        "default".to_string(),
                        SwitchCaseDefinition {
                            when: None,
                            then: Some("exit".to_string()),
                        },
                    ),
                ],
            },
            common: TaskDefinitionFields::new(),
        });

        let runner = make_do_runner(vec![("inc", inc_task), ("looping", switch_task)]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({"count": 0}), &mut support).await.unwrap();
        // Loop runs: count 0→1→2→3→4→5→6 (count<6 fails at 6, exits)
        assert_eq!(output["count"], json!(6));
    }

    #[tokio::test]
    async fn test_switch_then_string() {
        // Matches Java SDK's switch-then-string.yaml
        // processOrder switch → processElectronicOrder / processPhysicalOrder / handleUnknownOrderType
        // "exit" and "end" are flow directives, not task names
        let switch_task = TaskDefinition::Switch(SwitchTaskDefinition {
            switch: Map {
                entries: vec![
                    (
                        "case1".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".orderType == "electronic""#.to_string()),
                            then: Some("processElectronicOrder".to_string()),
                        },
                    ),
                    (
                        "case2".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".orderType == "physical""#.to_string()),
                            then: Some("processPhysicalOrder".to_string()),
                        },
                    ),
                    (
                        "default".to_string(),
                        SwitchCaseDefinition {
                            when: None,
                            then: Some("handleUnknownOrderType".to_string()),
                        },
                    ),
                ],
            },
            common: TaskDefinitionFields::new(),
        });

        // processElectronicOrder: set validate=true, status=fulfilled, then: exit (flow directive)
        let mut electronic_task = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("validate".to_string(), json!(true));
                m.insert("status".to_string(), json!("fulfilled"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });
        if let TaskDefinition::Set(ref mut s) = electronic_task {
            s.common.then = Some("exit".to_string());
        }

        // processPhysicalOrder: set inventory, items, address, then: exit
        let mut physical_task = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("inventory".to_string(), json!("clear"));
                m.insert("items".to_string(), json!(1));
                m.insert("address".to_string(), json!("Elmer St"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });
        if let TaskDefinition::Set(ref mut s) = physical_task {
            s.common.then = Some("exit".to_string());
        }

        // handleUnknownOrderType: set log=warn, message (no then, continues sequentially)
        let unknown_task = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("log".to_string(), json!("warn"));
                m.insert("message".to_string(), json!("something's wrong"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });

        let runner = make_do_runner(vec![
            ("processOrder", switch_task),
            ("processElectronicOrder", electronic_task),
            ("processPhysicalOrder", physical_task),
            ("handleUnknownOrderType", unknown_task),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // Test electronic order path
        let output = runner
            .run(json!({"orderType": "electronic"}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["validate"], json!(true));
        assert_eq!(output["status"], json!("fulfilled"));
        assert!(output.get("inventory").is_none());
    }

    #[tokio::test]
    async fn test_switch_then_string_physical() {
        // Same workflow as above, testing physical order path
        let switch_task = TaskDefinition::Switch(SwitchTaskDefinition {
            switch: Map {
                entries: vec![
                    (
                        "case1".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".orderType == "electronic""#.to_string()),
                            then: Some("processElectronicOrder".to_string()),
                        },
                    ),
                    (
                        "case2".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".orderType == "physical""#.to_string()),
                            then: Some("processPhysicalOrder".to_string()),
                        },
                    ),
                    (
                        "default".to_string(),
                        SwitchCaseDefinition {
                            when: None,
                            then: Some("handleUnknownOrderType".to_string()),
                        },
                    ),
                ],
            },
            common: TaskDefinitionFields::new(),
        });

        let mut electronic_task = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("validate".to_string(), json!(true));
                m.insert("status".to_string(), json!("fulfilled"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });
        if let TaskDefinition::Set(ref mut s) = electronic_task {
            s.common.then = Some("exit".to_string());
        }

        let mut physical_task = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("inventory".to_string(), json!("clear"));
                m.insert("items".to_string(), json!(1));
                m.insert("address".to_string(), json!("Elmer St"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });
        if let TaskDefinition::Set(ref mut s) = physical_task {
            s.common.then = Some("exit".to_string());
        }

        let unknown_task = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("log".to_string(), json!("warn"));
                m.insert("message".to_string(), json!("something's wrong"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });

        let runner = make_do_runner(vec![
            ("processOrder", switch_task),
            ("processElectronicOrder", electronic_task),
            ("processPhysicalOrder", physical_task),
            ("handleUnknownOrderType", unknown_task),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // Test physical order path
        let output = runner
            .run(json!({"orderType": "physical"}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["inventory"], json!("clear"));
        assert_eq!(output["items"], json!(1));
        assert_eq!(output["address"], json!("Elmer St"));
        assert!(output.get("validate").is_none());
    }

    #[tokio::test]
    async fn test_switch_then_string_default() {
        // Same workflow, testing default/unknown order path
        let switch_task = TaskDefinition::Switch(SwitchTaskDefinition {
            switch: Map {
                entries: vec![
                    (
                        "case1".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".orderType == "electronic""#.to_string()),
                            then: Some("processElectronicOrder".to_string()),
                        },
                    ),
                    (
                        "case2".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".orderType == "physical""#.to_string()),
                            then: Some("processPhysicalOrder".to_string()),
                        },
                    ),
                    (
                        "default".to_string(),
                        SwitchCaseDefinition {
                            when: None,
                            then: Some("handleUnknownOrderType".to_string()),
                        },
                    ),
                ],
            },
            common: TaskDefinitionFields::new(),
        });

        let mut electronic_task = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("validate".to_string(), json!(true));
                m.insert("status".to_string(), json!("fulfilled"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });
        if let TaskDefinition::Set(ref mut s) = electronic_task {
            s.common.then = Some("exit".to_string());
        }

        let mut physical_task = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("inventory".to_string(), json!("clear"));
                m.insert("items".to_string(), json!(1));
                m.insert("address".to_string(), json!("Elmer St"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });
        if let TaskDefinition::Set(ref mut s) = physical_task {
            s.common.then = Some("exit".to_string());
        }

        let unknown_task = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("log".to_string(), json!("warn"));
                m.insert("message".to_string(), json!("something's wrong"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });

        let runner = make_do_runner(vec![
            ("processOrder", switch_task),
            ("processElectronicOrder", electronic_task),
            ("processPhysicalOrder", physical_task),
            ("handleUnknownOrderType", unknown_task),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // Test unknown order type path (falls through to default)
        let output = runner
            .run(json!({"orderType": "digital"}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["log"], json!("warn"));
        assert_eq!(output["message"], json!("something's wrong"));
    }

    #[tokio::test]
    async fn test_switch_match_color() {
        // Matches Go SDK's switch_match.yaml
        // switchColor → red/green/blue cases, each appends to colors array, then end
        let switch_task = TaskDefinition::Switch(SwitchTaskDefinition {
            switch: Map {
                entries: vec![
                    (
                        "red".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".color == "red""#.to_string()),
                            then: Some("setRed".to_string()),
                        },
                    ),
                    (
                        "green".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".color == "green""#.to_string()),
                            then: Some("setGreen".to_string()),
                        },
                    ),
                    (
                        "blue".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".color == "blue""#.to_string()),
                            then: Some("setBlue".to_string()),
                        },
                    ),
                ],
            },
            common: TaskDefinitionFields::new(),
        });

        let mut set_red = make_set_task("colors", json!("${ .colors + [\"red\"] }"));
        if let TaskDefinition::Set(ref mut s) = set_red {
            s.common.then = Some("end".to_string());
        }
        let mut set_green = make_set_task("colors", json!("${ .colors + [\"green\"] }"));
        if let TaskDefinition::Set(ref mut s) = set_green {
            s.common.then = Some("end".to_string());
        }
        let mut set_blue = make_set_task("colors", json!("${ .colors + [\"blue\"] }"));
        if let TaskDefinition::Set(ref mut s) = set_blue {
            s.common.then = Some("end".to_string());
        }

        let runner = make_do_runner(vec![
            ("switchColor", switch_task),
            ("setRed", set_red),
            ("setGreen", set_green),
            ("setBlue", set_blue),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // Test red path
        let output = runner
            .run(json!({"color": "red", "colors": []}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["colors"], json!(["red"]));
    }

    #[tokio::test]
    async fn test_switch_with_default_fallback() {
        // Matches Go SDK's switch_with_default.yaml
        // switchColor → red/green/fallback cases
        let switch_task = TaskDefinition::Switch(SwitchTaskDefinition {
            switch: Map {
                entries: vec![
                    (
                        "red".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".color == "red""#.to_string()),
                            then: Some("setRed".to_string()),
                        },
                    ),
                    (
                        "green".to_string(),
                        SwitchCaseDefinition {
                            when: Some(r#".color == "green""#.to_string()),
                            then: Some("setGreen".to_string()),
                        },
                    ),
                    (
                        "fallback".to_string(),
                        SwitchCaseDefinition {
                            when: None,
                            then: Some("setDefault".to_string()),
                        },
                    ),
                ],
            },
            common: TaskDefinitionFields::new(),
        });

        let mut set_red = make_set_task("colors", json!("${ .colors + [\"red\"] }"));
        if let TaskDefinition::Set(ref mut s) = set_red {
            s.common.then = Some("end".to_string());
        }
        let mut set_green = make_set_task("colors", json!("${ .colors + [\"green\"] }"));
        if let TaskDefinition::Set(ref mut s) = set_green {
            s.common.then = Some("end".to_string());
        }
        let mut set_default = make_set_task("colors", json!("${ .colors + [\"default\"] }"));
        if let TaskDefinition::Set(ref mut s) = set_default {
            s.common.then = Some("end".to_string());
        }

        let runner = make_do_runner(vec![
            ("switchColor", switch_task),
            ("setRed", set_red),
            ("setGreen", set_green),
            ("setDefault", set_default),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // Test fallback (no matching case)
        let output = runner
            .run(json!({"color": "yellow", "colors": []}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["colors"], json!(["default"]));
    }

    #[tokio::test]
    async fn test_switch_no_match_continues() {
        // Switch with no matching case and no default should continue to next task
        let switch_task = TaskDefinition::Switch(SwitchTaskDefinition {
            switch: Map {
                entries: vec![(
                    "red".to_string(),
                    SwitchCaseDefinition {
                        when: Some(r#".color == "red""#.to_string()),
                        then: Some("setRed".to_string()),
                    },
                )],
            },
            common: TaskDefinitionFields::new(),
        });

        let set_red = make_set_task("isRed", json!(true));

        let runner = make_do_runner(vec![("switchColor", switch_task), ("setRed", set_red)]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // Color is "green" which doesn't match "red" - no default, so continue
        let output = runner
            .run(json!({"color": "green"}), &mut support)
            .await
            .unwrap();
        // setRed task runs because switch continues flow (no match, no default)
        // But setRed was the goto target - switch returns "continue" so the next task in list runs
        // which happens to be setRed, so it executes
        assert_eq!(output["isRed"], json!(true));
    }

    // --- Go SDK pattern tests ---

    #[tokio::test]
    async fn test_chained_set_tasks() {
        // Matches Go SDK's chained_set_tasks.yaml
        // task1: set baseValue=10, task2: set doubled=baseValue*2, task3: set tripled=doubled*3
        // Each set replaces the output; the next task receives the previous output as input
        let runner = make_do_runner(vec![
            ("task1", make_set_task("baseValue", json!(10))),
            (
                "task2",
                make_set_task("doubled", json!("${ .baseValue * 2 }")),
            ),
            (
                "task3",
                make_set_task("tripled", json!("${ .doubled * 3 }")),
            ),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({}), &mut support).await.unwrap();
        // Set replaces output, so only the last task's output remains
        assert_eq!(output["tripled"], json!(60));
    }

    #[tokio::test]
    async fn test_sequential_set_colors() {
        // Matches Go SDK's sequential_set_colors.yaml
        // Sequentially append colors to array
        let runner = make_do_runner(vec![
            (
                "setRed",
                make_set_task("colors", json!("${ .colors + [\"red\"] }")),
            ),
            (
                "setGreen",
                make_set_task("colors", json!("${ .colors + [\"green\"] }")),
            ),
            (
                "setBlue",
                make_set_task("colors", json!("${ .colors + [\"blue\"] }")),
            ),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner
            .run(json!({"colors": []}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["colors"], json!(["red", "green", "blue"]));
    }

    #[tokio::test]
    async fn test_set_with_then_goto_and_expression() {
        // Matches Go SDK's set_tasks_with_then.yaml
        // task1: set value=30, then: task3; task3: set result=value*3
        let mut task1 = make_set_task("value", json!(30));
        if let TaskDefinition::Set(ref mut s) = task1 {
            s.common.then = Some("task3".to_string());
        }

        let runner = make_do_runner(vec![
            ("task1", task1),
            ("task2", make_set_task("skipped", json!(true))),
            ("task3", make_set_task("result", json!("${ .value * 3 }"))),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({}), &mut support).await.unwrap();
        // Set replaces output; task1 sets {value: 30}, task3 uses that as input
        assert_eq!(output["result"], json!(90));
        assert!(output.get("skipped").is_none());
    }

    #[tokio::test]
    async fn test_conditional_raise_skipped() {
        // Matches Go SDK's raise_conditional.yaml - raise with if condition
        // When condition is false, raise is skipped and next task runs
        let mut raise_task = TaskDefinition::Raise(swf_core::models::task::RaiseTaskDefinition {
            raise: swf_core::models::task::RaiseErrorDefinition::new(
                swf_core::models::error::OneOfErrorDefinitionOrReference::Error(
                    swf_core::models::error::ErrorDefinition::new(
                        "authorization",
                        "Authorization Error",
                        json!(403),
                        Some("User is under the required age".to_string()),
                        None,
                    ),
                ),
            ),
            common: TaskDefinitionFields::new(),
        });
        if let TaskDefinition::Raise(ref mut r) = raise_task {
            r.common.if_ = Some("${ .user.age < 18 }".to_string());
        }

        let runner = make_do_runner(vec![
            ("underageError", raise_task),
            (
                "continueProcess",
                make_set_task("message", json!("User is allowed")),
            ),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // User is 25 (>= 18), so raise is skipped, continueProcess runs
        let output = runner
            .run(json!({"user": {"age": 25}}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["message"], json!("User is allowed"));
    }

    #[tokio::test]
    async fn test_conditional_raise_triggered() {
        // Same workflow, but user is underage so raise fires
        let mut raise_task = TaskDefinition::Raise(swf_core::models::task::RaiseTaskDefinition {
            raise: swf_core::models::task::RaiseErrorDefinition::new(
                swf_core::models::error::OneOfErrorDefinitionOrReference::Error(
                    swf_core::models::error::ErrorDefinition::new(
                        "authorization",
                        "Authorization Error",
                        json!(403),
                        Some("User is under the required age".to_string()),
                        None,
                    ),
                ),
            ),
            common: TaskDefinitionFields::new(),
        });
        if let TaskDefinition::Raise(ref mut r) = raise_task {
            r.common.if_ = Some("${ .user.age < 18 }".to_string());
        }

        let runner = make_do_runner(vec![
            ("underageError", raise_task),
            (
                "continueProcess",
                make_set_task("message", json!("User is allowed")),
            ),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // User is 15 (< 18), so raise fires
        let result = runner.run(json!({"user": {"age": 15}}), &mut support).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_wait_then_set_with_iso8601() {
        // Matches Go SDK's wait_duration_iso8601.yaml
        // set phase=started, wait PT0.01S, set phase=completed
        use swf_core::models::duration::OneOfDurationOrIso8601Expression;
        use swf_core::models::task::WaitTaskDefinition;

        let wait_task = TaskDefinition::Wait(WaitTaskDefinition {
            wait: OneOfDurationOrIso8601Expression::Iso8601Expression("PT0.01S".to_string()),
            common: TaskDefinitionFields::new(),
        });

        let runner = make_do_runner(vec![
            (
                "prepareWaitExample",
                make_set_task("phase", json!("started")),
            ),
            ("waitOneSecond", wait_task),
            (
                "completeWaitExample",
                make_set_task("phase", json!("completed")),
            ),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({}), &mut support).await.unwrap();
        assert_eq!(output["phase"], json!("completed"));
    }

    #[tokio::test]
    async fn test_concatenating_strings() {
        // Matches Go SDK's concatenating_strings.yaml
        // task1: set firstName/lastName, task2: update, task3: concatenate
        let runner = make_do_runner(vec![
            (
                "task1",
                TaskDefinition::Set(SetTaskDefinition {
                    set: SetValue::Map({
                        let mut m = HashMap::new();
                        m.insert("firstName".to_string(), json!("John"));
                        m.insert("lastName".to_string(), json!(""));
                        m
                    }),
                    common: TaskDefinitionFields::new(),
                }),
            ),
            (
                "task2",
                TaskDefinition::Set(SetTaskDefinition {
                    set: SetValue::Map({
                        let mut m = HashMap::new();
                        m.insert("firstName".to_string(), json!("${ .firstName }"));
                        m.insert("lastName".to_string(), json!("Doe"));
                        m
                    }),
                    common: TaskDefinitionFields::new(),
                }),
            ),
            (
                "task3",
                make_set_task("fullName", json!("${ .firstName + \" \" + .lastName }")),
            ),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({}), &mut support).await.unwrap();
        // Set replaces output, so only last task's output remains
        assert_eq!(output["fullName"], json!("John Doe"));
    }

    #[tokio::test]
    async fn test_conditional_logic() {
        // Matches Go SDK's conditional_logic.yaml
        // set temperature, then set weather based on condition
        let runner = make_do_runner(vec![
            (
                "task1",
                TaskDefinition::Set(SetTaskDefinition {
                    set: SetValue::Map({
                        let mut m = HashMap::new();
                        m.insert("temperature".to_string(), json!(35));
                        m
                    }),
                    common: TaskDefinitionFields::new(),
                }),
            ),
            (
                "task2",
                make_set_task(
                    "weather",
                    json!("${ if .temperature > 25 then \"hot\" else \"cold\" end }"),
                ),
            ),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({}), &mut support).await.unwrap();
        assert_eq!(output["weather"], json!("hot"));
    }

    #[tokio::test]
    async fn test_set_tasks_with_termination() {
        // Matches Go SDK's set_tasks_with_termination.yaml
        // task1: set finalValue=20, then: end
        // task2: set skipped=true (should be skipped because then: end)
        let mut task1 = make_set_task("finalValue", json!(20));
        if let TaskDefinition::Set(ref mut s) = task1 {
            s.common.then = Some("end".to_string());
        }

        let runner = make_do_runner(vec![
            ("task1", task1),
            ("task2", make_set_task("skipped", json!(true))),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({}), &mut support).await.unwrap();
        assert_eq!(output["finalValue"], json!(20));
        assert!(output.get("skipped").is_none());
    }

    #[tokio::test]
    async fn test_set_tasks_invalid_then_goto() {
        // Matches Go SDK's set_tasks_invalid_then.yaml
        // task1: set partialResult=15, then: nonExistentTask
        // task2: set skipped=true
        // Invalid goto target should result in an error
        let mut task1 = make_set_task("partialResult", json!(15));
        if let TaskDefinition::Set(ref mut s) = task1 {
            s.common.then = Some("nonExistentTask".to_string());
        }

        let runner = make_do_runner(vec![
            ("task1", task1),
            ("task2", make_set_task("skipped", json!(true))),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // Invalid goto target should produce an error
        let result = runner.run(json!({}), &mut support).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("nonExistentTask"));
    }

    #[tokio::test]
    async fn test_conditional_set_enabled() {
        // Matches Java SDK's conditional-set.yaml - set with if condition
        // When if condition is true, set executes
        let mut set_task = make_set_task("name", json!("javierito"));
        if let TaskDefinition::Set(ref mut s) = set_task {
            s.common.if_ = Some(".enabled".to_string());
        }

        let runner = make_do_runner(vec![("conditionalExpression", set_task)]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // enabled=true, so set should execute
        let output = runner
            .run(json!({"enabled": true}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["name"], json!("javierito"));
    }

    #[tokio::test]
    async fn test_conditional_set_disabled() {
        // Same workflow, but enabled=false so set is skipped
        let mut set_task = make_set_task("name", json!("javierito"));
        if let TaskDefinition::Set(ref mut s) = set_task {
            s.common.if_ = Some(".enabled".to_string());
        }

        let runner = make_do_runner(vec![("conditionalExpression", set_task)]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        // enabled=false, so set is skipped, output is unchanged input
        let output = runner
            .run(json!({"enabled": false, "original": "data"}), &mut support)
            .await
            .unwrap();
        assert!(output.get("name").is_none());
        assert_eq!(output["original"], json!("data"));
    }

    #[tokio::test]
    async fn test_sequential_set_colors_with_output_as() {
        // Matches Go SDK's sequential_set_colors.yaml - with output.as transformation
        // on the last task
        let mut set_blue = make_set_task("colors", json!("${ .colors + [\"blue\"] }"));
        if let TaskDefinition::Set(ref mut s) = set_blue {
            s.common.output = Some(swf_core::models::output::OutputDataModelDefinition {
                as_: Some(json!("${ { resultColors: .colors } }")),
                schema: None,
            });
        }

        let runner = make_do_runner(vec![
            (
                "setRed",
                make_set_task("colors", json!("${ .colors + [\"red\"] }")),
            ),
            (
                "setGreen",
                make_set_task("colors", json!("${ .colors + [\"green\"] }")),
            ),
            ("setBlue", set_blue),
        ]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner
            .run(json!({"colors": []}), &mut support)
            .await
            .unwrap();
        // Output.as transforms the last task's output
        assert_eq!(output["resultColors"], json!(["red", "green", "blue"]));
    }

    #[tokio::test]
    async fn test_fork_with_join_result() {
        // Matches Go SDK's fork_simple.yaml - fork non-compete with join set
        // branchColors: fork (compete: false) with setRed/setBlue branches
        // joinResult: set colors: ${ [.[] | .[]] }
        use swf_core::models::task::{BranchingDefinition, ForkTaskDefinition};

        let set_red = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("color1".to_string(), json!("red"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });
        let set_blue = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("color2".to_string(), json!("blue"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });

        let branch_entries = vec![
            ("setRed".to_string(), set_red),
            ("setBlue".to_string(), set_blue),
        ];

        let fork_task = TaskDefinition::Fork(ForkTaskDefinition {
            fork: BranchingDefinition {
                branches: Map {
                    entries: branch_entries,
                },
                compete: false,
            },
            common: TaskDefinitionFields::new(),
        });

        let join_set = TaskDefinition::Set(SetTaskDefinition {
            set: SetValue::Map({
                let mut m = HashMap::new();
                m.insert("colors".to_string(), json!("${ [to_entries[].value[]] }"));
                m
            }),
            common: TaskDefinitionFields::new(),
        });

        let runner = make_do_runner(vec![("branchColors", fork_task), ("joinResult", join_set)]);

        let workflow = WorkflowDefinition::default();
        default_support!(workflow, context, support);

        let output = runner.run(json!({}), &mut support).await.unwrap();
        // Fork returns object: {setRed: {color1:"red"}, setBlue: {color2:"blue"}}
        // joinResult: to_entries[].value[] → ["red", "blue"] (order may vary)
        let colors = output["colors"].as_array().unwrap();
        assert_eq!(colors.len(), 2);
        assert!(colors.contains(&json!("red")));
        assert!(colors.contains(&json!("blue")));
    }

    // --- Extension before/after tests ---

    use swf_core::models::extension::ExtensionDefinition;
    use swf_core::models::workflow::ComponentDefinitionCollection;

    fn make_workflow_with_extensions(
        tasks: Vec<(&str, TaskDefinition)>,
        extensions: Vec<HashMap<String, ExtensionDefinition>>,
    ) -> WorkflowDefinition {
        let mut workflow = WorkflowDefinition::default();
        let entries: Vec<(String, TaskDefinition)> = tasks
            .into_iter()
            .map(|(name, task)| (name.to_string(), task))
            .collect();
        workflow.do_ = Map { entries };
        workflow.use_ = Some(ComponentDefinitionCollection {
            extensions: Some(extensions),
            ..Default::default()
        });
        workflow
    }

    #[tokio::test]
    async fn test_extension_before_set() {
        // Extension with before task that exports to $context
        let before_task = make_set_task("preKey", json!("preValue"));
        let before_task_with_export = {
            let mut t = before_task;
            if let TaskDefinition::Set(ref mut s) = t {
                s.common.export = Some(swf_core::models::output::OutputDataModelDefinition {
                    as_: Some(json!("${ {preKey: .preKey} }")),
                    schema: None,
                });
            }
            t
        };

        let ext = ExtensionDefinition {
            extend: "set".to_string(),
            when: None,
            before: Some(vec![HashMap::from([(
                "preTask".to_string(),
                before_task_with_export,
            )])]),
            after: None,
        };

        let workflow = make_workflow_with_extensions(
            vec![("mainSet", make_set_task("result", json!(42)))],
            vec![HashMap::from([("myExt".to_string(), ext)])],
        );

        let do_runner = DoTaskRunner::new_from_workflow(&workflow).unwrap();
        default_support!(workflow, context, support);

        let output = do_runner.run(json!({}), &mut support).await.unwrap();
        // Main task output is preserved (before task output is discarded)
        assert_eq!(output["result"], json!(42));
        // Before task's export updated $context
        let ctx = support.context.get_instance_ctx().unwrap();
        assert_eq!(ctx["preKey"], json!("preValue"));
    }

    #[tokio::test]
    async fn test_extension_after_set() {
        // Extension with after task that exports to $context
        let after_task = make_set_task("postKey", json!("postValue"));
        let after_task_with_export = {
            let mut t = after_task;
            if let TaskDefinition::Set(ref mut s) = t {
                s.common.export = Some(swf_core::models::output::OutputDataModelDefinition {
                    as_: Some(json!("${ {postKey: .postKey} }")),
                    schema: None,
                });
            }
            t
        };

        let ext = ExtensionDefinition {
            extend: "set".to_string(),
            when: None,
            before: None,
            after: Some(vec![HashMap::from([(
                "postTask".to_string(),
                after_task_with_export,
            )])]),
        };

        let workflow = make_workflow_with_extensions(
            vec![("mainSet", make_set_task("result", json!(42)))],
            vec![HashMap::from([("myExt".to_string(), ext)])],
        );

        let do_runner = DoTaskRunner::new_from_workflow(&workflow).unwrap();
        default_support!(workflow, context, support);

        let output = do_runner.run(json!({}), &mut support).await.unwrap();
        // Main task output is preserved
        assert_eq!(output["result"], json!(42));
        // After task's export updated $context
        let ctx = support.context.get_instance_ctx().unwrap();
        assert_eq!(ctx["postKey"], json!("postValue"));
    }

    #[tokio::test]
    async fn test_extension_before_and_after() {
        let before_task = {
            let mut t = make_set_task("preKey", json!("before"));
            if let TaskDefinition::Set(ref mut s) = t {
                s.common.export = Some(swf_core::models::output::OutputDataModelDefinition {
                    as_: Some(json!("${ {preKey: .preKey} }")),
                    schema: None,
                });
            }
            t
        };
        let after_task = {
            let mut t = make_set_task("postKey", json!("after"));
            if let TaskDefinition::Set(ref mut s) = t {
                s.common.export = Some(swf_core::models::output::OutputDataModelDefinition {
                    as_: Some(json!("${ {postKey: .postKey} }")),
                    schema: None,
                });
            }
            t
        };

        let ext = ExtensionDefinition {
            extend: "set".to_string(),
            when: None,
            before: Some(vec![HashMap::from([(
                "preTask".to_string(),
                before_task,
            )])]),
            after: Some(vec![HashMap::from([(
                "postTask".to_string(),
                after_task,
            )])]),
        };

        let workflow = make_workflow_with_extensions(
            vec![("mainSet", make_set_task("result", json!(42)))],
            vec![HashMap::from([("myExt".to_string(), ext)])],
        );

        let do_runner = DoTaskRunner::new_from_workflow(&workflow).unwrap();
        default_support!(workflow, context, support);

        let output = do_runner.run(json!({}), &mut support).await.unwrap();
        assert_eq!(output["result"], json!(42));
        // Before export then after export — last export wins
        let ctx = support.context.get_instance_ctx().unwrap();
        assert_eq!(ctx["postKey"], json!("after"));
    }

    #[tokio::test]
    async fn test_extension_when_condition_true() {
        let before_task = {
            let mut t = make_set_task("touched", json!(true));
            if let TaskDefinition::Set(ref mut s) = t {
                s.common.export = Some(swf_core::models::output::OutputDataModelDefinition {
                    as_: Some(json!("${ {touched: .touched} }")),
                    schema: None,
                });
            }
            t
        };

        let ext = ExtensionDefinition {
            extend: "set".to_string(),
            when: Some(".enabled".to_string()),
            before: Some(vec![HashMap::from([(
                "condTask".to_string(),
                before_task,
            )])]),
            after: None,
        };

        let workflow = make_workflow_with_extensions(
            vec![("mainSet", make_set_task("result", json!(1)))],
            vec![HashMap::from([("condExt".to_string(), ext)])],
        );

        let do_runner = DoTaskRunner::new_from_workflow(&workflow).unwrap();
        default_support!(workflow, context, support);

        let output = do_runner
            .run(json!({"enabled": true}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["result"], json!(1));
        let ctx = support.context.get_instance_ctx().unwrap();
        assert_eq!(ctx["touched"], json!(true));
    }

    #[tokio::test]
    async fn test_extension_when_condition_false() {
        let before_task = {
            let mut t = make_set_task("touched", json!(true));
            if let TaskDefinition::Set(ref mut s) = t {
                s.common.export = Some(swf_core::models::output::OutputDataModelDefinition {
                    as_: Some(json!("${ {touched: .touched} }")),
                    schema: None,
                });
            }
            t
        };

        let ext = ExtensionDefinition {
            extend: "set".to_string(),
            when: Some(".enabled".to_string()),
            before: Some(vec![HashMap::from([(
                "condTask".to_string(),
                before_task,
            )])]),
            after: None,
        };

        let workflow = make_workflow_with_extensions(
            vec![("mainSet", make_set_task("result", json!(1)))],
            vec![HashMap::from([("condExt".to_string(), ext)])],
        );

        let do_runner = DoTaskRunner::new_from_workflow(&workflow).unwrap();
        default_support!(workflow, context, support);

        let output = do_runner
            .run(json!({"enabled": false}), &mut support)
            .await
            .unwrap();
        assert_eq!(output["result"], json!(1));
        // Extension was skipped because when condition is false
        let ctx = support.context.get_instance_ctx();
        assert!(ctx.is_none() || ctx.unwrap().get("touched").is_none());
    }

    #[tokio::test]
    async fn test_extension_extend_all() {
        let after_task = {
            let mut t = make_set_task("logMsg", json!("logged"));
            if let TaskDefinition::Set(ref mut s) = t {
                s.common.export = Some(swf_core::models::output::OutputDataModelDefinition {
                    as_: Some(json!("${ {logMsg: .logMsg} }")),
                    schema: None,
                });
            }
            t
        };

        let ext = ExtensionDefinition {
            extend: "all".to_string(),
            when: None,
            before: None,
            after: Some(vec![HashMap::from([(
                "logAfter".to_string(),
                after_task,
            )])]),
        };

        let workflow = make_workflow_with_extensions(
            vec![
                ("task1", make_set_task("a", json!(1))),
                ("task2", make_set_task("b", json!(2))),
            ],
            vec![HashMap::from([("logExt".to_string(), ext)])],
        );

        let do_runner = DoTaskRunner::new_from_workflow(&workflow).unwrap();
        default_support!(workflow, context, support);

        let output = do_runner.run(json!({}), &mut support).await.unwrap();
        // Both tasks run, "all" extension runs after each
        assert_eq!(output["b"], json!(2));
        let ctx = support.context.get_instance_ctx().unwrap();
        assert_eq!(ctx["logMsg"], json!("logged"));
    }

    #[tokio::test]
    async fn test_extension_no_match() {
        let before_task = {
            let mut t = make_set_task("touched", json!(true));
            if let TaskDefinition::Set(ref mut s) = t {
                s.common.export = Some(swf_core::models::output::OutputDataModelDefinition {
                    as_: Some(json!("${ {touched: .touched} }")),
                    schema: None,
                });
            }
            t
        };

        // Extension targets "call" but we only have "set" tasks
        let ext = ExtensionDefinition {
            extend: "call".to_string(),
            when: None,
            before: Some(vec![HashMap::from([(
                "callBefore".to_string(),
                before_task,
            )])]),
            after: None,
        };

        let workflow = make_workflow_with_extensions(
            vec![("mainSet", make_set_task("result", json!(1)))],
            vec![HashMap::from([("callExt".to_string(), ext)])],
        );

        let do_runner = DoTaskRunner::new_from_workflow(&workflow).unwrap();
        default_support!(workflow, context, support);

        let output = do_runner.run(json!({}), &mut support).await.unwrap();
        assert_eq!(output["result"], json!(1));
        // Extension didn't match, so no side effects
        let ctx = support.context.get_instance_ctx();
        assert!(ctx.is_none() || ctx.unwrap().get("touched").is_none());
    }
}