bzzz-core 0.1.0

Bzzz core library - Declarative orchestration engine for 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
//! Parameter substitution module
//!
//! Provides expression resolution for SwarmFiles using the `{{expression}}` syntax.
//! Supports:
//! - `{{input.x}}` - Input parameters
//! - `{{steps.worker.output.y}}` - Step outputs
//! - `{{env.X}}` - Environment variables
//! - `{{sys.run_id}}` - System variables

use std::collections::HashMap;

use chrono::Utc;
use handlebars::{Handlebars, RenderError};
use serde_json::Value;

use crate::{Run, RunError, Step, SwarmId};

// ============================================================================
// Error Types
// ============================================================================

/// Resolution error types
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ResolutionError {
    /// Referenced variable does not exist
    #[error("Missing variable: {path}")]
    MissingVariable {
        /// Path to the missing variable
        path: String,
    },

    /// Path traversal fails
    #[error("Invalid path: {path} - {reason}")]
    InvalidPath {
        /// Path that failed
        path: String,
        /// Reason for failure
        reason: String,
    },

    /// Type mismatch
    #[error("Type mismatch at {path}: expected {expected}, got {actual}")]
    TypeMismatch {
        /// Path where mismatch occurred
        path: String,
        /// Expected type
        expected: String,
        /// Actual type
        actual: String,
    },

    /// Invalid syntax
    #[error("Invalid syntax: {message}")]
    InvalidSyntax {
        /// Error message
        message: String,
    },

    /// Circular dependency detected
    #[error("Circular dependency detected: {chain}")]
    CircularDependency {
        /// Dependency chain
        chain: String,
    },

    /// Environment variable not allowed
    #[error("Environment variable '{var_name}' not allowed by policy")]
    EnvNotAllowed {
        /// Variable name
        var_name: String,
    },

    /// Schema validation failure
    #[error("Schema validation failed for field '{field}': expected {expected}, got {actual}")]
    SchemaValidation {
        /// Field that failed validation
        field: String,
        /// Expected schema
        expected: String,
        /// Actual value
        actual: Value,
    },

    /// Template rendering error
    #[error("Template error: {message}")]
    TemplateError {
        /// Error message
        message: String,
    },
}

impl ResolutionError {
    /// Create a MissingVariable error
    pub fn missing_variable(path: impl Into<String>) -> Self {
        ResolutionError::MissingVariable { path: path.into() }
    }

    /// Create an InvalidPath error
    pub fn invalid_path(path: impl Into<String>, reason: impl Into<String>) -> Self {
        ResolutionError::InvalidPath {
            path: path.into(),
            reason: reason.into(),
        }
    }

    /// Create an InvalidSyntax error
    pub fn invalid_syntax(message: impl Into<String>) -> Self {
        ResolutionError::InvalidSyntax {
            message: message.into(),
        }
    }

    /// Create a TemplateError
    pub fn template_error(message: impl Into<String>) -> Self {
        ResolutionError::TemplateError {
            message: message.into(),
        }
    }

    /// Convert to RunError
    pub fn to_run_error(&self) -> RunError {
        RunError::PatternError {
            pattern: "template".into(),
            step: "resolution".into(),
            message: self.to_string(),
        }
    }
}

impl From<RenderError> for ResolutionError {
    fn from(e: RenderError) -> Self {
        ResolutionError::template_error(e.to_string())
    }
}

// ============================================================================
// Scope Types
// ============================================================================

/// Output from a completed step
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StepOutput {
    /// Step name
    pub name: String,
    /// Output data (JSON value)
    pub output: Value,
}

impl StepOutput {
    /// Create a new step output
    pub fn new(name: impl Into<String>, output: Value) -> Self {
        StepOutput {
            name: name.into(),
            output,
        }
    }
}

/// Environment variable access policy
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EnvAllowlist {
    /// List of allowed environment variable names (case-sensitive)
    #[serde(default)]
    pub allowed: Vec<String>,

    /// Policy mode
    #[serde(default)]
    pub mode: EnvAllowlistMode,
}

/// Allowlist mode
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum EnvAllowlistMode {
    /// Only variables in the allowlist are accessible
    #[default]
    Strict,
    /// All variables accessible except blocked ones (open by default)
    Lenient,
}

