choreo 0.12.0

DSL for BDD type testing.
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
use crate::backend::filesystem_backend::FileSystemBackend;
use crate::backend::system_backend::SystemBackend;
use crate::backend::terminal_backend::TerminalBackend;
use crate::backend::web_backend::WebBackend;
use crate::colours;
use crate::error::AppError;
use crate::parser::ast::{
    Action, Condition, GivenStep, ReportFormat, Scenario, Statement, TaskArg, TaskBodyItem,
    TaskCall, TaskDef, TestCase, TestState, TestSuite, TestSuiteSettings, ThenStep, WhenStep,
};
use crate::parser::helpers::{
    check_all_conditions_met, extract_conditions_from_then_steps, is_synchronous,
    substitute_variables_in_action, substitute_variables_in_condition,
};
use crate::parser::parser::expand_foreach_blocks;
use crate::reporting::generate_choreo_report;
use rayon::prelude::*;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

pub struct TestRunner {
    test_suite: TestSuite,
    base_dir: PathBuf,
    env_vars: HashMap<String, String>,
    #[allow(dead_code)] // Will be used for task expansion in future implementation
    tasks: HashMap<String, TaskDef>,
    verbose: bool,
}

impl TestRunner {
    pub fn new(
        test_suite: TestSuite,
        base_dir: PathBuf,
        env_vars: HashMap<String, String>,
        tasks: HashMap<String, TaskDef>,
        verbose: bool,
    ) -> Self {
        Self {
            test_suite,
            base_dir,
            env_vars,
            tasks,
            verbose,
        }
    }

