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
//! Delegate pattern executor
//!
//! Loads and executes a sub-SwarmFile as a nested flow.
//! Failure semantics: sub-flow failure causes overall failure.
//!
//! ## P2-1: Scope Inheritance
//!
//! The delegate executor supports scope inheritance:
//! - `input_mapping`: Maps parent scope values to nested pattern inputs
//! - `output_mapping`: Maps nested pattern outputs back to parent scope
//! - `failure_inherit`: Controls whether nested failure propagates to parent
//!
//! The nested pattern receives merged scope (parent + local mappings).
//!
//! ## P2-5: Dynamic Worker Selection
//!
//! The delegate executor also supports dynamic worker selection:
//! - `worker_expr`: Expression that resolves to a worker name
//! - `fallback`: Worker name when expression fails or no match
//!
//! When `worker_expr` is provided (and `swarm` is not), the executor:
//! 1. Evaluates the expression against the current scope
//! 2. Looks up the resolved worker name in the swarm's workers list
//! 3. Executes that single worker
//! 4. Records selection decision in ExecutionResult.metrics.selection_trace

use std::collections::HashMap;

use async_trait::async_trait;
use serde_json::Value;

use crate::{
    template::{resolve_path_value, ExpressionResolver, HandlebarsResolver},
    ExecutionMetrics, ExecutionResult, FlowPattern, RunError, RunId, RunStatus, RunTarget, Scope,
    SwarmFile, Worker,
};

use super::{build_capability_output, execute_worker, PatternContext, PatternExecutor};

/// Default nesting depth limit
const DEFAULT_MAX_NESTING_DEPTH: u32 = crate::MAX_NESTING_DEPTH;

/// Delegate pattern executor
///
/// Handles two modes:
/// 1. Sub-swarm delegation (when `swarm` path is provided)
/// 2. Dynamic worker selection (when `worker_expr` is provided)
pub struct DelegateExecutor {
    /// Maximum nesting depth (defaults to MAX_NESTING_DEPTH)
    max_depth: u32,
}

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

impl DelegateExecutor {
    /// Create a new delegate executor with default max depth
    pub fn new() -> Self {
        DelegateExecutor {
            max_depth: DEFAULT_MAX_NESTING_DEPTH,
        }
    }

    /// Create a delegate executor with custom max depth
    pub fn with_max_depth(max_depth: u32) -> Self {
        DelegateExecutor { max_depth }
    }

    /// Resolve worker expression to a worker name (P2-5)
    ///
    /// Evaluates the expression against the current scope to determine
    /// which worker to execute.
    ///
    /// # Arguments
    /// * `expr` - Expression like `{{input.processor_type}}`
    /// * `scope` - Current resolution scope
    ///
    /// # Returns
    /// The resolved worker name, or an error if resolution fails.
    fn resolve_worker_expr(&self, expr: &str, scope: &Scope) -> Result<String, RunError> {
        let resolver = HandlebarsResolver::new();
        let resolved = resolver
            .resolve(expr, scope)
            .map_err(|e| RunError::PatternError {
                pattern: "delegate".into(),
                step: "worker_expr".into(),
                message: format!("Failed to resolve worker_expr '{}': {}", expr, e),
            })?;

        // Trim whitespace from resolved value
        let worker_name = resolved.trim();

        if worker_name.is_empty() {
            return Err(RunError::PatternError {
                pattern: "delegate".into(),
                step: "worker_expr".into(),
                message: format!("Resolved worker_expr '{}' is empty", expr),
            });
        }

        Ok(worker_name.to_string())
    }