impl EnvAllowlist {
    /// Create a strict allowlist with specific variables
    pub fn strict(allowed: Vec<String>) -> Self {
        EnvAllowlist {
            allowed,
            mode: EnvAllowlistMode::Strict,
        }
    }

    /// Create a lenient allowlist (all variables accessible)
    pub fn lenient() -> Self {
        EnvAllowlist {
            allowed: Vec::new(),
            mode: EnvAllowlistMode::Lenient,
        }
    }

    /// Check if a variable is allowed
    pub fn is_allowed(&self, var_name: &str) -> bool {
        match self.mode {
            EnvAllowlistMode::Strict => self.allowed.contains(&var_name.to_string()),
            EnvAllowlistMode::Lenient => true,
        }
    }
}

impl Default for EnvAllowlist {
    fn default() -> Self {
        // Default: strict mode with empty allowlist (no env access)
        EnvAllowlist::strict(Vec::new())
    }
}

/// System-provided variables
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SystemVariables {
    /// Unique identifier for current run
    pub run_id: String,
    /// Unique identifier for current step
    pub step_id: String,
    /// ISO 8601 timestamp at resolution time
    pub timestamp: String,
    /// Identifier of the current swarm
    pub swarm_id: String,
    /// Current iteration index (for loop pattern)
    pub iteration_index: Option<u32>,
    /// Current iteration value (for loop pattern)
    pub iteration_value: Option<Value>,
}

impl SystemVariables {
    /// Create from Run state
    pub fn from_run(run: &Run, swarm_id: &SwarmId) -> Self {
        SystemVariables {
            run_id: run.id.as_str().to_string(),
            step_id: String::new(), // Set by step executor
            timestamp: Utc::now().to_rfc3339(),
            swarm_id: swarm_id.as_str().to_string(),
            iteration_index: None,
            iteration_value: None,
        }
    }

    /// Set step context
    pub fn with_step(&mut self, step: &Step) {
        self.step_id = step.id.as_str().to_string();
    }

    /// Set loop iteration context
    pub fn with_iteration(&mut self, index: u32, value: Value) {
        self.iteration_index = Some(index);
        self.iteration_value = Some(value);
    }

    /// Convert to JSON Value for template rendering
    pub fn to_json(&self) -> Value {
        let mut obj = serde_json::Map::new();
        obj.insert("run_id".to_string(), Value::String(self.run_id.clone()));
        obj.insert("step_id".to_string(), Value::String(self.step_id.clone()));
        obj.insert(
            "timestamp".to_string(),
            Value::String(self.timestamp.clone()),
        );
        obj.insert("swarm_id".to_string(), Value::String(self.swarm_id.clone()));

        if let Some(index) = self.iteration_index {
            obj.insert("iteration_index".to_string(), Value::Number(index.into()));
        }

        if let Some(value) = &self.iteration_value {
            obj.insert("iteration_value".to_string(), value.clone());
        }

        Value::Object(obj)
    }
}

/// Resolution scope containing all available variables
#[derive(Debug, Clone)]
pub struct Scope {
    /// Input parameters passed to the swarm
    pub input: Value,
    /// Outputs from completed steps
    pub steps: HashMap<String, StepOutput>,
    /// Environment variables (filtered by allowlist)
    pub env: HashMap<String, String>,
    /// System-provided variables
    pub sys: SystemVariables,
}

impl Scope {
    /// Create a new scope with empty values
    pub fn empty() -> Self {
        Scope {
            input: Value::Object(serde_json::Map::new()),
            steps: HashMap::new(),
            env: HashMap::new(),
            sys: SystemVariables {
                run_id: String::new(),
                step_id: String::new(),
                timestamp: Utc::now().to_rfc3339(),
                swarm_id: String::new(),
                iteration_index: None,
                iteration_value: None,
            },
        }
    }

    /// Create a scope with input parameters
    pub fn with_input(input: Value) -> Self {
        Scope {
            input,
            steps: HashMap::new(),
            env: HashMap::new(),
            sys: SystemVariables {
                run_id: String::new(),
                step_id: String::new(),
                timestamp: Utc::now().to_rfc3339(),
                swarm_id: String::new(),
                iteration_index: None,
                iteration_value: None,
            },
        }
    }

    /// Add a step output
    pub fn add_step_output(&mut self, name: String, output: Value) {
        self.steps
            .insert(name.clone(), StepOutput::new(name, output));
    }