    pub fn run(&mut self, suite_name: &str, scenarios: &[Scenario]) -> Result<(), AppError> {
        let mut settings = TestSuiteSettings::default();
        let mut feature_name = "Choreo Test Feature".to_string(); // Default name
                                                                  //let mut scenarios: Vec<crate::parser::ast::Scenario> = Vec::new();

        for s in &self.test_suite.statements {
            match s {
                Statement::SettingsDef(s_def) => settings = s_def.clone(),
                Statement::FeatureDef(name) => feature_name = name.clone(),
                _ => {}
            }
        }

        // Set a default shell path if not provided
        if settings.shell_path.is_none() {
            settings.shell_path = Some("/bin/sh".to_string());
        }

        // Clone scenarios into a mutable Vec so we can remove Background and run it first.
        let mut scenarios_vec: Vec<_> = scenarios.iter().cloned().collect();
        let mut bg_http_headers: HashMap<String, String> = HashMap::new();

        // Run any Background scenario first so its actions (e.g. Web set_header) modify `self.env_vars`.
        // NOTE: Background runs exactly ONCE for the entire suite (not before each scenario).
        // Any side-effects it produces (env vars, HTTP headers) are inherited by all subsequent scenarios.
        if let Some(pos) = scenarios_vec.iter().position(|s| s.name == "Background") {
            if self.verbose {
                colours::info("Running Background setup first...");
            }

            let bg = scenarios_vec.remove(pos);

            // Per-background backends (run on main thread, mutating self.env_vars)
            let mut terminal_backend =
                TerminalBackend::new(self.base_dir.clone(), settings.clone());
            let fs_backend = FileSystemBackend::new();
            let mut web_backend = WebBackend::new();
            let mut last_exit_code: Option<i32> = None;

            // Background was created in main as a single test with given steps.
            for test in &bg.tests {
                for step in &test.given {
                    if let GivenStep::Action(action) = step {
                        // Use the runner method which mutates self.env_vars
                        self.execute_action(
                            action,
                            &mut terminal_backend,
                            &fs_backend,
                            &mut web_backend,
                            &mut last_exit_code,
                            settings.timeout_seconds,
                        );
                    }
                }
            }

            // Capture headers set by the background web backend so scenarios inherit them
            bg_http_headers = web_backend.get_headers();

            if self.verbose {
                colours::success("Background setup applied to runner env_vars.");
            }
        }

        // -- Parallel execution using Rayon --
        //let mut test_states: HashMap<String, TestState> = HashMap::new();
        //let mut test_start_times: HashMap<String, Instant> = HashMap::new();

        let test_states = Arc::new(Mutex::new(HashMap::new()));
        let test_start_times = Arc::new(Mutex::new(HashMap::new()));

        // --- Main Test Loop ---
        let suite_start_time = Instant::now();

        // Use scenarios_vec (with Background already removed) for state registration
        // and partitioning to prevent the Background scenario from being run a second time.
        {
            let mut states = test_states.lock().unwrap();
            for sc in &scenarios_vec {
                for t in &sc.tests {
                    states
                        .entry(scoped_name(&sc.name, &t.name))
                        .or_insert(TestState::Pending);
                }
            }
        }

        // Separate parallel and sequential scenarios
        let (parallel_scenarios, sequential_scenarios): (Vec<_>, Vec<_>) =
            scenarios_vec.iter().cloned().partition(|s| s.parallel);

        if !parallel_scenarios.is_empty() {
            if self.verbose {
                colours::info(&format!(
                    "\nRunning {} scenarios in parallel...",
                    parallel_scenarios.len()
                ));
            }
            let parallel_results: Vec<Result<(), AppError>> = parallel_scenarios
                .par_iter()
                .cloned() // clone Scenario if needed so closure owns it
                .map(|scenario| {
                    // each closure runs in parallel; pass cloned Arcs
                    run_scenario(
                        &scenario,
                        &settings,
                        self.env_vars.clone(),
                        &self.tasks,
                        self.verbose,
                        &self.base_dir,
                        Arc::clone(&test_states),
                        Arc::clone(&test_start_times),
                        bg_http_headers.clone(),
                    )
                })
                .collect();

            // Propagate any errors (return first Err)
            for res in parallel_results {
                res?;
            }
        }

        if !sequential_scenarios.is_empty() {
            if self.verbose {
                colours::info(&format!(
                    "\nRunning {} scenarios sequentially...",
                    sequential_scenarios.len()
                ));
            }

            // Run sequential scenarios on current thread (or spawn them too, depending on desired semantics)
            for scenario in sequential_scenarios {
                run_scenario(
                    &scenario,
                    &settings,
                    self.env_vars.clone(),
                    &self.tasks,
                    self.verbose,
                    &self.base_dir,
                    Arc::clone(&test_states),
                    Arc::clone(&test_start_times),
                    bg_http_headers.clone(),
                )?;
            }
        }

        // --- Final Reporting ---
        let suite_duration = suite_start_time.elapsed();
        // Snapshot final maps for reporting
        let test_states_final = test_states.lock().unwrap().clone();
        let test_start_times_final = test_start_times.lock().unwrap().clone();

        // This is the logic from the old print_summary function
        let mut passed = 0;
        let mut failed = 0;
        let mut skipped = 0;
        for state in test_states_final.values() {
            match state {
                TestState::Passed => passed += 1,
                TestState::Failed(_) => failed += 1,
                TestState::Skipped => skipped += 1,
                _ => {}
            }
        }
        colours::info(&format!(
            "\nTest suite '{}' summary: {} tests run in {:.2}s ({} passed, {} failed, {} skipped)",
            suite_name,
            test_states_final.len(),
            suite_duration.as_secs_f32(),
            passed,
            failed,
            skipped
        ));

        if settings.report_format != ReportFormat::None {
            generate_choreo_report(
                suite_name,
                suite_start_time.elapsed(),
                &feature_name,
                &scenarios_vec,
                &test_states_final,
                &test_start_times_final,
                &mut self.env_vars,
                &settings,
                self.verbose,
            )?;

            if self.verbose {
                colours::success("Reports generated successfully.");
            }
        }

        let failures = test_states_final.values().filter(|s| s.is_failed()).count();
        if failures > settings.expected_failures {
            return Err(AppError::TestsFailed {
                count: failures,
                expected: settings.expected_failures,
            });
        }

        Ok(())
    }

