prodigy 0.4.4

Turn ad-hoc Claude sessions into reproducible development pipelines with parallel AI agents
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
use crate::cook::execution::interpolation::{InterpolationContext, InterpolationEngine};
use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;

/// Standard variable names that work in ALL execution modes
/// These are the ONLY variable names that should be used
pub struct StandardVariables;

impl StandardVariables {
    // Input variables - consistent regardless of source
    pub const ITEM: &'static str = "item"; // Current item being processed
    pub const INDEX: &'static str = "item_index"; // Zero-based index
    pub const TOTAL: &'static str = "item_total"; // Total number of items

    // For backwards compatibility during migration
    pub const ITEM_VALUE: &'static str = "item.value"; // The actual value
    pub const ITEM_PATH: &'static str = "item.path"; // For file inputs
    pub const ITEM_NAME: &'static str = "item.name"; // Display name

    // Workflow context variables
    pub const WORKFLOW_NAME: &'static str = "workflow.name";
    pub const WORKFLOW_ID: &'static str = "workflow.id";
    pub const ITERATION: &'static str = "workflow.iteration";

    // Step context variables
    pub const STEP_NAME: &'static str = "step.name";
    pub const STEP_INDEX: &'static str = "step.index";

    // Output capture variables
    pub const LAST_OUTPUT: &'static str = "last.output";
    pub const LAST_EXIT_CODE: &'static str = "last.exit_code";

    // MapReduce specific (only available in those contexts)
    pub const MAP_KEY: &'static str = "map.key"; // Key for map output
    pub const MAP_RESULTS: &'static str = "map.results"; // Aggregated map results
    pub const WORKER_ID: &'static str = "worker.id"; // Parallel worker ID
}

/// Represents different types of execution inputs
#[derive(Debug, Clone)]
pub enum ExecutionInput {
    Argument(String),
    FilePath(String),
    JsonObject(Value),
}

/// Execution mode for the workflow
#[derive(Debug, Clone)]
pub enum ExecutionMode {
    Standard,
    WithArguments,
    WithFilePattern,
    MapReduce,
}

/// Unified variable context that ALL paths use
#[derive(Debug, Clone)]
pub struct VariableContext {
    variables: HashMap<String, Value>, // ALL variables stored here
    aliases: HashMap<String, String>,  // For backwards compatibility
}

impl VariableContext {
    /// Create context for any execution mode with STANDARD variable names
    pub fn from_execution_input(
        _mode: &ExecutionMode,
        input: &ExecutionInput,
        index: usize,
        total: usize,
    ) -> Self {
        let mut variables = HashMap::new();
        let mut aliases = HashMap::new();

        // Standard variables that work everywhere
        match input {
            ExecutionInput::Argument(arg) => {
                variables.insert(StandardVariables::ITEM.into(), json!(arg));
                variables.insert(StandardVariables::ITEM_VALUE.into(), json!(arg));
                // Legacy compatibility
                aliases.insert("ARG".into(), StandardVariables::ITEM_VALUE.into());
                aliases.insert("ARGUMENT".into(), StandardVariables::ITEM_VALUE.into());
            }
            ExecutionInput::FilePath(path) => {
                variables.insert(StandardVariables::ITEM.into(), json!(path));
                variables.insert(StandardVariables::ITEM_PATH.into(), json!(path));
                // Legacy compatibility
                aliases.insert("FILE".into(), StandardVariables::ITEM_PATH.into());
                aliases.insert("FILE_PATH".into(), StandardVariables::ITEM_PATH.into());
            }
            ExecutionInput::JsonObject(obj) => {
                // MapReduce items - use the SAME variable names!
                variables.insert(StandardVariables::ITEM.into(), obj.clone());
                // Flatten for convenience
                if let Some(path) = obj.get("file_path") {
                    variables.insert(StandardVariables::ITEM_PATH.into(), path.clone());
                }
                if let Some(name) = obj.get("name") {
                    variables.insert(StandardVariables::ITEM_NAME.into(), name.clone());
                }
            }
        }

        // Always set standard context variables
        variables.insert(StandardVariables::INDEX.into(), json!(index));
        variables.insert(StandardVariables::TOTAL.into(), json!(total));

        Self { variables, aliases }
    }

    /// Create an empty context for testing
    pub fn empty() -> Self {
        Self {
            variables: HashMap::new(),
            aliases: HashMap::new(),
        }
    }