    /// Set system variables
    pub fn set_sys(&mut self, sys: SystemVariables) {
        self.sys = sys;
    }

    /// Load environment variables from process
    pub fn load_env(&mut self, allowlist: &EnvAllowlist) {
        for (key, value) in std::env::vars() {
            if allowlist.is_allowed(&key) {
                self.env.insert(key, value);
            }
        }
    }

    /// Convert to JSON Value for template rendering
    pub fn to_json(&self) -> Value {
        let mut obj = serde_json::Map::new();

        // Input scope
        obj.insert("input".to_string(), self.input.clone());

        // Steps scope
        let steps_obj = serde_json::Map::from_iter(self.steps.iter().map(|(name, output)| {
            let mut step_obj = serde_json::Map::new();
            step_obj.insert("output".to_string(), output.output.clone());
            (name.clone(), Value::Object(step_obj))
        }));
        obj.insert("steps".to_string(), Value::Object(steps_obj));

        // Env scope
        let env_obj = serde_json::Map::from_iter(
            self.env
                .iter()
                .map(|(k, v)| (k.clone(), Value::String(v.clone()))),
        );
        obj.insert("env".to_string(), Value::Object(env_obj));

        // Sys scope
        obj.insert("sys".to_string(), self.sys.to_json());

        Value::Object(obj)
    }
}

// ============================================================================
// Expression Resolver Trait
// ============================================================================

/// Expression resolver interface
pub trait ExpressionResolver: Send + Sync {
    /// Resolve all expressions in a string
    fn resolve(&self, template: &str, scope: &Scope) -> Result<String, ResolutionError>;

    /// Resolve expressions into a typed value
    fn resolve_value(&self, value: &Value, scope: &Scope) -> Result<Value, ResolutionError>;

    /// Validate expression syntax without resolution
    fn validate(&self, template: &str) -> Result<(), ResolutionError>;
}

// ============================================================================
// Handlebars Resolver Implementation
// ============================================================================

/// Handlebars-based expression resolver
pub struct HandlebarsResolver {
    /// Handlebars registry
    registry: Handlebars<'static>,
    /// Environment variable allowlist (used in future extensions for env filtering)
    #[allow(dead_code)]
    env_policy: EnvAllowlist,
}

impl HandlebarsResolver {
    /// Create a new resolver with default settings
    pub fn new() -> Self {
        HandlebarsResolver {
            registry: Handlebars::new(),
            env_policy: EnvAllowlist::default(),
        }
    }

    /// Create a resolver with custom env policy
    pub fn with_env_policy(env_policy: EnvAllowlist) -> Self {
        HandlebarsResolver {
            registry: Handlebars::new(),
            env_policy,
        }
    }

    /// Render a template string with the given data
    fn render_template(&self, template: &str, data: &Value) -> Result<String, ResolutionError> {
        self.registry
            .render_template(template, data)
            .map_err(ResolutionError::from)
    }
}

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

impl ExpressionResolver for HandlebarsResolver {
    fn resolve(&self, template: &str, scope: &Scope) -> Result<String, ResolutionError> {
        // Check if template contains expressions
        if !template.contains("{{") {
            // No expressions, return as-is
            return Ok(template.to_string());
        }

        // Validate first
        self.validate(template)?;

        // Convert scope to JSON
        let data = scope.to_json();

        // Render template
        self.render_template(template, &data)
    }