    /// Dispatches an action to the correct backend.
    fn execute_action(
        &mut self, // Make it a method
        action: &Action,
        terminal: &mut TerminalBackend,
        fs: &FileSystemBackend,
        web: &mut WebBackend,
        last_exit_code: &mut Option<i32>,
        timeout_seconds: u64,
    ) {
        if self.verbose {
            colours::info(&format!("[RUNNER] Executing action: {:?}", action));
        }
        // Substitute variables in the action
        let substituted_action = substitute_variables_in_action(action, &self.env_vars);

        let env_vars = &mut self.env_vars;

        // Check if it's a terminal action
        if terminal.execute_action(
            &substituted_action,
            last_exit_code,
            Some(Duration::from_secs(timeout_seconds)),
            env_vars,
            self.verbose,
        ) {
            return;
        }
        // Check if it's a filesystem action
        if fs.execute_action(&substituted_action, terminal.get_cwd(), env_vars) {
            return;
        }

        // Check if it's a web action
        if web.execute_action(&substituted_action, env_vars, self.verbose) {
            return;
        } else {
            println!(
                "[WARNING] Web action failed to execute: {:?}",
                substituted_action
            );
        }
        println!(
            "[WARNING] Action not recognised by any backend: {:?}",
            action
        );
    }
}

// --- Thread-safe run_scenario ---
// Accepts shared Arcs for states/times so multiple scenarios can run in parallel.

/// Creates a scoped test name: "ScenarioName::TestName"
/// This ensures test names are unique across scenarios.
fn scoped_name(scenario_name: &str, test_name: &str) -> String {
    format!("{}::{}", scenario_name, test_name)
}