    /// Add a variable to the context
    pub fn add_variable(&mut self, key: impl Into<String>, value: Value) {
        self.variables.insert(key.into(), value);
    }

    /// Add an alias for backwards compatibility
    pub fn add_alias(&mut self, old_name: impl Into<String>, new_name: impl Into<String>) {
        self.aliases.insert(old_name.into(), new_name.into());
    }

    /// Get a variable value
    pub fn get(&self, key: &str) -> Option<&Value> {
        // Check if it's an alias first
        if let Some(actual_key) = self.aliases.get(key) {
            self.variables.get(actual_key)
        } else {
            self.variables.get(key)
        }
    }

    /// Use the SAME interpolation engine for ALL paths
    /// This ensures consistent behavior across all execution modes
    pub fn interpolate(&self, template: &str) -> Result<String> {
        // First resolve aliases for backwards compatibility
        let template = self.resolve_aliases(template);

        // Convert our variables to InterpolationContext
        // We need to organize nested variables properly
        let mut context = InterpolationContext::new();
        let mut nested_objects: HashMap<String, HashMap<String, Value>> = HashMap::new();

        for (key, value) in &self.variables {
            // Handle nested keys like "item.value" by grouping them
            if key.contains('.') {
                let parts: Vec<&str> = key.split('.').collect();
                if parts.len() == 2 {
                    // Add to nested object
                    nested_objects
                        .entry(parts[0].to_string())
                        .or_default()
                        .insert(parts[1].to_string(), value.clone());
                } else {
                    // Complex nesting not supported yet
                    context.set(key.clone(), value.clone());
                }
            } else {
                context.set(key.clone(), value.clone());
            }
        }

        // Add nested objects to context
        for (obj_name, fields) in nested_objects {
            context.set(obj_name, json!(fields));
        }

        // Use the existing MapReduce InterpolationEngine for ALL paths!
        // This gives everyone nested access, defaults, etc.
        let mut engine = InterpolationEngine::new(false);

        engine
            .interpolate(&template, &context)
            .context("Failed to interpolate variables")
    }

    fn resolve_aliases(&self, template: &str) -> String {
        self.aliases
            .iter()
            .fold(template.to_string(), |acc, (old, new)| {
                acc.replace(&format!("${{{}}}", old), &format!("${{{}}}", new))
                    .replace(&format!("${}", old), &format!("${}", new))
            })
    }

    /// Convert to a format the InterpolationEngine can use
    pub fn to_interpolation_context(&self) -> InterpolationContext {
        let mut context = InterpolationContext::new();
        for (key, value) in &self.variables {
            context.set(key.clone(), value.clone());
        }
        context
    }

    /// Set workflow metadata
    pub fn set_workflow_metadata(&mut self, name: &str, id: &str, iteration: usize) {
        self.variables
            .insert(StandardVariables::WORKFLOW_NAME.into(), json!(name));
        self.variables
            .insert(StandardVariables::WORKFLOW_ID.into(), json!(id));
        self.variables
            .insert(StandardVariables::ITERATION.into(), json!(iteration));
    }

    /// Set step metadata
    pub fn set_step_metadata(&mut self, name: &str, index: usize) {
        self.variables
            .insert(StandardVariables::STEP_NAME.into(), json!(name));
        self.variables
            .insert(StandardVariables::STEP_INDEX.into(), json!(index));
    }

    /// Set command output results
    pub fn set_last_output(&mut self, output: &str, exit_code: i32) {
        self.variables
            .insert(StandardVariables::LAST_OUTPUT.into(), json!(output));
        self.variables
            .insert(StandardVariables::LAST_EXIT_CODE.into(), json!(exit_code));
    }

    /// Set MapReduce specific variables
    pub fn set_mapreduce_metadata(&mut self, worker_id: Option<usize>, map_key: Option<&str>) {
        if let Some(id) = worker_id {
            self.variables
                .insert(StandardVariables::WORKER_ID.into(), json!(id));
        }
        if let Some(key) = map_key {
            self.variables
                .insert(StandardVariables::MAP_KEY.into(), json!(key));
        }
    }

    /// Set aggregated map results for reduce phase
    pub fn set_map_results(&mut self, results: Value) {
        self.variables
            .insert(StandardVariables::MAP_RESULTS.into(), results);
    }
}