    fn resolve_value(&self, value: &Value, scope: &Scope) -> Result<Value, ResolutionError> {
        match value {
            Value::String(s) => {
                // Check if string contains expressions
                if s.contains("{{") {
                    let resolved = self.resolve(s, scope)?;
                    // Try to parse as JSON if it looks like a JSON value
                    if resolved.starts_with('{') || resolved.starts_with('[') {
                        // Try JSON parse, fallback to string on failure
                        Ok(serde_json::from_str(&resolved).unwrap_or(Value::String(resolved)))
                    } else if resolved == "true" {
                        Ok(Value::Bool(true))
                    } else if resolved == "false" {
                        Ok(Value::Bool(false))
                    } else if resolved == "null" {
                        Ok(Value::Null)
                    } else if let Ok(n) = resolved.parse::<i64>() {
                        Ok(Value::Number(n.into()))
                    } else if let Ok(n) = resolved.parse::<f64>() {
                        Ok(Value::Number(
                            serde_json::Number::from_f64(n)
                                .unwrap_or_else(|| serde_json::Number::from(0)),
                        ))
                    } else {
                        Ok(Value::String(resolved))
                    }
                } else {
                    Ok(Value::String(s.clone()))
                }
            }
            Value::Object(obj) => {
                // Resolve each field
                let resolved_obj = serde_json::Map::from_iter(obj.iter().map(|(k, v)| {
                    let resolved_v = self.resolve_value(v, scope);
                    (k.clone(), resolved_v.unwrap_or_else(|_| v.clone()))
                }));
                Ok(Value::Object(resolved_obj))
            }
            Value::Array(arr) => {
                // Resolve each element
                let resolved_arr: Vec<Value> = arr
                    .iter()
                    .map(|v| self.resolve_value(v, scope))
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(Value::Array(resolved_arr))
            }
            // Numbers, bools, null are preserved as-is
            other => Ok(other.clone()),
        }
    }

    fn validate(&self, template: &str) -> Result<(), ResolutionError> {
        // Check for unclosed braces
        let open_count = template.matches("{{").count();
        let close_count = template.matches("}}").count();

        if open_count != close_count {
            return Err(ResolutionError::invalid_syntax(
                "Unclosed braces in expression",
            ));
        }

        // Check for empty expressions
        if template.contains("{{}}") {
            return Err(ResolutionError::invalid_syntax("Empty expression"));
        }

        // Try to render with empty data to validate syntax
        let empty_data = Value::Object(serde_json::Map::new());
        // Just checking if template parses, not if values resolve
        self.registry
            .render_template(template, &empty_data)
            .map_err(ResolutionError::from)?;

        Ok(())
    }
}

// ============================================================================
// Convenience Functions
// ============================================================================

/// Resolve worker input values
///
/// Takes a worker's input mapping and resolves all expressions using the provided scope.
pub fn resolve_worker_input(
    input: &HashMap<String, Value>,
    scope: &Scope,
) -> Result<HashMap<String, Value>, ResolutionError> {
    let resolver = HandlebarsResolver::new();
    let mut resolved = HashMap::new();

    for (key, value) in input {
        let resolved_value = resolver.resolve_value(value, scope)?;
        resolved.insert(key.clone(), resolved_value);
    }

    Ok(resolved)
}

/// Resolve worker output values
///
/// Takes a worker's output mapping and resolves all expressions using the provided scope.
/// The scope should already contain the step's raw output.
pub fn resolve_worker_output(
    output_mapping: &HashMap<String, Value>,
    step_output: &Value,
    scope: &Scope,
) -> Result<HashMap<String, Value>, ResolutionError> {
    let resolver = HandlebarsResolver::new();
    let mut resolved = HashMap::new();

    // Create a scope that includes the raw step output
    let mut extended_scope = scope.clone();
    extended_scope.add_step_output("_raw".to_string(), step_output.clone());

    for (key, value) in output_mapping {
        let resolved_value = resolver.resolve_value(value, &extended_scope)?;
        resolved.insert(key.clone(), resolved_value);
    }

    Ok(resolved)
}

/// Resolve expose mappings to produce final output
///
/// Takes a SwarmFile's expose mappings and resolves them using the provided scope
/// to produce the final output object.
///
/// Supports both full expression syntax (`{{steps.parser.output.items}}`) and
/// simplified notation (`steps.parser.output.items`).
pub fn resolve_expose(
    expose: &[crate::ExposeMapping],
    scope: &Scope,
) -> Result<Value, ResolutionError> {
    let resolver = HandlebarsResolver::new();
    let mut output = serde_json::Map::new();

    for entry in expose {
        let value = resolve_expose_from(&entry.from, scope, &resolver)?;
        output.insert(entry.name.clone(), value);
    }

    Ok(Value::Object(output))
}

/// Resolve a single expose "from" expression
///
/// Handles both full expression syntax (`{{...}}`) and simplified notation.
/// Directly traverses the scope's JSON structure to preserve complex types.
fn resolve_expose_from(
    from: &str,
    scope: &Scope,
    _resolver: &HandlebarsResolver,
) -> Result<Value, ResolutionError> {
    // Normalize: strip {{ }} if present
    let path = if from.starts_with("{{") && from.ends_with("}}") {
        &from[2..from.len() - 2]
    } else {
        from
    };

    // Try direct path traversal (preserves complex types)
    // This will fail if the path doesn't exist in the scope
    traverse_scope_path(path, scope)
}

