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
//! Loop pattern executor
//!
//! Iterates over a variable, executing worker for each item.
//! Failure semantics controlled by `SwarmFile.on_failure`:
//! - `FailFast` (default): any iteration failure immediately terminates the loop
//! - `Continue`: records failure, continues remaining iterations, returns aggregated error
//! - `Ignore`: records failure but treats as success, continues remaining iterations
//!
//! ## CR2: CapabilityOutput
//!
//! After all iterations complete, applies expose resolution or output behavior
//! to produce the final capability output. Iteration outputs are collected in scope.

use async_trait::async_trait;

use crate::template::{ExpressionResolver, HandlebarsResolver};
use crate::{ExecutionMetrics, ExecutionResult, FailureBehavior, FlowPattern, RunError, RunId, RunStatus};

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

/// Loop pattern executor
pub struct LoopExecutor;

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

impl LoopExecutor {
    /// Create a new loop executor
    pub fn new() -> Self {
        LoopExecutor
    }

    /// Resolve the iterable variable
    ///
    /// Returns a vector of items to iterate over.
    /// Uses ExpressionResolver for template syntax:
    /// - `{{input.items}}` - Input parameter (array)
    /// - Range syntax: `1..10` (generates numbers 1-9)
    /// - Count: `5` (iterate 5 times, indices 0-4)
    /// - Literal list: `a,b,c` (comma-separated)
    fn resolve_iterable(&self, over: &str, ctx: &PatternContext) -> Result<Vec<String>, RunError> {
        let resolver = HandlebarsResolver::new();

        // First, resolve template expressions
        let resolved = resolver
            .resolve(over, &ctx.scope)
            .map_err(|e| e.to_run_error())?;

        // Check if resolved value is a JSON array
        if resolved.starts_with('[') && resolved.ends_with(']') {
            if let Ok(serde_json::Value::Array(arr)) =
                serde_json::from_str::<serde_json::Value>(&resolved)
            {
                return Ok(arr.iter().map(|v| v.to_string()).collect());
            }
        }

        // Check if it's a range syntax (e.g., "1..10")
        let resolved_str = resolved.trim();
        if resolved_str.contains("..") {
            let parts: Vec<&str> = resolved_str.split("..").collect();
            if parts.len() == 2 {
                let start: usize =
                    parts[0]
                        .trim()
                        .parse()
                        .map_err(|_| RunError::InvalidConfig {
                            message: format!("Invalid range start: {}", parts[0]),
                        })?;
                let end: usize = parts[1]
                    .trim()
                    .parse()
                    .map_err(|_| RunError::InvalidConfig {
                        message: format!("Invalid range end: {}", parts[1]),
                    })?;
                return Ok((start..end).map(|i| i.to_string()).collect());
            }
        }

        // Check if it's a count (e.g., "5" means iterate 5 times)
        if let Ok(count) = resolved_str.parse::<u32>() {
            return Ok((0..count).map(|i| i.to_string()).collect());
        }

        // Default: treat as a literal comma-separated list
        Ok(resolved_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect())
    }
}

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

    async fn execute(
        &self,
        ctx: &PatternContext,
        runtime: &dyn crate::RuntimeAdapter,
        cancel: &crate::CancellationToken,
    ) -> Result<ExecutionResult, RunError> {
        let (over, do_worker, max_iterations) = match &ctx.swarm.flow {
            FlowPattern::Loop {
                over,
                do_,
                max_iterations,
            } => (over.clone(), do_.clone(), *max_iterations),
            _ => {
                return Err(RunError::PatternError {
                    pattern: "loop".into(),
                    step: "flow".into(),
                    message: "LoopExecutor requires Loop pattern in flow".into(),
                })
            }
        };

        // Resolve iterable
        let items = self.resolve_iterable(&over, ctx)?;

        if items.is_empty() {
            return Ok(ExecutionResult {
                run_id: RunId::new(),
                status: RunStatus::Completed,
                artifacts: vec![],
                error: None,
                metrics: ExecutionMetrics::default(),
                output: None,
            });
        }

        // Get worker to execute in each iteration
        let worker = ctx
            .get_worker(&do_worker)
            .ok_or_else(|| RunError::PatternError {
                pattern: "loop".into(),
                step: do_worker.clone(),
                message: format!("Worker '{}' not found in swarm for loop body", do_worker),
            })?;

        // Execute iterations
        let mut artifacts = vec![];
        let mut metrics = ExecutionMetrics::default();
        let mut current_ctx = ctx.clone();
        let on_failure = ctx.swarm.on_failure;
        // Tracks failed iteration indices for Continue/Ignore summary
        let mut failed_iterations: Vec<usize> = vec![];

        for (iteration_count, item) in items.iter().enumerate() {
            // Check max_iterations limit
            if max_iterations > 0 && iteration_count >= max_iterations as usize {
                break;
            }

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

            // Set iteration context for this iteration
            // sys.iteration_index and sys.iteration_value are available for parameter substitution
            current_ctx.scope.sys.with_iteration(
                iteration_count as u32,
                serde_json::Value::String(item.clone()),
            );

            // Execute worker with iteration context
            let result = execute_worker(
                worker,
                runtime,
                &current_ctx.runtime_ctx,
                &current_ctx.scope,
                cancel,
            )
            .await?;

            match result.status {
                RunStatus::Completed => {
                    artifacts.extend(result.artifacts);
                    metrics.wall_time_ms += result.metrics.wall_time_ms;
                    metrics.retries += result.metrics.retries;
                    // Overwrite scope with each iteration's output (Phase 0: last-wins)
                    if let Some(output) = &result.output {
                        current_ctx.add_step_output(&do_worker, output.clone());
                    }
                }
                RunStatus::Failed => {
                    match on_failure {
                        FailureBehavior::FailFast => {
                            return Ok(ExecutionResult {
                                run_id: RunId::new(),
                                status: RunStatus::Failed,
                                artifacts,
                                error: result.error,
                                metrics,
                                output: None,
                            });
                        }
                        FailureBehavior::Continue | FailureBehavior::Ignore => {
                            // Record failure and continue with next iteration
                            failed_iterations.push(iteration_count);
                            metrics.wall_time_ms += result.metrics.wall_time_ms;
                            metrics.retries += result.metrics.retries;
                        }
                    }
                }
                RunStatus::Cancelled => {
                    return Ok(ExecutionResult {
                        run_id: RunId::new(),
                        status: RunStatus::Cancelled,
                        artifacts,
                        error: Some(RunError::Cancelled {
                            reason: "Execution cancelled".into(),
                        }),
                        metrics,
                        output: None,
                    });
                }
                _ => {}
            }
        }

        // Determine final status based on on_failure behavior
        let (final_status, final_error) = if failed_iterations.is_empty() {
            (RunStatus::Completed, None)
        } else {
            match on_failure {
                FailureBehavior::Continue => (
                    RunStatus::Failed,
                    Some(RunError::PatternError {
                        pattern: "loop".into(),
                        step: "summary".into(),
                        message: format!(
                            "{} iteration(s) failed: {}",
                            failed_iterations.len(),
                            failed_iterations
                                .iter()
                                .map(|i| i.to_string())
                                .collect::<Vec<_>>()
                                .join(", ")
                        ),
                    }),
                ),
                // Ignore: treat failures as success
                FailureBehavior::Ignore => (RunStatus::Completed, None),
                // FailFast already returned early above
                FailureBehavior::FailFast => unreachable!(),
            }
        };

        // CR2: Build result with expose resolution
        let result = ExecutionResult {
            run_id: RunId::new(),
            status: final_status,
            artifacts,
            error: final_error,
            metrics,
            output: None,
        };

        Ok(build_capability_output(
            result,
            &ctx.swarm,
            &current_ctx.scope,
        ))
    }

    async fn on_failure(
        &self,
        ctx: &mut PatternContext,
        _runtime: &dyn crate::RuntimeAdapter,
        _failed_worker: &str,
        _error: &RunError,
    ) -> Result<bool, RunError> {
        // Loop: failure stops iteration
        ctx.state.iteration += 1;
        Ok(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::template::Scope;
    use crate::{CancellationToken, ExecutionContext, FailureBehavior, FlowPattern, RuntimeKind, SwarmFile, Worker};
    use serde_json::json;
    use std::io::Write;

    #[test]
    fn test_loop_executor_name() {
        let executor = LoopExecutor::new();
        assert_eq!(executor.name(), "loop");
    }

    #[test]
    fn test_resolve_iterable_range() {
        let executor = LoopExecutor::new();
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Loop {
                over: "1..5".into(),
                do_: "worker".into(),
                max_iterations: 0,
            },
        );
        let ctx = PatternContext::new(swarm, ExecutionContext::new("ctx", RuntimeKind::Local));

        let items = executor.resolve_iterable("1..5", &ctx).unwrap();
        assert_eq!(items, vec!["1", "2", "3", "4"]);
    }

    #[test]
    fn test_resolve_iterable_count() {
        let executor = LoopExecutor::new();
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Loop {
                over: "3".into(),
                do_: "worker".into(),
                max_iterations: 0,
            },
        );
        let ctx = PatternContext::new(swarm, ExecutionContext::new("ctx", RuntimeKind::Local));

        let items = executor.resolve_iterable("3", &ctx).unwrap();
        assert_eq!(items, vec!["0", "1", "2"]);
    }

    #[test]
    fn test_resolve_iterable_list() {
        let executor = LoopExecutor::new();
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Loop {
                over: "a,b,c".into(),
                do_: "worker".into(),
                max_iterations: 0,
            },
        );
        let ctx = PatternContext::new(swarm, ExecutionContext::new("ctx", RuntimeKind::Local));

        let items = executor.resolve_iterable("a,b,c", &ctx).unwrap();
        assert_eq!(items, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_resolve_iterable_template() {
        use crate::pattern::PatternState;
        use crate::template::Scope;
        use serde_json::json;

        let executor = LoopExecutor::new();
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Loop {
                over: "{{input.items}}".into(),
                do_: "worker".into(),
                max_iterations: 0,
            },
        );

        // Create scope with input array
        let scope = Scope::with_input(json!({ "items": ["x", "y", "z"] }));
        let ctx = PatternContext {
            swarm,
            runtime_ctx: ExecutionContext::new("ctx", RuntimeKind::Local),
            handles: std::collections::HashMap::new(),
            state: PatternState::default(),
            scope,
        };

        let items = executor.resolve_iterable("{{input.items}}", &ctx).unwrap();
        // Array items are serialized as JSON strings
        assert_eq!(items.len(), 3);
    }

    #[tokio::test]
    async fn test_loop_executor_wrong_pattern() {
        let executor = LoopExecutor::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());
    }

    /// AC1/AC2: Loop scope output — last-wins overwrite semantics via add_step_output
    #[test]
    fn test_loop_scope_output_last_wins() {
        // Simulate what the loop executor does: overwrite scope on each iteration
        let mut scope = Scope::with_input(json!({}));

        // First iteration
        scope.add_step_output("printer".to_string(), json!({ "value": "first" }));
        let data = scope.to_json();
        assert_eq!(data["steps"]["printer"]["output"]["value"], json!("first"));

        // Second iteration overwrites (last-wins)
        scope.add_step_output("printer".to_string(), json!({ "value": "final" }));
        let data = scope.to_json();
        assert_eq!(data["steps"]["printer"]["output"]["value"], json!("final"));
    }

    /// AC2: Continue mode — iteration failure is recorded but loop continues
    #[tokio::test]
    async fn test_loop_on_failure_continue() {
        let executor = LoopExecutor::new();

        let temp_dir = std::env::temp_dir().join("bzzz-loop-continue-test");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let failing_spec_path = temp_dir.join("failing.yaml");
        let mut file = std::fs::File::create(&failing_spec_path).unwrap();
        writeln!(file, "apiVersion: v1").unwrap();
        writeln!(file, "id: failing-agent").unwrap();
        writeln!(file, "runtime:").unwrap();
        writeln!(file, "  kind: Local").unwrap();
        writeln!(file, "  config:").unwrap();
        writeln!(file, "    command: /usr/bin/false").unwrap();
        drop(file);

        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Loop {
                over: "3".into(),
                do_: "failing".into(),
                max_iterations: 0,
            },
        )
        .with_worker(Worker::new(
            "failing",
            failing_spec_path.to_string_lossy().to_string(),
        ))
        .with_failure_behavior(FailureBehavior::Continue);

        let ctx = PatternContext::new(swarm, ExecutionContext::new("ctx", RuntimeKind::Local));
        let cancel = CancellationToken::new();

        let result = executor
            .execute(&ctx, &crate::LocalRuntime::new(), &cancel)
            .await
            .unwrap();

        std::fs::remove_dir_all(&temp_dir).ok();

        // Continue: all iterations ran, final status is Failed with summary
        assert_eq!(result.status, RunStatus::Failed);
        assert!(result.error.is_some());
        if let Some(RunError::PatternError { message, .. }) = &result.error {
            assert!(message.contains("3 iteration(s) failed"));
        }
    }

    /// AC3: Ignore mode — iteration failure is treated as success
    #[tokio::test]
    async fn test_loop_on_failure_ignore() {
        let executor = LoopExecutor::new();

        let temp_dir = std::env::temp_dir().join("bzzz-loop-ignore-test");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let failing_spec_path = temp_dir.join("failing.yaml");
        let mut file = std::fs::File::create(&failing_spec_path).unwrap();
        writeln!(file, "apiVersion: v1").unwrap();
        writeln!(file, "id: failing-agent").unwrap();
        writeln!(file, "runtime:").unwrap();
        writeln!(file, "  kind: Local").unwrap();
        writeln!(file, "  config:").unwrap();
        writeln!(file, "    command: /usr/bin/false").unwrap();
        drop(file);

        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Loop {
                over: "2".into(),
                do_: "failing".into(),
                max_iterations: 0,
            },
        )
        .with_worker(Worker::new(
            "failing",
            failing_spec_path.to_string_lossy().to_string(),
        ))
        .with_failure_behavior(FailureBehavior::Ignore);

        let ctx = PatternContext::new(swarm, ExecutionContext::new("ctx", RuntimeKind::Local));
        let cancel = CancellationToken::new();

        let result = executor
            .execute(&ctx, &crate::LocalRuntime::new(), &cancel)
            .await
            .unwrap();

        std::fs::remove_dir_all(&temp_dir).ok();

        // Ignore: failures treated as success
        assert_eq!(result.status, RunStatus::Completed);
        assert!(result.error.is_none());
    }

    /// AC7: Scope chain — manual scope setup → resolve_worker_input → template resolves correctly
    #[test]
    fn test_scope_chain_template_resolution() {
        use crate::template::{resolve_worker_input, Scope};
        use std::collections::HashMap;

        let mut scope = Scope::with_input(json!({}));
        scope.add_step_output(
            "step_a".to_string(),
            json!({ "count": 42, "nested": { "key": "hello" } }),
        );

        let mut input: HashMap<String, serde_json::Value> = HashMap::new();
        input.insert("total".to_string(), json!("{{steps.step_a.output.count}}"));
        input.insert(
            "msg".to_string(),
            json!("{{steps.step_a.output.nested.key}}"),
        );

        let resolved = resolve_worker_input(&input, &scope).unwrap();
        assert_eq!(resolved["total"], json!(42));
        assert_eq!(resolved["msg"], json!("hello"));
    }
}