/// Format for captured output
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "snake_case")]
pub enum CaptureFormat {
    /// Raw string output (default)
    #[default]
    String,
    /// Parse as JSON
    Json,
    /// Split into array of lines
    Lines,
    /// Parse as number
    Number,
    /// Parse as boolean
    Boolean,
}

/// Which streams to capture from command execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaptureStreams {
    #[serde(default = "default_true")]
    pub stdout: bool,
    #[serde(default)]
    pub stderr: bool,
    #[serde(default = "default_true")]
    pub exit_code: bool,
    #[serde(default = "default_true")]
    pub success: bool,
    #[serde(default = "default_true")]
    pub duration: bool,
}

impl Default for CaptureStreams {
    fn default() -> Self {
        Self {
            stdout: true,
            stderr: false,
            exit_code: true,
            success: true,
            duration: true,
        }
    }
}

fn default_true() -> bool {
    true
}

/// Captured value from command execution
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CapturedValue {
    /// Simple string value
    String(String),
    /// Numeric value
    Number(f64),
    /// Boolean value
    Boolean(bool),
    /// JSON value
    Json(Value),
    /// Array of values
    Array(Vec<CapturedValue>),
    /// Object with key-value pairs
    Object(HashMap<String, CapturedValue>),
}

impl std::fmt::Display for CapturedValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CapturedValue::String(s) => write!(f, "{}", s),
            CapturedValue::Number(n) => write!(f, "{}", n),
            CapturedValue::Boolean(b) => write!(f, "{}", b),
            CapturedValue::Json(j) => write!(f, "{}", j),
            CapturedValue::Array(_) | CapturedValue::Object(_) => {
                // Convert to JSON for proper formatting when used in string interpolation
                // This ensures that ${map.results} produces valid JSON for write_file
                let json_value = self.to_json();
                write!(f, "{}", json_value)
            }
        }
    }
}

impl CapturedValue {
    /// Convert to JSON value
    pub fn to_json(&self) -> Value {
        match self {
            CapturedValue::String(s) => Value::String(s.clone()),
            CapturedValue::Number(n) => json!(n),
            CapturedValue::Boolean(b) => Value::Bool(*b),
            CapturedValue::Json(j) => j.clone(),
            CapturedValue::Array(arr) => {
                let values: Vec<Value> = arr.iter().map(|v| v.to_json()).collect();
                Value::Array(values)
            }
            CapturedValue::Object(map) => {
                let mut obj = serde_json::Map::new();
                for (k, v) in map {
                    obj.insert(k.clone(), v.to_json());
                }
                Value::Object(obj)
            }
        }
    }
}

impl From<Value> for CapturedValue {
    fn from(value: Value) -> Self {
        match value {
            Value::String(s) => CapturedValue::String(s),
            Value::Number(n) => {
                if let Some(f) = n.as_f64() {
                    CapturedValue::Number(f)
                } else if let Some(i) = n.as_i64() {
                    CapturedValue::Number(i as f64)
                } else if let Some(u) = n.as_u64() {
                    CapturedValue::Number(u as f64)
                } else {
                    CapturedValue::Json(Value::Number(n))
                }
            }
            Value::Bool(b) => CapturedValue::Boolean(b),
            Value::Array(arr) => {
                let values: Vec<CapturedValue> = arr.into_iter().map(Into::into).collect();
                CapturedValue::Array(values)
            }
            Value::Object(obj) => {
                let mut map = HashMap::new();
                for (k, v) in obj {
                    map.insert(k, v.into());
                }
                CapturedValue::Object(map)
            }
            Value::Null => CapturedValue::String("null".to_string()),
        }
    }
}

/// Command execution result for variable capture
pub struct CommandResult {
    pub stdout: Option<String>,
    pub stderr: Option<String>,
    pub exit_code: i32,
    pub success: bool,
    pub duration: Duration,
}

/// Thread-safe variable storage for captured outputs
#[derive(Debug, Clone)]
pub struct VariableStore {
    variables: Arc<RwLock<HashMap<String, CapturedValue>>>,
    parent: Option<Arc<VariableStore>>,
}

impl Default for VariableStore {
    fn default() -> Self {
        Self::new()
    }
}

impl VariableStore {
    /// Create a new variable store
    pub fn new() -> Self {
        Self {
            variables: Arc::new(RwLock::new(HashMap::new())),
            parent: None,
        }
    }