fn run_scenario(
    scenario: &Scenario,
    settings: &TestSuiteSettings,
    env_vars: HashMap<String, String>,
    tasks: &HashMap<String, TaskDef>,
    verbose: bool,
    base_dir: &PathBuf,
    test_states: Arc<Mutex<HashMap<String, TestState>>>,
    test_start_times: Arc<Mutex<HashMap<String, Instant>>>,
    initial_http_headers: HashMap<String, String>,
) -> Result<(), AppError> {
    // Per-scenario isolated backends and mutable state
    let mut terminal_backend = TerminalBackend::new(base_dir.clone(), settings.clone());
    let fs_backend = FileSystemBackend::new();
    let mut web_backend = WebBackend::with_headers(initial_http_headers);
    let mut system_backend = SystemBackend::new();
    let mut variables = env_vars.clone();
    let test_timeout = Duration::from_secs(settings.timeout_seconds);
    let mut last_exit_code: Option<i32> = None;
    let mut output_buffer = String::new();

    let expanded_tests = expand_foreach_blocks(scenario, &variables);
    let mut scenario_clone = scenario.clone();
    scenario_clone.tests = expanded_tests.clone();

    // Initialise tests states (insert Pending entries) under lock
    {
        let mut states = test_states.lock().unwrap();
        for test in &expanded_tests {
            states
                .entry(scoped_name(&scenario.name, &test.name))
                .or_insert(TestState::Pending);
        }
    }

    let scenario_start_time = Instant::now();
    colours::info(&format!("\nRunning scenario: '{}'", scenario.name));
    'scenario_loop: loop {
        let elapsed_since_scenario_start = scenario_start_time.elapsed();
        let mut progress_made = false;

        //let mut tests_to_start: Vec<(String, Vec<Action>)> = Vec::new();
        let mut tests_to_start: Vec<(String, Vec<Action>, bool)> = Vec::new();
        let mut tests_to_pass: Vec<String> = Vec::new();
        let mut immediate_failures: Vec<(String, String)> = Vec::new();

        // --- Checking Phase: take snapshots of shared maps and operate on snapshots ---
        let states_snapshot: HashMap<String, TestState> = {
            let locked = test_states.lock().unwrap();
            locked.clone()
        };
        let start_times_snapshot: HashMap<String, Instant> = {
            let locked = test_start_times.lock().unwrap();
            locked.clone()
        };

        // Build a scenario-scoped view of states for condition checking (e.g. HasSucceeded).
        // This maps bare test names to states for tests within the current scenario,
        // so `Test has_succeeded Setup` resolves to this scenario's `Setup`, not another's.
        let scenario_prefix = format!("{}::", scenario.name);
        let scoped_states_for_conditions: HashMap<String, TestState> = states_snapshot
            .iter()
            .filter_map(|(k, v)| {
                k.strip_prefix(&scenario_prefix)
                    .map(|bare| (bare.to_string(), v.clone()))
            })
            .collect();

        // Determine tests to evaluate (not done)
        let tests_to_check: Vec<TestCase> = expanded_tests
            .iter()
            .filter(|tc| {
                let key = scoped_name(&scenario.name, &tc.name);
                !states_snapshot.get(&key).map_or(false, |s| s.is_done())
            })
            .cloned()
            .collect();

        //println!("How many tests? '{}'", tests_to_check.len());
        for test_case in &tests_to_check {
            let scoped = scoped_name(&scenario.name, &test_case.name);
            let current_state = states_snapshot
                .get(&scoped)
                .cloned()
                .unwrap_or(TestState::Pending);
            //println!("Running test: '{}'", test_case.name);

            match current_state {
                TestState::Pending => {
                    // Extract conditions and actions from given steps, expanding task calls
                    let mut given_conditions: Vec<Condition> = Vec::new();
                    let mut given_actions: Vec<Action> = Vec::new();
                    for step in &test_case.given {
                        match step {
                            GivenStep::Condition(c) => given_conditions.push(c.clone()),
                            GivenStep::Action(a) => given_actions.push(a.clone()),
                            GivenStep::TaskCall(tc) => {
                                // Expand task call into actions and conditions
                                let (task_actions, task_conditions) =
                                    expand_task_call(tc, tasks, &variables);
                                given_actions.extend(task_actions);
                                given_conditions.extend(task_conditions);
                            }
                        }
                    }

                    let is_sync = is_synchronous(&test_case);
                    //println!("Test is sync = {}", is_sync);

                    let sync_test = is_synchronous(test_case);
                    if !sync_test {
                        terminal_backend.read_pty_output(&mut output_buffer);
                    }

                    if check_all_conditions_met(
                        "given",
                        &given_conditions,
                        &scoped_states_for_conditions,
                        &output_buffer,
                        &terminal_backend.last_stderr.clone(),
                        elapsed_since_scenario_start.as_secs_f32(),
                        &mut variables,
                        &last_exit_code,
                        &fs_backend,
                        &mut terminal_backend,
                        &mut web_backend,
                        &system_backend,
                        verbose,
                    ) {
                        tests_to_start.push((
                            test_case.name.clone(),
                            given_actions.clone(),
                            is_sync,
                        ));
                        //tests_to_start.push((test_case.name.clone(), given_actions));
                    }
                }
                TestState::Running => {
                    if !is_synchronous(test_case) {
                        terminal_backend.read_pty_output(&mut output_buffer);
                    }

                    let elapsed_for_test = start_times_snapshot
                        .get(&scoped)
                        .map_or(0.0, |start| start.elapsed().as_secs_f32());

                    // Extract conditions from then steps, expanding task calls
                    let mut then_conditions = extract_conditions_from_then_steps(&test_case.then);
                    for step in &test_case.then {
                        if let ThenStep::TaskCall(tc) = step {
                            let (_, task_conditions) = expand_task_call(tc, tasks, &variables);
                            then_conditions.extend(task_conditions);
                        }
                    }
                    if check_all_conditions_met(
                        "then",
                        &then_conditions,
                        &scoped_states_for_conditions,
                        &output_buffer,
                        &terminal_backend.last_stderr.clone(),
                        elapsed_for_test,
                        &mut variables,
                        &last_exit_code,
                        &fs_backend,
                        &mut terminal_backend,
                        &mut web_backend,
                        &system_backend,
                        verbose,
                    ) {
                        tests_to_pass.push(test_case.name.clone());
                    } else if start_times_snapshot
                        .get(&scoped)
                        .map_or(false, |start| start.elapsed() > test_timeout)
                    {
                        immediate_failures.push((
                            test_case.name.clone(),
                            format!("Test timed out after {} seconds", settings.timeout_seconds),
                        ));
                    }
                }
                _ => {}
            }
        }

        // --- Updating Phase: perform mutations under brief locks, but run actions without locks ---
        if !tests_to_start.is_empty() {
            progress_made = true;
            for (name, given_actions, is_sync) in tests_to_start {
                let test_case = expanded_tests.iter().find(|tc| tc.name == name).unwrap();
                let scoped = scoped_name(&scenario.name, &name);

                if is_sync {
                    //println!(" ▶️ Starting SYNC test: {}", name);
                    {
                        let mut states = test_states.lock().unwrap();
                        states.insert(scoped.clone(), TestState::Running);
                    }
                    {
                        let mut starts = test_start_times.lock().unwrap();
                        starts.insert(scoped.clone(), Instant::now());
                    }

                    // execute given actions and when actions (no locks held)
                    for given_action in &given_actions {
                        let substituted_action =
                            substitute_variables_in_action(given_action, &mut variables);
                        execute_action(
                            &substituted_action,
                            &mut terminal_backend,
                            &fs_backend,
                            &mut web_backend,
                            &mut system_backend,
                            &mut last_exit_code,
                            settings.timeout_seconds,
                            &mut variables,
                            verbose,
                        );
                    }
                    for step in &test_case.when {
                        match step {
                            WhenStep::Action(action) => {
                                let substituted_action =
                                    substitute_variables_in_action(action, &mut variables);
                                execute_action(
                                    &substituted_action,
                                    &mut terminal_backend,
                                    &fs_backend,
                                    &mut web_backend,
                                    &mut system_backend,
                                    &mut last_exit_code,
                                    settings.timeout_seconds,
                                    &mut variables,
                                    verbose,
                                );
                            }
                            WhenStep::TaskCall(tc) => {
                                // Expand task call and execute all resulting actions
                                let (task_actions, _) = expand_task_call(tc, tasks, &variables);
                                for action in task_actions {
                                    let substituted_action =
                                        substitute_variables_in_action(&action, &mut variables);
                                    execute_action(
                                        &substituted_action,
                                        &mut terminal_backend,
                                        &fs_backend,
                                        &mut web_backend,
                                        &mut system_backend,
                                        &mut last_exit_code,
                                        settings.timeout_seconds,
                                        &mut variables,
                                        verbose,
                                    );
                                }
                            }
                        }
                    }

                    if let Some(137) = last_exit_code {
                        break;
                    }

                    // Extract conditions from then steps, expanding task calls
                    let mut then_conditions_sync =
                        extract_conditions_from_then_steps(&test_case.then);
                    for step in &test_case.then {
                        if let ThenStep::TaskCall(tc) = step {
                            let (_, task_conditions) = expand_task_call(tc, tasks, &variables);
                            then_conditions_sync.extend(task_conditions);
                        }
                    }
                    let passed = check_all_conditions_met(
                        "then",
                        &then_conditions_sync,
                        &{
                            // Build scoped view for condition checking
                            let locked = test_states.lock().unwrap();
                            let prefix = format!("{}::", scenario.name);
                            locked
                                .iter()
                                .filter_map(|(k, v)| {
                                    k.strip_prefix(&prefix)
                                        .map(|bare| (bare.to_string(), v.clone()))
                                })
                                .collect::<HashMap<String, TestState>>()
                        },
                        &output_buffer,
                        &terminal_backend.last_stderr.clone(),
                        test_start_times
                            .lock()
                            .unwrap()
                            .get(&scoped)
                            .map_or(0.0, |start| start.elapsed().as_secs_f32()),
                        &mut variables,
                        &last_exit_code,
                        &fs_backend,
                        &mut terminal_backend,
                        &mut web_backend,
                        &system_backend,
                        verbose,
                    );

                    if let Some(mut state_guard) = test_states.lock().ok() {
                        if passed {
                            state_guard.insert(scoped.clone(), TestState::Passed);
                            colours::success(&format!(" 🟢 Test Passed: {}", name));
                        } else {
                            let mut error_msg = "Synchronous test conditions not met".to_string();
                            if !terminal_backend.last_stderr.is_empty() {
                                error_msg = format!(
                                    "Synchronous test failed. Stderr: {}",
                                    terminal_backend.last_stderr.trim()
                                );
                            }
                            state_guard
                                .insert(scoped.clone(), TestState::Failed(error_msg.clone()));
                            colours::error(&format!(" 🔴 Test Failed: {} - {}", name, error_msg));
                        }
                    }

                    // Mark that progress was made so the outer loop won't spin
                    progress_made = true;

                    if settings.stop_on_failure
                        && test_states.lock().unwrap().values().any(|s| s.is_failed())
                    {
                        break;
                    }
                    continue; // re-evaluate after a sync test finishes
                } else {
                    // async case: mark running and execute given/when without holding locks while executing actions
                    //println!(" ▶  Starting ASYNC test: {}", name);
                    {
                        let mut states = test_states.lock().unwrap();
                        states.insert(scoped.clone(), TestState::Running);
                    }
                    {
                        let mut starts = test_start_times.lock().unwrap();
                        starts.insert(scoped.clone(), Instant::now());
                    }

                    // Mark progress once the test has been started
                    progress_made = true;

                    for given_action in &given_actions {
                        let substituted_action =
                            substitute_variables_in_action(given_action, &mut variables);
                        execute_action(
                            &substituted_action,
                            &mut terminal_backend,
                            &fs_backend,
                            &mut web_backend,
                            &mut system_backend,
                            &mut last_exit_code,
                            settings.timeout_seconds,
                            &mut variables,
                            verbose,
                        );
                    }
                    for step in &test_case.when {
                        match step {
                            WhenStep::Action(action) => {
                                let substituted_action =
                                    substitute_variables_in_action(action, &mut variables);
                                execute_action(
                                    &substituted_action,
                                    &mut terminal_backend,
                                    &fs_backend,
                                    &mut web_backend,
                                    &mut system_backend,
                                    &mut last_exit_code,
                                    settings.timeout_seconds,
                                    &mut variables,
                                    verbose,
                                );
                            }
                            WhenStep::TaskCall(tc) => {
                                // Expand task call and execute all resulting actions
                                let (task_actions, _) = expand_task_call(tc, tasks, &variables);
                                for action in task_actions {
                                    let substituted_action =
                                        substitute_variables_in_action(&action, &mut variables);
                                    execute_action(
                                        &substituted_action,
                                        &mut terminal_backend,
                                        &fs_backend,
                                        &mut web_backend,
                                        &mut system_backend,
                                        &mut last_exit_code,
                                        settings.timeout_seconds,
                                        &mut variables,
                                        verbose,
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }

        if !tests_to_pass.is_empty() {
            progress_made = true;
            let mut states = test_states.lock().unwrap();
            for name in tests_to_pass {
                let scoped = scoped_name(&scenario.name, &name);
                if let Some(state) = states.get_mut(&scoped) {
                    if !state.is_done() {
                        *state = TestState::Passed;
                        colours::success(&format!(" 🟢  Test Passed: {}", name));
                    }
                }
            }
        }

        if !immediate_failures.is_empty() {
            progress_made = true;
            let mut states = test_states.lock().unwrap();
            for (name, error_msg) in immediate_failures {
                let scoped = scoped_name(&scenario.name, &name);
                if let Some(state) = states.get_mut(&scoped) {
                    if !state.is_done() {
                        *state = TestState::Failed(error_msg.clone());
                        colours::error(&format!(" 🔴  Test Failed: {} - {}", name, error_msg));
                    }
                }
            }
        }

        // Check if all tests in this scenario are done (use expanded_tests to include foreach-generated tests)
        let all_done = {
            let states = test_states.lock().unwrap();
            expanded_tests.iter().all(|t| {
                let key = scoped_name(&scenario.name, &t.name);
                states.get(&key).map_or(false, |s| s.is_done())
            })
        };

        if all_done {
            if !scenario.after.is_empty() {
                colours::info("\nRunning after block...");
                for action in &scenario.after {
                    let substituted_action = substitute_variables_in_action(action, &mut variables);
                    execute_action(
                        &substituted_action,
                        &mut terminal_backend,
                        &fs_backend,
                        &mut web_backend,
                        &mut system_backend,
                        &mut last_exit_code,
                        settings.timeout_seconds,
                        &mut variables,
                        verbose,
                    );
                }
            }
            break;
        }

        // stop_on_failure handling across global shared state
        if settings.stop_on_failure && test_states.lock().unwrap().values().any(|s| s.is_failed()) {
            let mut states = test_states.lock().unwrap();
            for (_name, state) in states.iter_mut() {
                if matches!(*state, TestState::Pending | TestState::Running) {
                    *state = TestState::Skipped;
                }
            }
            colours::error("\nStopping test run due to failure (stop_on_failure is true).");
            break 'scenario_loop;
        }

        if !progress_made {
            thread::sleep(Duration::from_millis(50));
            let elapsed_since_suite_start = scenario_start_time.elapsed();
            if elapsed_since_suite_start > test_timeout + Duration::from_secs(1) {
                colours::warn("\nWarning: No progress was made in the last loop iteration, and the scenario is not complete. Marking remaining tests as skipped.");
                let mut states = test_states.lock().unwrap();
                for test in &expanded_tests {
                    let key = scoped_name(&scenario.name, &test.name);
                    if let Some(state) = states.get_mut(&key) {
                        if matches!(*state, TestState::Pending | TestState::Running) {
                            *state = TestState::Skipped;
                        }
                    }
                }
                break;
            }
        }
    } // end scenario loop

    Ok(())
}

/// Dispatches an action to the correct backend.
fn execute_action(
    action: &Action,
    terminal: &mut TerminalBackend,
    fs: &FileSystemBackend,
    web: &mut WebBackend,
    system: &mut SystemBackend,
    last_exit_code: &mut Option<i32>,
    timeout_seconds: u64,
    env_vars: &mut HashMap<String, String>,
    verbose: bool,
) {
    if verbose {
        colours::info(&format!("[RUNNER] Executing action: {:?}", action));
    }
    // Substitute variables in the action
    let substituted_action = substitute_variables_in_action(action, env_vars);

    // Check if it's a system action first
    if system.execute_action(&substituted_action, env_vars, verbose) {
        return;
    }

    // Check if it's a terminal action
    if terminal.execute_action(
        &substituted_action,
        last_exit_code,
        Some(Duration::from_secs(timeout_seconds)),
        env_vars,
        verbose,
    ) {
        return;
    }
    // Check if it's a filesystem action
    if fs.execute_action(&substituted_action, terminal.get_cwd(), env_vars) {
        return;
    }

    // Check if it's a web action
    if web.execute_action(&substituted_action, env_vars, verbose) {
        return;
    } else {
        println!(
            "[WARNING] Web action failed to execute: {:?}",
            substituted_action
        );
    }
    println!(
        "[WARNING] Action not recognised by any backend: {:?}",
        action
    );
}

/// Expands a TaskCall into its constituent actions and conditions by binding arguments to parameters.
pub fn expand_task_call(
    task_call: &TaskCall,
    tasks: &HashMap<String, TaskDef>,
    env_vars: &HashMap<String, String>,
) -> (Vec<Action>, Vec<Condition>) {
    let mut actions = Vec::new();
    let mut conditions = Vec::new();

    let Some(task_def) = tasks.get(&task_call.name) else {
        eprintln!("[WARNING] Task '{}' not found", task_call.name);
        return (actions, conditions);
    };

    // Build parameter bindings
    let mut task_scope = env_vars.clone();
    for (i, param) in task_def.parameters.iter().enumerate() {
        if let Some(arg) = task_call.arguments.get(i) {
            let value = match arg {
                TaskArg::String(s) => s.clone(),
                TaskArg::Number(n) => n.to_string(),
                TaskArg::Duration(d) => format!("{}s", d),
                TaskArg::VariableRef(v) => {
                    // Resolve variable reference from env_vars
                    let var_name = v.trim_start_matches("${").trim_end_matches('}');
                    env_vars.get(var_name).cloned().unwrap_or_else(|| v.clone())
                }
            };
            task_scope.insert(param.clone(), value);
        }
    }

    // Expand task body items with parameter substitution
    for item in &task_def.body {
        match item {
            TaskBodyItem::Action(action) => {
                let substituted = substitute_variables_in_action(action, &task_scope);
                actions.push(substituted);
            }
            TaskBodyItem::Condition(condition) => {
                let substituted = substitute_variables_in_condition(condition, &task_scope);
                conditions.push(substituted);
            }
        }
    }

    (actions, conditions)
}