/// Resolve a path expression directly in the scope, preserving complex types.
///
/// This is useful for output mappings where you want to pass through
/// arrays and objects without string conversion.
///
/// # Arguments
/// * `path` - Path expression like "steps.nested.output.results" or "{{steps.nested.output.results}}"
/// * `scope` - The scope to resolve against
///
/// # Returns
/// The value at the path, preserving complex types (arrays, objects).
///
/// # Errors
/// Returns `ResolutionError` if the path doesn't exist or is invalid.
pub fn resolve_path_value(path: &str, scope: &Scope) -> Result<Value, ResolutionError> {
    // Normalize: strip {{ }} if present
    let normalized_path = if path.starts_with("{{") && path.ends_with("}}") {
        &path[2..path.len() - 2]
    } else {
        path
    };

    traverse_scope_path(normalized_path, scope)
}

/// Traverse a path like "steps.parser.output.items" directly in the scope
///
/// This preserves complex types (arrays, objects) without string conversion.
fn traverse_scope_path(path: &str, scope: &Scope) -> Result<Value, ResolutionError> {
    let parts: Vec<&str> = path.split('.').collect();
    if parts.is_empty() {
        return Err(ResolutionError::invalid_path(path, "Empty path"));
    }

    let scope_json = scope.to_json();
    let mut current = &scope_json;

    for part in &parts {
        match current {
            Value::Object(obj) => {
                current = obj
                    .get(*part)
                    .ok_or_else(|| ResolutionError::missing_variable(path))?;
            }
            Value::Array(arr) => {
                // Handle array index access like "items.0" or "items.[0]"
                let idx_str = part.trim_start_matches('[').trim_end_matches(']');
                if let Ok(idx) = idx_str.parse::<usize>() {
                    current = arr.get(idx).ok_or_else(|| {
                        ResolutionError::invalid_path(
                            path,
                            format!("Array index {} out of bounds", idx),
                        )
                    })?;
                } else {
                    return Err(ResolutionError::invalid_path(
                        path,
                        format!("Invalid array index: {}", part),
                    ));
                }
            }
            _ => {
                return Err(ResolutionError::invalid_path(
                    path,
                    format!("Cannot traverse {} on non-object/array", part),
                ));
            }
        }
    }

    Ok(current.clone())
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_scope_empty() {
        let scope = Scope::empty();
        assert!(scope.input.is_object());
        assert!(scope.steps.is_empty());
        assert!(scope.env.is_empty());
    }

    #[test]
    fn test_scope_with_input() {
        let scope = Scope::with_input(json!({ "user_id": "123", "items": ["a", "b", "c"] }));
        assert_eq!(scope.input["user_id"], "123");
        assert_eq!(scope.input["items"].as_array().unwrap().len(), 3);
    }

    #[test]
    fn test_scope_add_step_output() {
        let mut scope = Scope::empty();
        scope.add_step_output("fetcher".to_string(), json!({ "result": "data" }));

        assert!(scope.steps.contains_key("fetcher"));
        assert_eq!(scope.steps["fetcher"].output["result"], "data");
    }

    #[test]
    fn test_system_variables_to_json() {
        let sys = SystemVariables {
            run_id: "run-123".to_string(),
            step_id: "step-456".to_string(),
            timestamp: "2026-04-06T12:00:00Z".to_string(),
            swarm_id: "swarm-789".to_string(),
            iteration_index: Some(5),
            iteration_value: Some(json!("item-value")),
        };

        let json_val = sys.to_json();
        assert_eq!(json_val["run_id"], "run-123");
        assert_eq!(json_val["step_id"], "step-456");
        assert_eq!(json_val["iteration_index"], 5);
        assert_eq!(json_val["iteration_value"], "item-value");
    }

    #[test]
    fn test_scope_to_json() {
        let mut scope = Scope::with_input(json!({ "x": 1 }));
        scope.add_step_output("worker".to_string(), json!({ "y": 2 }));
        scope
            .env
            .insert("HOME".to_string(), "/home/user".to_string());

        let json_val = scope.to_json();
        assert_eq!(json_val["input"]["x"], 1);
        assert_eq!(json_val["steps"]["worker"]["output"]["y"], 2);
        assert_eq!(json_val["env"]["HOME"], "/home/user");
    }

    #[test]
    fn test_resolver_simple_input() {
        let resolver = HandlebarsResolver::new();
        let scope = Scope::with_input(json!({ "user_id": "123" }));

        let result = resolver.resolve("{{input.user_id}}", &scope).unwrap();
        assert_eq!(result, "123");
    }

    #[test]
    fn test_resolver_nested_input() {
        let resolver = HandlebarsResolver::new();
        let scope = Scope::with_input(json!({ "user": { "name": "Alice" } }));

        let result = resolver.resolve("{{input.user.name}}", &scope).unwrap();
        assert_eq!(result, "Alice");
    }

    #[test]
    fn test_resolver_step_output() {
        let resolver = HandlebarsResolver::new();
        let mut scope = Scope::empty();
        scope.add_step_output("fetcher".to_string(), json!({ "body": "response_data" }));

        let result = resolver
            .resolve("{{steps.fetcher.output.body}}", &scope)
            .unwrap();
        assert_eq!(result, "response_data");
    }

    #[test]
    fn test_resolver_string_interpolation() {
        let resolver = HandlebarsResolver::new();
        let scope = Scope::with_input(json!({ "id": "123" }));

        let result = resolver
            .resolve("prefix-{{input.id}}-suffix", &scope)
            .unwrap();
        assert_eq!(result, "prefix-123-suffix");
    }

    #[test]
    fn test_resolver_no_expression() {
        let resolver = HandlebarsResolver::new();
        let scope = Scope::empty();

        let result = resolver.resolve("static string", &scope).unwrap();
        assert_eq!(result, "static string");
    }

    #[test]
    fn test_resolver_invalid_syntax_unclosed() {
        let resolver = HandlebarsResolver::new();
        let scope = Scope::empty();

        let result = resolver.resolve("{{input.x", &scope);
        assert!(matches!(result, Err(ResolutionError::InvalidSyntax { .. })));
    }

    #[test]
    fn test_resolver_validate_success() {
        let resolver = HandlebarsResolver::new();
        assert!(resolver.validate("{{input.x}}").is_ok());
        assert!(resolver.validate("prefix-{{input.x}}-suffix").is_ok());
    }

    #[test]
    fn test_resolver_validate_failure() {
        let resolver = HandlebarsResolver::new();
        assert!(resolver.validate("{{input.x").is_err());
        assert!(resolver.validate("{{}}").is_err());
    }

    #[test]
    fn test_resolve_value_string() {
        let resolver = HandlebarsResolver::new();
        let scope = Scope::with_input(json!({ "x": "hello" }));

        let result = resolver
            .resolve_value(&Value::String("{{input.x}}".to_string()), &scope)
            .unwrap();
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_resolve_value_number_preserved() {
        let resolver = HandlebarsResolver::new();
        let scope = Scope::empty();

        let result = resolver
            .resolve_value(&Value::Number(42.into()), &scope)
            .unwrap();
        assert_eq!(result, 42);
    }

    #[test]
    fn test_resolve_value_bool_preserved() {
        let resolver = HandlebarsResolver::new();
        let scope = Scope::empty();

        let result = resolver.resolve_value(&Value::Bool(true), &scope).unwrap();
        assert_eq!(result, true);
    }

    #[test]
    fn test_resolve_value_array() {
        let resolver = HandlebarsResolver::new();
        let scope = Scope::with_input(json!({ "items": ["a", "b"] }));

        let input = json!(["{{input.items.[0]}}", "{{input.items.[1]}}"]);

        let result = resolver.resolve_value(&input, &scope).unwrap();
        // Handlebars array access uses [0] syntax with brackets
        assert_eq!(result, json!(["a", "b"]));
    }

    #[test]
    fn test_resolve_value_object() {
        let resolver = HandlebarsResolver::new();
        let scope = Scope::with_input(json!({ "user": { "name": "Bob" } }));

        let input = json!({
            "username": "{{input.user.name}}",
            "count": 5
        });

        let result = resolver.resolve_value(&input, &scope).unwrap();
        assert_eq!(result["username"], "Bob");
        assert_eq!(result["count"], 5);
    }

    #[test]
    fn test_resolve_worker_input() {
        let mut scope = Scope::with_input(json!({ "endpoint": "https://api.example.com" }));
        scope.add_step_output("fetcher".to_string(), json!({ "body": "raw_data" }));

        let input = HashMap::from([
            (
                "url".to_string(),
                Value::String("{{input.endpoint}}".to_string()),
            ),
            (
                "data".to_string(),
                Value::String("{{steps.fetcher.output.body}}".to_string()),
            ),
        ]);

        let resolved = resolve_worker_input(&input, &scope).unwrap();
        assert_eq!(resolved["url"], "https://api.example.com");
        assert_eq!(resolved["data"], "raw_data");
    }

    #[test]
    fn test_env_allowlist_strict() {
        let policy = EnvAllowlist::strict(vec!["HOME".to_string(), "PATH".to_string()]);
        assert!(policy.is_allowed("HOME"));
        assert!(policy.is_allowed("PATH"));
        assert!(!policy.is_allowed("AWS_SECRET"));
    }

    #[test]
    fn test_env_allowlist_lenient() {
        let policy = EnvAllowlist::lenient();
        assert!(policy.is_allowed("HOME"));
        assert!(policy.is_allowed("AWS_SECRET"));
    }

    #[test]
    fn test_env_allowlist_default() {
        let policy = EnvAllowlist::default();
        // Default is strict with empty list
        assert!(!policy.is_allowed("HOME"));
    }

    #[test]
    fn test_resolution_error_to_run_error() {
        let err = ResolutionError::missing_variable("input.x");
        let run_err = err.to_run_error();
        assert!(matches!(run_err, RunError::PatternError { .. }));
    }

    #[test]
    fn test_system_variables_from_run() {
        use crate::{RunTarget, RuntimeKind};
        use std::path::PathBuf;

        let run = Run::new(
            RunTarget::Agent {
                spec_path: PathBuf::from("agent.yaml"),
            },
            RuntimeKind::Local,
        );
        let swarm_id = SwarmId::new("test-swarm");

        let sys = SystemVariables::from_run(&run, &swarm_id);
        assert_eq!(sys.run_id, run.id.as_str());
        assert_eq!(sys.swarm_id, swarm_id.as_str());
        assert!(sys.iteration_index.is_none());
    }

    #[test]
    fn test_system_variables_with_iteration() {
        let mut sys = SystemVariables {
            run_id: "run-1".to_string(),
            step_id: "step-1".to_string(),
            timestamp: "2026-04-06T12:00:00Z".to_string(),
            swarm_id: "swarm-1".to_string(),
            iteration_index: None,
            iteration_value: None,
        };

        sys.with_iteration(3, json!("item-3"));
        assert_eq!(sys.iteration_index, Some(3));
        assert_eq!(sys.iteration_value, Some(json!("item-3")));
    }

    #[test]
    fn test_sys_variable_resolution() {
        let resolver = HandlebarsResolver::new();
        let mut scope = Scope::empty();
        scope.sys = SystemVariables {
            run_id: "run-123".to_string(),
            step_id: "step-456".to_string(),
            timestamp: "2026-04-06T12:00:00Z".to_string(),
            swarm_id: "swarm-789".to_string(),
            iteration_index: Some(0),
            iteration_value: Some(json!("first-item")),
        };

        let result = resolver.resolve("{{sys.run_id}}", &scope).unwrap();
        assert_eq!(result, "run-123");

        let result = resolver.resolve("{{sys.swarm_id}}", &scope).unwrap();
        assert_eq!(result, "swarm-789");

        let result = resolver.resolve("{{sys.iteration_index}}", &scope).unwrap();
        assert_eq!(result, "0");
    }

    // ===== Tests for resolve_expose =====

    #[test]
    fn test_resolve_expose_simplified_notation() {
        use crate::ExposeMapping;

        let mut scope = Scope::empty();
        scope.add_step_output(
            "parser".to_string(),
            json!({ "items": ["a", "b", "c"], "total": 3 }),
        );
        scope.add_step_output("counter".to_string(), json!({ "count": 42 }));

        let exposes = vec![
            ExposeMapping::new("results", "steps.parser.output.items"),
            ExposeMapping::new("total", "steps.parser.output.total"),
        ];

        let output = resolve_expose(&exposes, &scope).unwrap();

        assert_eq!(output["results"], json!(["a", "b", "c"]));
        assert_eq!(output["total"], 3);
    }

    #[test]
    fn test_resolve_expose_full_expression() {
        use crate::ExposeMapping;

        let mut scope = Scope::empty();
        scope.add_step_output("worker".to_string(), json!({ "value": "test_result" }));

        let exposes = vec![ExposeMapping::new(
            "output",
            "{{steps.worker.output.value}}",
        )];

        let output = resolve_expose(&exposes, &scope).unwrap();
        assert_eq!(output["output"], "test_result");
    }

    #[test]
    fn test_resolve_expose_empty() {
        let scope = Scope::empty();
        let exposes: Vec<crate::ExposeMapping> = vec![];

        let output = resolve_expose(&exposes, &scope).unwrap();
        assert!(output.is_object());
        assert_eq!(output.as_object().unwrap().len(), 0);
    }

    #[test]
    fn test_resolve_expose_multiple_fields() {
        use crate::ExposeMapping;

        let mut scope = Scope::empty();
        scope.add_step_output(
            "fetcher".to_string(),
            json!({ "data": { "id": 123, "name": "test" } }),
        );
        scope.add_step_output("processor".to_string(), json!({ "result": "processed" }));
        scope.add_step_output("counter".to_string(), json!({ "count": 5 }));

        let exposes = vec![
            ExposeMapping::new("id", "steps.fetcher.output.data.id"),
            ExposeMapping::new("name", "steps.fetcher.output.data.name"),
            ExposeMapping::new("result", "steps.processor.output.result"),
            ExposeMapping::new("count", "steps.counter.output.count"),
        ];

        let output = resolve_expose(&exposes, &scope).unwrap();

        assert_eq!(output["id"], 123);
        assert_eq!(output["name"], "test");
        assert_eq!(output["result"], "processed");
        assert_eq!(output["count"], 5);
    }

    #[test]
    fn test_resolve_expose_with_input() {
        use crate::ExposeMapping;

        let mut scope = Scope::with_input(json!({ "query": "search_term", "limit": 10 }));
        scope.add_step_output("searcher".to_string(), json!({ "hits": ["hit1", "hit2"] }));

        let exposes = vec![
            ExposeMapping::new("query_used", "input.query"),
            ExposeMapping::new("results", "steps.searcher.output.hits"),
        ];

        let output = resolve_expose(&exposes, &scope).unwrap();

        assert_eq!(output["query_used"], "search_term");
        assert_eq!(output["results"], json!(["hit1", "hit2"]));
    }

    #[test]
    fn test_resolve_expose_boolean_value() {
        use crate::ExposeMapping;

        let mut scope = Scope::empty();
        scope.add_step_output(
            "validator".to_string(),
            json!({ "valid": true, "invalid": false }),
        );

        let exposes = vec![
            ExposeMapping::new("is_valid", "steps.validator.output.valid"),
            ExposeMapping::new("is_invalid", "steps.validator.output.invalid"),
        ];

        let output = resolve_expose(&exposes, &scope).unwrap();
        assert_eq!(output["is_valid"], true);
        assert_eq!(output["is_invalid"], false);
    }

    #[test]
    fn test_resolve_expose_number_value() {
        use crate::ExposeMapping;

        let mut scope = Scope::empty();
        scope.add_step_output(
            "calculator".to_string(),
            json!({ "integer": 42, "float": 2.71 }),
        );

        let exposes = vec![
            ExposeMapping::new("int_val", "steps.calculator.output.integer"),
            ExposeMapping::new("float_val", "steps.calculator.output.float"),
        ];

        let output = resolve_expose(&exposes, &scope).unwrap();
        assert_eq!(output["int_val"], 42);
        // Float comparison
        assert!(output["float_val"].as_f64().unwrap() > 2.0);
        assert!(output["float_val"].as_f64().unwrap() < 3.0);
    }

    #[test]
    fn test_resolve_expose_missing_variable() {
        use crate::ExposeMapping;

        let scope = Scope::empty();
        let exposes = vec![ExposeMapping::new(
            "missing",
            "steps.nonexistent.output.value",
        )];

        // Should fail because the variable doesn't exist
        assert!(resolve_expose(&exposes, &scope).is_err());
    }
}