    /// Create a child store with this store as parent
    pub fn child(&self) -> Self {
        Self {
            variables: Arc::new(RwLock::new(HashMap::new())),
            parent: Some(Arc::new(self.clone())),
        }
    }

    /// Set a variable value
    pub async fn set(&self, name: impl Into<String>, value: CapturedValue) {
        let mut vars = self.variables.write().await;
        vars.insert(name.into(), value);
    }

    /// Get a variable value
    pub fn get<'a>(
        &'a self,
        name: &'a str,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Option<CapturedValue>> + Send + 'a>>
    {
        Box::pin(async move {
            // Check local variables first
            let vars = self.variables.read().await;
            if let Some(value) = vars.get(name) {
                return Some(value.clone());
            }
            drop(vars); // Release lock before checking parent

            // Check parent if not found locally
            if let Some(parent) = &self.parent {
                parent.get(name).await
            } else {
                None
            }
        })
    }

    /// Capture command result into variables
    pub async fn capture_command_result(
        &self,
        name: &str,
        result: CommandResult,
        format: CaptureFormat,
        streams: &CaptureStreams,
    ) -> Result<()> {
        // Capture main output based on format
        if streams.stdout {
            let value = match format {
                CaptureFormat::String => {
                    CapturedValue::String(result.stdout.clone().unwrap_or_default())
                }
                CaptureFormat::Json => {
                    let json_str = result.stdout.as_deref().unwrap_or("null");
                    let json_value: Value = serde_json::from_str(json_str)
                        .map_err(|e| anyhow!("Failed to parse JSON output: {}", e))?;
                    CapturedValue::from(json_value)
                }
                CaptureFormat::Lines => {
                    let lines = result
                        .stdout
                        .as_deref()
                        .unwrap_or("")
                        .lines()
                        .map(|s| CapturedValue::String(s.to_string()))
                        .collect();
                    CapturedValue::Array(lines)
                }
                CaptureFormat::Number => {
                    let num_str = result.stdout.as_deref().unwrap_or("0").trim();
                    let num = num_str
                        .parse::<f64>()
                        .map_err(|e| anyhow!("Failed to parse number '{}': {}", num_str, e))?;
                    CapturedValue::Number(num)
                }
                CaptureFormat::Boolean => {
                    let bool_str = result.stdout.as_deref().unwrap_or("false").trim();
                    let val = bool_str.parse::<bool>().unwrap_or(result.success);
                    CapturedValue::Boolean(val)
                }
            };
            self.set(name, value).await;
        }

        // Capture stderr if requested
        if streams.stderr {
            if let Some(stderr) = &result.stderr {
                self.set(
                    format!("{}.stderr", name),
                    CapturedValue::String(stderr.clone()),
                )
                .await;
            }
        }

        // Capture metadata fields
        if streams.exit_code {
            self.set(
                format!("{}.exit_code", name),
                CapturedValue::Number(result.exit_code as f64),
            )
            .await;
        }

        if streams.success {
            self.set(
                format!("{}.success", name),
                CapturedValue::Boolean(result.success),
            )
            .await;
        }

        if streams.duration {
            self.set(
                format!("{}.duration", name),
                CapturedValue::Number(result.duration.as_secs_f64()),
            )
            .await;
        }

        Ok(())
    }

    /// Resolve a variable path (e.g., "var.field.subfield")
    pub async fn resolve_path(&self, path: &str) -> Result<CapturedValue> {
        let parts: Vec<&str> = path.split('.').collect();

        // Get base variable
        let base_value = self
            .get(parts[0])
            .await
            .ok_or_else(|| anyhow!("Variable '{}' not found", parts[0]))?;

        // Navigate nested path
        let mut current = base_value;
        for part in &parts[1..] {
            current = match current {
                CapturedValue::Json(ref obj) => {
                    if let Some(value) = obj.get(*part) {
                        value.clone().into()
                    } else {
                        return Err(anyhow!("Field '{}' not found in JSON object", part));
                    }
                }
                CapturedValue::Object(ref map) => map
                    .get(*part)
                    .ok_or_else(|| anyhow!("Field '{}' not found in object", part))?
                    .clone(),
                _ => {
                    return Err(anyhow!(
                        "Cannot access field '{}' on non-object value",
                        part
                    ))
                }
            };
        }

        Ok(current)
    }