    /// Find a worker by name in the swarm's workers list (P2-5)
    ///
    /// # Arguments
    /// * `worker_name` - Name of the worker to find
    /// * `swarm` - The SwarmFile containing workers list
    ///
    /// # Returns
    /// The worker if found, or None if not found.
    fn find_worker<'a>(&self, worker_name: &str, swarm: &'a SwarmFile) -> Option<&'a Worker> {
        swarm.workers.iter().find(|w| w.name == worker_name)
    }

    /// Build selection trace string for metrics (P2-5 AC4)
    ///
    /// Creates a human-readable trace of the selection decision.
    fn build_selection_trace(
        &self,
        expr: &str,
        resolved_name: &str,
        found: bool,
        fallback_used: Option<&str>,
    ) -> String {
        let status = if found {
            "selected"
        } else if fallback_used.is_some() {
            "fallback"
        } else {
            "failed"
        };

        let fallback_str = fallback_used
            .map(|f| format!(" fallback={}", f))
            .unwrap_or_default();

        format!(
            "expr={} resolved={} status={}{}",
            expr, resolved_name, status, fallback_str
        )
    }

    /// Load the delegate SwarmFile
    fn load_delegate_swarm(
        &self,
        path: &std::path::PathBuf,
        ctx: &PatternContext,
    ) -> Result<SwarmFile, RunError> {
        // Resolve path relative to current SwarmFile's directory
        let default_path = std::path::PathBuf::from(".");
        let base_dir = ctx
            .swarm
            .file_path
            .as_ref()
            .and_then(|p| p.parent())
            .unwrap_or(&default_path);

        let full_path = base_dir.join(path);

        SwarmFile::from_yaml_file(&full_path)
    }

    /// Build nested scope from parent scope and input_mapping
    ///
    /// Merges parent scope with local input mappings to create the scope
    /// passed to the nested pattern.
    ///
    /// # Arguments
    /// * `parent_scope` - The scope from the parent pattern execution
    /// * `input_mapping` - Mapping configuration from the delegate pattern
    ///
    /// # Returns
    /// A new scope with merged input values.
    fn build_nested_scope(
        &self,
        parent_scope: &Scope,
        input_mapping: &HashMap<String, Value>,
    ) -> Result<Scope, RunError> {
        // Create a new scope starting with empty input
        let mut nested_scope = Scope::empty();

        // Build the nested input from mappings
        let mut nested_input = serde_json::Map::new();

        // Apply input_mapping to resolve values from parent scope
        for (key, value) in input_mapping {
            let resolver = HandlebarsResolver::new();
            let resolved = resolver.resolve_value(value, parent_scope).map_err(|e| {
                RunError::PatternError {
                    pattern: "delegate".into(),
                    step: "input_mapping".into(),
                    message: format!("Failed to resolve input_mapping '{}': {}", key, e),
                }
            })?;
            nested_input.insert(key.clone(), resolved);
        }

        nested_scope.input = Value::Object(nested_input);

        // Copy parent's steps (nested pattern can see parent's step outputs)
        // This enables expressions like {{steps.parent_worker.output.x}} in nested patterns
        nested_scope.steps = parent_scope.steps.clone();

        // Copy parent's env (with same allowlist)
        nested_scope.env = parent_scope.env.clone();

        // Set new system variables for nested context
        nested_scope.sys = crate::template::SystemVariables {
            run_id: parent_scope.sys.run_id.clone(),
            step_id: format!("delegate-{}", parent_scope.sys.step_id),
            timestamp: chrono::Utc::now().to_rfc3339(),
            swarm_id: parent_scope.sys.swarm_id.clone(),
            iteration_index: parent_scope.sys.iteration_index,
            iteration_value: parent_scope.sys.iteration_value.clone(),
        };

        Ok(nested_scope)
    }

    /// Apply output_mapping to merge nested outputs back to parent scope
    ///
    /// Takes the nested pattern's output and maps it back to the parent scope
    /// using the output_mapping configuration.
    ///
    /// Uses direct path traversal to preserve complex types (arrays, objects).
    fn apply_output_mapping(
        &self,
        nested_output: &Value,
        parent_scope: &Scope,
        output_mapping: &HashMap<String, Value>,
    ) -> Result<Value, RunError> {
        // Create a scope that includes the nested output
        let mut mapping_scope = parent_scope.clone();
        mapping_scope.add_step_output("nested".to_string(), nested_output.clone());

        let mut result = serde_json::Map::new();

        for (key, value) in output_mapping {
            // For string values that look like expressions, use direct path traversal
            // to preserve complex types (arrays, objects)
            let resolved = match value {
                Value::String(s)
                    if s.contains("{{") && s.starts_with("{{") && s.ends_with("}}") =>
                {
                    // Use direct path traversal for path expressions to preserve types
                    resolve_path_value(s, &mapping_scope).map_err(|e| RunError::PatternError {
                        pattern: "delegate".into(),
                        step: "output_mapping".into(),
                        message: format!("Failed to resolve output_mapping '{}': {}", key, e),
                    })?
                }
                _ => {
                    // For other values, use regular resolution
                    let resolver = HandlebarsResolver::new();
                    resolver.resolve_value(value, &mapping_scope).map_err(|e| {
                        RunError::PatternError {
                            pattern: "delegate".into(),
                            step: "output_mapping".into(),
                            message: format!("Failed to resolve output_mapping '{}': {}", key, e),
                        }
                    })?
                }
            };
            result.insert(key.clone(), resolved);
        }

        Ok(Value::Object(result))
    }

    /// Check nesting depth before execution
    fn check_nesting_depth(&self, current_depth: u32) -> Result<(), RunError> {
        if current_depth >= self.max_depth {
            return Err(RunError::PatternError {
                pattern: "delegate".into(),
                step: "depth_check".into(),
                message: format!(
                    "Nesting depth {} exceeds maximum allowed {}",
                    current_depth, self.max_depth
                ),
            });
        }
        Ok(())
    }

    /// Execute swarm delegation mode (original behavior)
    #[allow(clippy::too_many_arguments)]
    async fn execute_swarm_delegate(
        &self,
        ctx: &PatternContext,
        runtime: &dyn crate::RuntimeAdapter,
        _cancel: &crate::CancellationToken,
        swarm_path: &std::path::PathBuf,
        input_mapping: &HashMap<String, Value>,
        output_mapping: &HashMap<String, Value>,
        failure_inherit: bool,
    ) -> Result<ExecutionResult, RunError> {
        let _ = failure_inherit; // Used in error propagation

        // Check nesting depth (use metadata from context if available)
        let current_depth = ctx
            .state
            .custom
            .get("nesting_depth")
            .and_then(|d| d.parse::<u32>().ok())
            .unwrap_or(0);
        self.check_nesting_depth(current_depth)?;

        // Load delegate SwarmFile
        let delegate_swarm = self.load_delegate_swarm(swarm_path, ctx)?;

        // Build nested scope with input_mapping
        let nested_scope = self.build_nested_scope(&ctx.scope, input_mapping)?;

        // Create execution context for delegate
        let delegate_ctx = crate::ExecutionContext::new(
            format!("delegate-{}", swarm_path.display()),
            runtime.kind(),
        );

        // Create nested pattern context
        let mut nested_pattern_ctx = PatternContext::new(delegate_swarm, delegate_ctx);
        nested_pattern_ctx.scope = nested_scope;

        // Track nesting depth in nested context
        nested_pattern_ctx
            .state
            .custom
            .insert("nesting_depth".to_string(), (current_depth + 1).to_string());

        // Execute delegate using simplified execution
        let run = crate::Run::new(
            RunTarget::Swarm {
                swarmfile_path: swarm_path.clone(),
            },
            runtime.kind(),
        );

        let handle = runtime
            .execute(&nested_pattern_ctx.runtime_ctx, &run)
            .await?;
        let result = runtime.wait(&handle).await?;

        // Build scope with delegate output for expose resolution
        let mut final_scope = ctx.scope.clone();

        // Apply output_mapping if present
        if !output_mapping.is_empty() {
            if let Some(ref output) = result.output {
                let mapped_output =
                    self.apply_output_mapping(output, &ctx.scope, output_mapping)?;
                final_scope.add_step_output("delegate".to_string(), mapped_output);
            }
        } else if let Some(output) = &result.output {
            // No output_mapping, pass through directly
            final_scope.add_step_output("delegate".to_string(), output.clone());
        }

        let exec_result = ExecutionResult {
            run_id: RunId::new(),
            status: result.status,
            artifacts: result.artifacts,
            error: result.error,
            metrics: result.metrics,
            output: None,
        };

        // CR2: Apply expose resolution or output behavior
        Ok(build_capability_output(
            exec_result,
            &ctx.swarm,
            &final_scope,
        ))
    }

    /// Execute dynamic worker selection mode (P2-5)
    ///
    /// This method:
    /// 1. Resolves the worker_expr to get the worker name
    /// 2. Finds the worker in the swarm's workers list
    /// 3. Executes the selected worker
    /// 4. Records selection trace in metrics
    #[allow(clippy::too_many_arguments)]
    async fn execute_worker_selection(
        &self,
        ctx: &PatternContext,
        runtime: &dyn crate::RuntimeAdapter,
        cancel: &crate::CancellationToken,
        worker_expr: &str,
        fallback: Option<&str>,
        input_mapping: &HashMap<String, Value>,
        output_mapping: &HashMap<String, Value>,
        failure_inherit: bool,
    ) -> Result<ExecutionResult, RunError> {
        let _ = failure_inherit; // Used for error propagation

        // AC1: Resolve the worker expression
        let resolved_name = self.resolve_worker_expr(worker_expr, &ctx.scope)?;

        // Find the worker in the swarm
        let worker = self.find_worker(&resolved_name, &ctx.swarm);

        // Determine which worker to actually use
        let (selected_worker, selection_trace) = match worker {
            Some(w) => {
                // Worker found - use it
                let trace = self.build_selection_trace(worker_expr, &resolved_name, true, None);
                (w, trace)
            }
            None => {
                // Worker not found - try fallback (AC3)
                match fallback {
                    Some(fallback_name) => {
                        // Try to find fallback worker
                        match self.find_worker(fallback_name, &ctx.swarm) {
                            Some(fw) => {
                                let trace = self.build_selection_trace(
                                    worker_expr,
                                    &resolved_name,
                                    false,
                                    Some(fallback_name),
                                );
                                (fw, trace)
                            }
                            None => {
                                // Fallback worker also not found
                                let trace = self.build_selection_trace(
                                    worker_expr,
                                    &resolved_name,
                                    false,
                                    Some(fallback_name),
                                );
                                return Err(RunError::PatternError {
                                    pattern: "delegate".into(),
                                    step: "worker_selection".into(),
                                    message: format!(
                                        "Worker '{}' not found and fallback '{}' also not found. Trace: {}",
                                        resolved_name, fallback_name, trace
                                    ),
                                });
                            }
                        }
                    }
                    None => {
                        // No fallback provided
                        let trace =
                            self.build_selection_trace(worker_expr, &resolved_name, false, None);
                        return Err(RunError::PatternError {
                            pattern: "delegate".into(),
                            step: "worker_selection".into(),
                            message: format!(
                                "Worker '{}' not found and no fallback provided. Trace: {}",
                                resolved_name, trace
                            ),
                        });
                    }
                }
            }
        };

        // Build worker scope from input_mapping
        let worker_scope = if !input_mapping.is_empty() {
            self.build_nested_scope(&ctx.scope, input_mapping)?
        } else {
            ctx.scope.clone()
        };

        // Execute the selected worker
        let result = execute_worker(
            selected_worker,
            runtime,
            &ctx.runtime_ctx,
            &worker_scope,
            cancel,
        )
        .await?;

        // Build final scope with worker output
        let mut final_scope = ctx.scope.clone();

        // Apply output_mapping if present
        if !output_mapping.is_empty() {
            if let Some(ref output) = result.output {
                let mapped_output =
                    self.apply_output_mapping(output, &ctx.scope, output_mapping)?;
                final_scope.add_step_output(selected_worker.name.clone(), mapped_output);
            }
        } else if let Some(output) = &result.output {
            final_scope.add_step_output(selected_worker.name.clone(), output.clone());
        }

        // AC4: Include selection trace in metrics
        let metrics = ExecutionMetrics {
            wall_time_ms: result.metrics.wall_time_ms,
            cpu_time_ms: result.metrics.cpu_time_ms,
            peak_memory_bytes: result.metrics.peak_memory_bytes,
            retries: result.metrics.retries,
            selection_trace: Some(selection_trace),
        };

        let exec_result = ExecutionResult {
            run_id: RunId::new(),
            status: result.status,
            artifacts: result.artifacts,
            error: result.error,
            metrics,
            output: None,
        };

        // Record fallback usage in state for debugging
        let final_result = build_capability_output(exec_result, &ctx.swarm, &final_scope);
        // Selection trace is already set in metrics above
        Ok(final_result)
    }
}