    /// Get all variables as a HashMap for interpolation
    pub fn to_hashmap(
        &self,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = HashMap<String, String>> + Send + '_>>
    {
        Box::pin(async move {
            let mut result = HashMap::new();

            // Get parent variables first
            if let Some(parent) = &self.parent {
                result.extend(parent.to_hashmap().await);
            }

            // Override with local variables
            let vars = self.variables.read().await;
            for (key, value) in vars.iter() {
                result.insert(key.clone(), value.to_string());
            }

            result
        })
    }

    /// Get all variables as a HashMap (flattened, including parent variables)
    pub fn get_all(
        &self,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = HashMap<String, CapturedValue>> + Send + '_>,
    > {
        Box::pin(async move {
            let mut result = HashMap::new();

            // Get parent variables first (they have lower precedence)
            if let Some(parent) = &self.parent {
                let parent_vars = parent.get_all().await;
                for (k, v) in parent_vars {
                    result.insert(k, v);
                }
            }

            // Override with local variables
            let vars = self.variables.read().await;
            for (key, value) in vars.iter() {
                result.insert(key.clone(), value.clone());
            }

            result
        })
    }

    /// Get all variables as JSON for debugging
    pub fn to_json(
        &self,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + '_>> {
        Box::pin(async move {
            let mut result = serde_json::Map::new();

            // Get parent variables first
            if let Some(parent) = &self.parent {
                if let Value::Object(parent_map) = parent.to_json().await {
                    result.extend(parent_map);
                }
            }

            // Override with local variables
            let vars = self.variables.read().await;
            for (key, value) in vars.iter() {
                result.insert(key.clone(), value.to_json());
            }

            Value::Object(result)
        })
    }
}

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

    #[test]
    fn test_standard_variables_from_argument() {
        let input = ExecutionInput::Argument("test_arg".to_string());
        let ctx =
            VariableContext::from_execution_input(&ExecutionMode::WithArguments, &input, 0, 3);

        assert_eq!(ctx.get("item"), Some(&json!("test_arg")));
        assert_eq!(ctx.get("item.value"), Some(&json!("test_arg")));
        assert_eq!(ctx.get("item_index"), Some(&json!(0)));
        assert_eq!(ctx.get("item_total"), Some(&json!(3)));

        // Test legacy alias
        assert_eq!(ctx.get("ARG"), Some(&json!("test_arg")));
    }

    #[test]
    fn test_standard_variables_from_file() {
        let input = ExecutionInput::FilePath("/path/to/file.txt".to_string());
        let ctx =
            VariableContext::from_execution_input(&ExecutionMode::WithFilePattern, &input, 1, 5);

        assert_eq!(ctx.get("item"), Some(&json!("/path/to/file.txt")));
        assert_eq!(ctx.get("item.path"), Some(&json!("/path/to/file.txt")));
        assert_eq!(ctx.get("item_index"), Some(&json!(1)));
        assert_eq!(ctx.get("item_total"), Some(&json!(5)));

        // Test legacy aliases
        assert_eq!(ctx.get("FILE"), Some(&json!("/path/to/file.txt")));
        assert_eq!(ctx.get("FILE_PATH"), Some(&json!("/path/to/file.txt")));
    }

    #[test]
    fn test_standard_variables_from_json() {
        let obj = json!({
            "file_path": "/path/to/data.json",
            "name": "Test Item",
            "value": 42
        });
        let input = ExecutionInput::JsonObject(obj.clone());
        let ctx = VariableContext::from_execution_input(&ExecutionMode::MapReduce, &input, 2, 10);

        assert_eq!(ctx.get("item"), Some(&obj));
        assert_eq!(ctx.get("item.path"), Some(&json!("/path/to/data.json")));
        assert_eq!(ctx.get("item.name"), Some(&json!("Test Item")));
        assert_eq!(ctx.get("item_index"), Some(&json!(2)));
        assert_eq!(ctx.get("item_total"), Some(&json!(10)));
    }

    #[test]
    fn test_variable_interpolation() {
        let input = ExecutionInput::Argument("test_file.txt".to_string());
        let mut ctx =
            VariableContext::from_execution_input(&ExecutionMode::WithArguments, &input, 0, 1);

        ctx.set_workflow_metadata("test_workflow", "wf-123", 1);
        ctx.set_step_metadata("process_file", 0);

        let template = "Processing ${item.value} in workflow ${workflow.name} (step ${step.index})";
        let result = ctx.interpolate(template).unwrap();

        assert_eq!(
            result,
            "Processing test_file.txt in workflow test_workflow (step 0)"
        );
    }

    #[test]
    fn test_alias_resolution() {
        let input = ExecutionInput::FilePath("/data/file.txt".to_string());
        let ctx =
            VariableContext::from_execution_input(&ExecutionMode::WithFilePattern, &input, 0, 1);

        // Test that legacy variable names work through aliases
        let template = "File: ${FILE} or ${FILE_PATH} or ${item.path}";
        let resolved = ctx.resolve_aliases(template);

        assert!(resolved.contains("${item.path}"));
        assert_eq!(resolved.matches("${item.path}").count(), 3);
    }

    #[test]
    fn test_mapreduce_metadata() {
        let mut ctx = VariableContext::empty();

        ctx.set_mapreduce_metadata(Some(3), Some("key_123"));
        ctx.set_map_results(json!({"total": 100, "processed": 95}));

        assert_eq!(ctx.get("worker.id"), Some(&json!(3)));
        assert_eq!(ctx.get("map.key"), Some(&json!("key_123")));
        assert_eq!(
            ctx.get("map.results"),
            Some(&json!({"total": 100, "processed": 95}))
        );
    }

    #[test]
    fn test_output_capture() {
        let mut ctx = VariableContext::empty();

        ctx.set_last_output("Command completed successfully", 0);

        assert_eq!(
            ctx.get("last.output"),
            Some(&json!("Command completed successfully"))
        );
        assert_eq!(ctx.get("last.exit_code"), Some(&json!(0)));
    }

    #[tokio::test]
    async fn test_variable_store_basic() {
        let store = VariableStore::new();

        // Set and get simple values
        store
            .set("name", CapturedValue::String("test".to_string()))
            .await;
        store.set("count", CapturedValue::Number(42.0)).await;
        store.set("enabled", CapturedValue::Boolean(true)).await;

        assert_eq!(store.get("name").await.unwrap().to_string(), "test");
        assert_eq!(store.get("count").await.unwrap().to_string(), "42");
        assert_eq!(store.get("enabled").await.unwrap().to_string(), "true");
    }

    #[tokio::test]
    async fn test_variable_store_hierarchy() {
        let parent = VariableStore::new();
        parent
            .set("parent_var", CapturedValue::String("parent".to_string()))
            .await;

        let child = parent.child();
        child
            .set("child_var", CapturedValue::String("child".to_string()))
            .await;

        // Child can access both parent and own variables
        assert_eq!(child.get("parent_var").await.unwrap().to_string(), "parent");
        assert_eq!(child.get("child_var").await.unwrap().to_string(), "child");

        // Parent cannot access child variables
        assert!(parent.get("child_var").await.is_none());
    }

    #[tokio::test]
    async fn test_capture_command_result() {
        let store = VariableStore::new();

        let result = CommandResult {
            stdout: Some("hello world".to_string()),
            stderr: Some("warning".to_string()),
            exit_code: 0,
            success: true,
            duration: Duration::from_secs(5),
        };

        store
            .capture_command_result(
                "cmd",
                result,
                CaptureFormat::String,
                &CaptureStreams {
                    stdout: true,
                    stderr: true,
                    ..Default::default()
                },
            )
            .await
            .unwrap();

        assert_eq!(store.get("cmd").await.unwrap().to_string(), "hello world");
        assert_eq!(
            store.get("cmd.stderr").await.unwrap().to_string(),
            "warning"
        );
        assert_eq!(store.get("cmd.exit_code").await.unwrap().to_string(), "0");
        assert_eq!(store.get("cmd.success").await.unwrap().to_string(), "true");
    }

    #[tokio::test]
    async fn test_json_capture() {
        let store = VariableStore::new();

        let result = CommandResult {
            stdout: Some(r#"{"name": "test", "count": 42}"#.to_string()),
            stderr: None,
            exit_code: 0,
            success: true,
            duration: Duration::from_secs(1),
        };

        store
            .capture_command_result(
                "data",
                result,
                CaptureFormat::Json,
                &CaptureStreams::default(),
            )
            .await
            .unwrap();

        // Test nested path resolution
        let name = store.resolve_path("data.name").await.unwrap();
        assert_eq!(name.to_string(), "test");

        let count = store.resolve_path("data.count").await.unwrap();
        assert_eq!(count.to_string(), "42");
    }

    #[tokio::test]
    async fn test_lines_capture() {
        let store = VariableStore::new();

        let result = CommandResult {
            stdout: Some("line1\nline2\nline3".to_string()),
            stderr: None,
            exit_code: 0,
            success: true,
            duration: Duration::from_secs(1),
        };

        store
            .capture_command_result(
                "lines",
                result,
                CaptureFormat::Lines,
                &CaptureStreams::default(),
            )
            .await
            .unwrap();

        let lines = store.get("lines").await.unwrap();
        match lines {
            CapturedValue::Array(arr) => {
                assert_eq!(arr.len(), 3);
                assert_eq!(arr[0].to_string(), "line1");
                assert_eq!(arr[1].to_string(), "line2");
                assert_eq!(arr[2].to_string(), "line3");
            }
            _ => panic!("Expected array value"),
        }
    }

    #[test]
    fn test_interpolation_with_captured_variables() {
        let mut ctx = VariableContext::empty();

        // Simulate captured variables from different commands
        ctx.add_variable("shell.output", json!("build successful"));
        ctx.add_variable("test.output", json!("all tests passed"));
        ctx.add_variable("custom_var", json!("custom value"));

        // Test interpolation with captured variables
        let template = "Build: ${shell.output}, Tests: ${test.output}, Custom: ${custom_var}";
        let result = ctx.interpolate(template).unwrap();

        assert_eq!(
            result,
            "Build: build successful, Tests: all tests passed, Custom: custom value"
        );
    }

    #[test]
    fn test_interpolation_missing_variable_fallback() {
        let mut ctx = VariableContext::empty();
        ctx.add_variable("existing", json!("present"));

        // Test with missing variable (should use empty string or fail gracefully)
        let template = "Existing: ${existing}, Missing: ${missing|default:not_found}";
        let result = ctx.interpolate(template);

        // The interpolation should handle missing variables
        assert!(result.is_ok());
    }

    #[test]
    fn test_complex_nested_interpolation() {
        let mut ctx = VariableContext::empty();

        // Add nested JSON structure
        let nested = json!({
            "build": {
                "status": "success",
                "time": 123,
                "artifacts": ["app.exe", "lib.dll"]
            }
        });
        ctx.add_variable("result", nested);

        // Test nested field access
        let template = "Status: ${result.build.status}, Time: ${result.build.time}s";
        let result = ctx.interpolate(template).unwrap();

        assert_eq!(result, "Status: success, Time: 123s");
    }

    #[test]
    fn test_interpolation_with_mixed_sources() {
        let mut ctx = VariableContext::empty();

        // Mix of workflow variables and captured outputs
        ctx.set_workflow_metadata("test-workflow", "wf-123", 1);
        ctx.add_variable("git.branch", json!("main"));
        ctx.add_variable("commit.hash", json!("abc123"));
        ctx.set_last_output("Deploy completed", 0);

        let template = concat!(
            "Workflow: ${workflow.name} (${workflow.id})\n",
            "Branch: ${git.branch} @ ${commit.hash}\n",
            "Status: ${last.output}"
        );

        let result = ctx.interpolate(template).unwrap();

        assert!(result.contains("Workflow: test-workflow (wf-123)"));
        assert!(result.contains("Branch: main @ abc123"));
        assert!(result.contains("Status: Deploy completed"));
    }

    #[tokio::test]
    async fn test_variable_store_to_hashmap() {
        let store = VariableStore::new();

        store
            .set("name", CapturedValue::String("test".to_string()))
            .await;
        store.set("count", CapturedValue::Number(42.0)).await;
        store
            .set("data", CapturedValue::Json(json!({"key": "value"})))
            .await;

        let hashmap = store.to_hashmap().await;

        assert_eq!(hashmap.get("name"), Some(&"test".to_string()));
        assert_eq!(hashmap.get("count"), Some(&"42".to_string()));
        assert!(hashmap.contains_key("data"));
    }

    #[tokio::test]
    async fn test_number_capture_format() {
        let store = VariableStore::new();

        let result = CommandResult {
            stdout: Some("  42.5  \n".to_string()),
            stderr: None,
            exit_code: 0,
            success: true,
            duration: Duration::from_secs(1),
        };

        store
            .capture_command_result(
                "number",
                result,
                CaptureFormat::Number,
                &CaptureStreams::default(),
            )
            .await
            .unwrap();

        let number = store.get("number").await.unwrap();
        assert_eq!(number.to_string(), "42.5");
    }

    #[tokio::test]
    async fn test_boolean_capture_format() {
        let store = VariableStore::new();

        // Test 'true' string
        let result_true = CommandResult {
            stdout: Some("true".to_string()),
            stderr: None,
            exit_code: 0,
            success: true,
            duration: Duration::from_secs(1),
        };

        store
            .capture_command_result(
                "bool_true",
                result_true,
                CaptureFormat::Boolean,
                &CaptureStreams::default(),
            )
            .await
            .unwrap();

        let bool_val = store.get("bool_true").await.unwrap();
        assert_eq!(bool_val.to_string(), "true");

        // Test 'false' string
        let result_false = CommandResult {
            stdout: Some("false".to_string()),
            stderr: None,
            exit_code: 1,
            success: false,
            duration: Duration::from_secs(1),
        };

        store
            .capture_command_result(
                "bool_false",
                result_false,
                CaptureFormat::Boolean,
                &CaptureStreams::default(),
            )
            .await
            .unwrap();

        let bool_val = store.get("bool_false").await.unwrap();
        assert_eq!(bool_val.to_string(), "false");
    }

    #[tokio::test]
    async fn test_variable_override_in_child_store() {
        let parent = VariableStore::new();
        parent
            .set(
                "shared_var",
                CapturedValue::String("parent_value".to_string()),
            )
            .await;

        let child = parent.child();

        // Child can access parent variable
        assert_eq!(
            child.get("shared_var").await.unwrap().to_string(),
            "parent_value"
        );

        // Child overrides the variable
        child
            .set(
                "shared_var",
                CapturedValue::String("child_value".to_string()),
            )
            .await;

        // Child sees overridden value
        assert_eq!(
            child.get("shared_var").await.unwrap().to_string(),
            "child_value"
        );

        // Parent still sees original value
        assert_eq!(
            parent.get("shared_var").await.unwrap().to_string(),
            "parent_value"
        );
    }

    #[test]
    fn test_captured_value_array_display_outputs_valid_json() {
        // Create an array captured value (simulating map.results)
        let items = vec![
            CapturedValue::Json(json!({"item_id": "item_0", "status": "Success"})),
            CapturedValue::Json(json!({"item_id": "item_1", "status": "Success"})),
            CapturedValue::Json(json!({"item_id": "item_2", "status": "Success"})),
        ];
        let captured_array = CapturedValue::Array(items);

        // Convert to string (this is what happens during interpolation)
        let interpolated = captured_array.to_string();

        // Verify it's valid JSON
        let parsed_result: Result<Value, _> = serde_json::from_str(&interpolated);
        assert!(
            parsed_result.is_ok(),
            "Interpolated string should be valid JSON. Got: {}",
            interpolated
        );

        let parsed = parsed_result.unwrap();
        assert!(parsed.is_array());
        assert_eq!(parsed.as_array().unwrap().len(), 3);
    }

    #[test]
    fn test_captured_value_object_display_outputs_valid_json() {
        // Create an object captured value
        let mut map = HashMap::new();
        map.insert("successful".to_string(), CapturedValue::Number(10.0));
        map.insert("failed".to_string(), CapturedValue::Number(0.0));
        map.insert("total".to_string(), CapturedValue::Number(10.0));
        let captured_object = CapturedValue::Object(map);

        // Convert to string (this is what happens during interpolation)
        let interpolated = captured_object.to_string();

        // Verify it's valid JSON
        let parsed_result: Result<Value, _> = serde_json::from_str(&interpolated);
        assert!(
            parsed_result.is_ok(),
            "Interpolated string should be valid JSON. Got: {}",
            interpolated
        );

        let parsed = parsed_result.unwrap();
        assert!(parsed.is_object());
        let obj = parsed.as_object().unwrap();
        assert_eq!(obj.get("successful").unwrap(), &json!(10.0));
        assert_eq!(obj.get("failed").unwrap(), &json!(0.0));
        assert_eq!(obj.get("total").unwrap(), &json!(10.0));
    }
}