#[async_trait]
impl PatternExecutor for DelegateExecutor {
    fn name(&self) -> &'static str {
        "delegate"
    }

    async fn execute(
        &self,
        ctx: &PatternContext,
        runtime: &dyn crate::RuntimeAdapter,
        cancel: &crate::CancellationToken,
    ) -> Result<ExecutionResult, RunError> {
        // Extract delegate pattern parameters
        let (swarm_path, worker_expr, fallback, input_mapping, output_mapping, failure_inherit) =
            match &ctx.swarm.flow {
                FlowPattern::Delegate {
                    swarm,
                    worker_expr,
                    fallback,
                    input_mapping,
                    output_mapping,
                    failure_inherit,
                } => (
                    swarm.clone(),
                    worker_expr.clone(),
                    fallback.clone(),
                    input_mapping.clone(),
                    output_mapping.clone(),
                    *failure_inherit,
                ),
                _ => {
                    return Err(RunError::PatternError {
                        pattern: "delegate".into(),
                        step: "flow".into(),
                        message: "DelegateExecutor requires Delegate pattern in flow".into(),
                    })
                }
            };

        // Check cancellation
        if cancel.is_cancelled().await {
            return Ok(ExecutionResult {
                run_id: RunId::new(),
                status: RunStatus::Cancelled,
                artifacts: vec![],
                error: Some(RunError::Cancelled {
                    reason: "Execution cancelled".into(),
                }),
                metrics: ExecutionMetrics::default(),
                output: None,
            });
        }

        // Determine execution mode: swarm delegation vs dynamic worker selection
        if let Some(path) = swarm_path {
            // Mode 1: Delegate to sub-swarm (original behavior)
            self.execute_swarm_delegate(
                ctx,
                runtime,
                cancel,
                &path,
                &input_mapping,
                &output_mapping,
                failure_inherit,
            )
            .await
        } else if let Some(expr) = worker_expr {
            // Mode 2: Dynamic worker selection (P2-5)
            self.execute_worker_selection(
                ctx,
                runtime,
                cancel,
                &expr,
                fallback.as_deref(),
                &input_mapping,
                &output_mapping,
                failure_inherit,
            )
            .await
        } else {
            // Neither swarm nor worker_expr provided - configuration error
            Err(RunError::PatternError {
                pattern: "delegate".into(),
                step: "config".into(),
                message:
                    "Delegate pattern requires either 'swarm' path or 'worker_expr' expression"
                        .into(),
            })
        }
    }

    async fn on_failure(
        &self,
        ctx: &mut PatternContext,
        _runtime: &dyn crate::RuntimeAdapter,
        _failed_worker: &str,
        _error: &RunError,
    ) -> Result<bool, RunError> {
        // Check failure_inherit setting
        let failure_inherit = match &ctx.swarm.flow {
            FlowPattern::Delegate {
                failure_inherit, ..
            } => *failure_inherit,
            _ => true,
        };

        if failure_inherit {
            // Sub-flow failure stops execution
            Ok(false)
        } else {
            // Failure is handled locally, execution can continue
            ctx.state
                .custom
                .insert("delegate_failed".to_string(), "true".to_string());
            Ok(true)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CancellationToken, ExecutionContext, FlowPattern, RuntimeKind, SwarmFile};
    use serde_json::json;

    #[test]
    fn test_delegate_executor_name() {
        let executor = DelegateExecutor::new();
        assert_eq!(executor.name(), "delegate");
    }

    #[test]
    fn test_delegate_executor_with_custom_max_depth() {
        let executor = DelegateExecutor::with_max_depth(5);
        assert_eq!(executor.max_depth, 5);
    }

    #[test]
    fn test_build_nested_scope_basic() {
        let executor = DelegateExecutor::new();
        let parent_scope = Scope::with_input(json!({ "query": "test", "limit": 10 }));

        let input_mapping = HashMap::from([(
            "search".to_string(),
            Value::String("{{input.query}}".to_string()),
        )]);

        let nested_scope = executor
            .build_nested_scope(&parent_scope, &input_mapping)
            .unwrap();

        assert_eq!(nested_scope.input["search"], "test");
        // Parent's input should NOT be directly inherited unless mapped
        assert!(nested_scope.input.get("query").is_none());
    }

    #[test]
    fn test_build_nested_scope_with_step_output() {
        let executor = DelegateExecutor::new();
        let mut parent_scope = Scope::with_input(json!({ "user_id": "123" }));
        parent_scope.add_step_output("fetcher".to_string(), json!({ "data": "fetched_value" }));

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

        let nested_scope = executor
            .build_nested_scope(&parent_scope, &input_mapping)
            .unwrap();

        assert_eq!(nested_scope.input["data"], "fetched_value");
        // Nested scope should inherit parent's steps
        assert!(nested_scope.steps.contains_key("fetcher"));
    }

    #[test]
    fn test_apply_output_mapping_basic() {
        let executor = DelegateExecutor::new();
        let parent_scope = Scope::empty();

        let nested_output = json!({ "results": "value1", "total": 42 });

        let output_mapping = HashMap::from([
            (
                "items".to_string(),
                Value::String("{{steps.nested.output.results}}".to_string()),
            ),
            (
                "count".to_string(),
                Value::String("{{steps.nested.output.total}}".to_string()),
            ),
        ]);

        let mapped = executor
            .apply_output_mapping(&nested_output, &parent_scope, &output_mapping)
            .unwrap();

        // String values are resolved as strings
        assert_eq!(mapped["items"], "value1");
        // Numeric values are resolved as numbers
        assert_eq!(mapped["count"], 42);
    }

    #[test]
    fn test_apply_output_mapping_with_object() {
        let executor = DelegateExecutor::new();
        let parent_scope = Scope::empty();

        // When nested output contains an object, it can be mapped
        let nested_output = json!({ "data": { "name": "test", "value": 123 } });

        let output_mapping = HashMap::from([(
            "result".to_string(),
            Value::String("{{steps.nested.output.data.name}}".to_string()),
        )]);

        let mapped = executor
            .apply_output_mapping(&nested_output, &parent_scope, &output_mapping)
            .unwrap();

        // Object field access resolves to string
        assert_eq!(mapped["result"], "test");
    }

    #[test]
    fn test_check_nesting_depth_within_limit() {
        let executor = DelegateExecutor::with_max_depth(5);
        assert!(executor.check_nesting_depth(0).is_ok());
        assert!(executor.check_nesting_depth(4).is_ok());
    }

    #[test]
    fn test_check_nesting_depth_exceeds_limit() {
        let executor = DelegateExecutor::with_max_depth(5);
        assert!(executor.check_nesting_depth(5).is_err());
        assert!(executor.check_nesting_depth(10).is_err());
    }

    #[tokio::test]
    async fn test_delegate_executor_wrong_pattern() {
        let executor = DelegateExecutor::new();
        let swarm = SwarmFile::new("test", FlowPattern::Sequence { steps: vec![] });
        let ctx = PatternContext::new(swarm, ExecutionContext::new("ctx", RuntimeKind::Local));
        let cancel = CancellationToken::new();

        let result = executor
            .execute(&ctx, &crate::LocalRuntime::new(), &cancel)
            .await;
        assert!(result.is_err());
    }

    #[test]
    fn test_delegate_pattern_with_mappings() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Delegate {
                swarm: Some(std::path::PathBuf::from("sub.yaml")),
                worker_expr: None,
                fallback: None,
                input_mapping: HashMap::from([(
                    "query".to_string(),
                    Value::String("{{input.search}}".to_string()),
                )]),
                output_mapping: HashMap::from([(
                    "result".to_string(),
                    Value::String("{{steps.nested.output.data}}".to_string()),
                )]),
                failure_inherit: true,
            },
        );

        // Verify the pattern can be created
        assert!(matches!(swarm.flow, FlowPattern::Delegate { .. }));
    }

    #[test]
    fn test_delegate_pattern_failure_inherit_false() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Delegate {
                swarm: Some(std::path::PathBuf::from("sub.yaml")),
                worker_expr: None,
                fallback: None,
                input_mapping: HashMap::new(),
                output_mapping: HashMap::new(),
                failure_inherit: false,
            },
        );

        if let FlowPattern::Delegate {
            failure_inherit, ..
        } = &swarm.flow
        {
            assert!(!*failure_inherit);
        }
    }

    // ===== P2-5: Dynamic Worker Selection Tests =====

    #[test]
    fn test_resolve_worker_expr_basic() {
        let executor = DelegateExecutor::new();
        let scope = Scope::with_input(json!({ "processor_type": "image_processor" }));

        let result = executor
            .resolve_worker_expr("{{input.processor_type}}", &scope)
            .unwrap();
        assert_eq!(result, "image_processor");
    }

    #[test]
    fn test_resolve_worker_expr_nested() {
        let executor = DelegateExecutor::new();
        let scope = Scope::with_input(json!({ "config": { "worker": "heavy_processor" } }));

        let result = executor
            .resolve_worker_expr("{{input.config.worker}}", &scope)
            .unwrap();
        assert_eq!(result, "heavy_processor");
    }

    #[test]
    fn test_resolve_worker_expr_empty_fails() {
        let executor = DelegateExecutor::new();
        let scope = Scope::with_input(json!({ "processor_type": "" }));

        let result = executor.resolve_worker_expr("{{input.processor_type}}", &scope);
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_worker_expr_missing_fails() {
        let executor = DelegateExecutor::new();
        let scope = Scope::empty();

        let result = executor.resolve_worker_expr("{{input.nonexistent}}", &scope);
        assert!(result.is_err());
    }

    #[test]
    fn test_find_worker_exists() {
        let executor = DelegateExecutor::new();
        let swarm = SwarmFile::new("test", FlowPattern::Sequence { steps: vec![] })
            .with_worker(Worker::new("processor_a", "agent.yaml"))
            .with_worker(Worker::new("processor_b", "agent.yaml"));

        let worker = executor.find_worker("processor_a", &swarm);
        assert!(worker.is_some());
        assert_eq!(worker.unwrap().name, "processor_a");
    }

    #[test]
    fn test_find_worker_not_exists() {
        let executor = DelegateExecutor::new();
        let swarm = SwarmFile::new("test", FlowPattern::Sequence { steps: vec![] })
            .with_worker(Worker::new("processor_a", "agent.yaml"));

        let worker = executor.find_worker("nonexistent", &swarm);
        assert!(worker.is_none());
    }

    #[test]
    fn test_build_selection_trace_selected() {
        let executor = DelegateExecutor::new();
        let trace = executor.build_selection_trace("{{input.type}}", "processor_a", true, None);

        assert!(trace.contains("expr={{input.type}}"));
        assert!(trace.contains("resolved=processor_a"));
        assert!(trace.contains("status=selected"));
        assert!(!trace.contains("fallback"));
    }

    #[test]
    fn test_build_selection_trace_fallback() {
        let executor = DelegateExecutor::new();
        let trace = executor.build_selection_trace(
            "{{input.type}}",
            "unknown",
            false,
            Some("default_worker"),
        );

        assert!(trace.contains("status=fallback"));
        assert!(trace.contains("fallback=default_worker"));
    }

    #[test]
    fn test_build_selection_trace_failed() {
        let executor = DelegateExecutor::new();
        let trace = executor.build_selection_trace("{{input.type}}", "unknown", false, None);

        assert!(trace.contains("status=failed"));
    }

    #[test]
    fn test_delegate_pattern_with_worker_expr() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Delegate {
                swarm: None,
                worker_expr: Some("{{input.processor_type}}".to_string()),
                fallback: Some("default_worker".to_string()),
                input_mapping: HashMap::new(),
                output_mapping: HashMap::new(),
                failure_inherit: true,
            },
        );

        if let FlowPattern::Delegate {
            worker_expr,
            fallback,
            ..
        } = &swarm.flow
        {
            assert_eq!(worker_expr, &Some("{{input.processor_type}}".to_string()));
            assert_eq!(fallback, &Some("default_worker".to_string()));
        } else {
            panic!("Expected Delegate pattern");
        }
    }

    #[test]
    fn test_delegate_pattern_swarm_takes_precedence() {
        // When both swarm and worker_expr are provided, swarm takes precedence
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Delegate {
                swarm: Some(std::path::PathBuf::from("sub.yaml")),
                worker_expr: Some("{{input.worker}}".to_string()),
                fallback: None,
                input_mapping: HashMap::new(),
                output_mapping: HashMap::new(),
                failure_inherit: true,
            },
        );

        // Both fields are stored, but executor will use swarm first
        assert!(matches!(swarm.flow, FlowPattern::Delegate { .. }));
    }

    #[tokio::test]
    async fn test_delegate_no_swarm_no_worker_expr_fails() {
        let executor = DelegateExecutor::new();
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Delegate {
                swarm: None,
                worker_expr: None,
                fallback: None,
                input_mapping: HashMap::new(),
                output_mapping: HashMap::new(),
                failure_inherit: true,
            },
        );
        let ctx = PatternContext::new(swarm, ExecutionContext::new("ctx", RuntimeKind::Local));
        let cancel = CancellationToken::new();

        let result = executor
            .execute(&ctx, &crate::LocalRuntime::new(), &cancel)
            .await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err
            .to_string()
            .contains("requires either 'swarm' path or 'worker_expr'"));
    }
}