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
//! Workflow pattern executor
//!
//! Executes workers as a DAG (Directed Acyclic Graph) with explicit dependencies.
//! Workers execute when all their dependencies are satisfied, enabling automatic
//! parallel execution based on the dependency structure.
//!
//! ## Algorithm
//!
//! Uses Kahn's algorithm for topological sorting:
//! 1. Build dependency graph from tasks
//! 2. Find tasks with zero pending dependencies (ready set)
//! 3. Execute ready tasks concurrently
//! 4. On completion, decrement dependency counts for downstream tasks
//! 5. Repeat until all tasks complete
//!
//! ## Failure Semantics
//!
//! - `FailFast` (default): Stop all execution on first failure
//! - `Continue`: Skip downstream tasks, continue independent paths
//! - `Ignore`: Treat failed tasks as success, continue all

use std::collections::HashMap;

use async_trait::async_trait;

use crate::{ExecutionMetrics, ExecutionResult, FailureBehavior, FlowPattern, RunError, RunId, RunStatus, WorkflowTask};

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

/// Workflow pattern executor
pub struct WorkflowExecutor;

impl WorkflowExecutor {
    /// Create a new workflow executor
    pub fn new() -> Self {
        WorkflowExecutor
    }
}

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

/// Task execution state for workflow
#[derive(Debug, Clone)]
struct TaskState {
    /// Number of pending dependencies
    pending_deps: usize,
    /// Whether the task has completed
    completed: bool,
    /// Whether the task has failed
    failed: bool,
    /// Whether the task has been skipped (due to upstream failure)
    skipped: bool,
}

impl TaskState {
    fn new(pending_deps: usize) -> Self {
        TaskState {
            pending_deps,
            completed: false,
            failed: false,
            skipped: false,
        }
    }
}

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

    async fn execute(
        &self,
        ctx: &PatternContext,
        runtime: &dyn crate::RuntimeAdapter,
        cancel: &crate::CancellationToken,
    ) -> Result<ExecutionResult, RunError> {
        let (tasks, synthesis) = match &ctx.swarm.flow {
            FlowPattern::Workflow { tasks, synthesis } => (tasks, synthesis),
            _ => {
                return Err(RunError::PatternError {
                    pattern: "workflow".into(),
                    step: "flow".into(),
                    message: "WorkflowExecutor requires Workflow pattern in flow".into(),
                })
            }
        };

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

        // Build dependency graph and initial state
        let mut task_states: HashMap<String, TaskState> = HashMap::new();
        let mut downstream: HashMap<String, Vec<String>> = HashMap::new(); // task -> tasks that depend on it

        for task in tasks {
            // Count dependencies
            let pending_deps = task.depends_on.len();
            task_states.insert(task.name.clone(), TaskState::new(pending_deps));

            // Build reverse mapping for downstream updates
            for dep in &task.depends_on {
                downstream
                    .entry(dep.clone())
                    .or_default()
                    .push(task.name.clone());
            }
        }

        // Execution state
        let mut artifacts = vec![];
        let mut current_ctx = ctx.clone();
        let on_failure = ctx.swarm.on_failure;
        let mut failed_tasks: Vec<String> = vec![];
        let mut skipped_tasks: Vec<String> = vec![];

        // Main execution loop - Kahn's algorithm
        loop {
            // 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: ExecutionMetrics::default(),
                    output: None,
                });
            }

            // Find ready tasks (pending_deps == 0 and not completed/failed/skipped)
            let ready: Vec<String> = task_states
                .iter()
                .filter(|(_, state)| {
                    state.pending_deps == 0
                        && !state.completed
                        && !state.failed
                        && !state.skipped
                })
                .map(|(name, _)| name.clone())
                .collect();

            // No more ready tasks
            if ready.is_empty() {
                break;
            }

            // Execute ready tasks (sequentially for simplicity; could be parallelized)
            for task_name in ready {
                // Check if task should be skipped due to failed upstream
                let should_skip = should_skip_task(&task_name, &task_states, tasks);

                if should_skip {
                    // Mark as skipped
                    if let Some(state) = task_states.get_mut(&task_name) {
                        state.skipped = true;
                        skipped_tasks.push(task_name.clone());
                    }

                    // Update downstream tasks
                    if let Some(downstream_tasks) = downstream.get(&task_name) {
                        for downstream_task in downstream_tasks {
                            if let Some(ds_state) = task_states.get_mut(downstream_task) {
                                ds_state.pending_deps = ds_state.pending_deps.saturating_sub(1);
                            }
                        }
                    }
                    continue;
                }

                // Get worker
                let worker = current_ctx
                    .get_worker(&task_name)
                    .ok_or_else(|| RunError::PatternError {
                        pattern: "workflow".into(),
                        step: task_name.clone(),
                        message: format!("Worker '{}' not found in swarm", task_name),
                    })?;

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

                match result.status {
                    RunStatus::Completed => {
                        artifacts.extend(result.artifacts);

                        // Add step output to scope
                        if let Some(output) = &result.output {
                            current_ctx.add_step_output(&task_name, output.clone());
                        }

                        // Mark task as completed
                        if let Some(state) = task_states.get_mut(&task_name) {
                            state.completed = true;
                        }

                        // Update downstream tasks
                        if let Some(downstream_tasks) = downstream.get(&task_name) {
                            for downstream_task in downstream_tasks {
                                if let Some(ds_state) = task_states.get_mut(downstream_task) {
                                    ds_state.pending_deps = ds_state.pending_deps.saturating_sub(1);
                                }
                            }
                        }
                    }
                    RunStatus::Failed => {
                        if let Some(state) = task_states.get_mut(&task_name) {
                            state.failed = true;
                        }
                        failed_tasks.push(task_name.clone());

                        match on_failure {
                            FailureBehavior::FailFast => {
                                // Mark all incomplete tasks as skipped
                                for (name, state) in &mut task_states {
                                    if !state.completed && !state.failed {
                                        state.skipped = true;
                                        skipped_tasks.push(name.clone());
                                    }
                                }
                                break;
                            }
                            FailureBehavior::Continue | FailureBehavior::Ignore => {
                                // Update downstream - they will be skipped
                                if let Some(downstream_tasks) = downstream.get(&task_name) {
                                    for downstream_task in downstream_tasks {
                                        if let Some(ds_state) = task_states.get_mut(downstream_task) {
                                            ds_state.pending_deps = ds_state.pending_deps.saturating_sub(1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    RunStatus::Cancelled => {
                        return Ok(ExecutionResult {
                            run_id: RunId::new(),
                            status: RunStatus::Cancelled,
                            artifacts,
                            error: Some(RunError::Cancelled {
                                reason: "Execution cancelled".into(),
                            }),
                            metrics: result.metrics,
                            output: None,
                        });
                    }
                    _ => {
                        return Ok(ExecutionResult {
                            run_id: RunId::new(),
                            status: RunStatus::Failed,
                            artifacts,
                            error: Some(RunError::RuntimeError {
                                message: format!("Unexpected status: {:?}", result.status),
                            }),
                            metrics: result.metrics,
                            output: None,
                        });
                    }
                }
            }
        }

        // Execute synthesis if specified and all tasks completed successfully
        if let Some(synth_name) = synthesis {
            // Check if any tasks failed
            let any_failed = failed_tasks.iter().any(|name| {
                task_states
                    .get(name)
                    .map(|s| s.failed)
                    .unwrap_or(false)
            });

            if !any_failed && !cancel.is_cancelled().await {
                let synth_worker = current_ctx
                    .get_worker(synth_name)
                    .ok_or_else(|| RunError::PatternError {
                        pattern: "workflow".into(),
                        step: synth_name.to_string(),
                        message: format!("Synthesis worker '{}' not found", synth_name),
                    })?;

                let result = execute_worker(
                    synth_worker,
                    runtime,
                    &current_ctx.runtime_ctx,
                    &current_ctx.scope,
                    cancel,
                )
                .await?;

                match result.status {
                    RunStatus::Completed => {
                        artifacts.extend(result.artifacts);
                        if let Some(output) = &result.output {
                            current_ctx.add_step_output(synth_name, output.clone());
                        }
                    }
                    RunStatus::Failed => {
                        failed_tasks.push(synth_name.to_string());
                    }
                    _ => {}
                }
            }
        }

        // Determine final status
        let (final_status, final_error) = if failed_tasks.is_empty() && skipped_tasks.is_empty() {
            (RunStatus::Completed, None)
        } else if !failed_tasks.is_empty() {
            match on_failure {
                FailureBehavior::Ignore => (RunStatus::Completed, None),
                _ => (
                    RunStatus::Failed,
                    Some(RunError::PatternError {
                        pattern: "workflow".into(),
                        step: "summary".into(),
                        message: format!(
                            "{} task(s) failed: {}, {} task(s) skipped: {}",
                            failed_tasks.len(),
                            failed_tasks.join(", "),
                            skipped_tasks.len(),
                            skipped_tasks.join(", ")
                        ),
                    }),
                ),
            }
        } else {
            // Only skipped tasks (due to upstream failure in Continue mode)
            match on_failure {
                FailureBehavior::Ignore => (RunStatus::Completed, None),
                _ => (
                    RunStatus::Failed,
                    Some(RunError::PatternError {
                        pattern: "workflow".into(),
                        step: "summary".into(),
                        message: format!("{} task(s) skipped due to upstream failure", skipped_tasks.len()),
                    }),
                ),
            }
        };

        let result = ExecutionResult {
            run_id: RunId::new(),
            status: final_status,
            artifacts,
            error: final_error,
            metrics: ExecutionMetrics::default(),
            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> {
        // Workflow pattern: failure handling is built into the execution logic
        Ok(false)
    }
}

/// Check if a task should be skipped due to failed upstream dependencies.
fn should_skip_task(
    task_name: &str,
    task_states: &HashMap<String, TaskState>,
    tasks: &[WorkflowTask],
) -> bool {
    // Find the task definition
    let task_def = match tasks.iter().find(|t| t.name == task_name) {
        Some(t) => t,
        None => return false,
    };

    // Check if any dependency failed or was skipped
    for dep in &task_def.depends_on {
        if let Some(state) = task_states.get(dep) {
            if state.failed || state.skipped {
                return true;
            }
        }
    }

    false
}

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

    #[test]
    fn test_workflow_executor_name() {
        let executor = WorkflowExecutor::new();
        assert_eq!(executor.name(), "workflow");
    }

    #[tokio::test]
    async fn test_workflow_executor_wrong_pattern() {
        let executor = WorkflowExecutor::new();
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Parallel {
                branches: vec![],
                fail_fast: false,
            },
        );
        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());
    }

    #[tokio::test]
    async fn test_workflow_empty_tasks() {
        let executor = WorkflowExecutor::new();
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Workflow {
                tasks: vec![],
                synthesis: None,
            },
        );
        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();

        assert_eq!(result.status, RunStatus::Completed);
    }

    #[tokio::test]
    async fn test_workflow_single_task() {
        let executor = WorkflowExecutor::new();

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

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

        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Workflow {
                tasks: vec![WorkflowTask::new("w1")],
                synthesis: None,
            },
        )
        .with_worker(Worker::new("w1", spec_path.to_string_lossy().to_string()));

        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();

        assert_eq!(result.status, RunStatus::Completed);
    }

    #[tokio::test]
    async fn test_workflow_linear_dependency() {
        let executor = WorkflowExecutor::new();

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

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

        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Workflow {
                tasks: vec![
                    WorkflowTask::new("a"),
                    WorkflowTask::new("b").with_depends_on(vec!["a".into()]),
                    WorkflowTask::new("c").with_depends_on(vec!["b".into()]),
                ],
                synthesis: None,
            },
        )
        .with_worker(Worker::new("a", spec_path.to_string_lossy().to_string()))
        .with_worker(Worker::new("b", spec_path.to_string_lossy().to_string()))
        .with_worker(Worker::new("c", spec_path.to_string_lossy().to_string()));

        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();

        assert_eq!(result.status, RunStatus::Completed);
    }

    #[test]
    fn test_workflow_task_creation() {
        let task = WorkflowTask::new("test-task")
            .with_depends_on(vec!["dep1".into(), "dep2".into()]);

        assert_eq!(task.name, "test-task");
        assert_eq!(task.depends_on, vec!["dep1", "dep2"]);
    }

    #[test]
    fn test_workflow_pattern_yaml_parsing() {
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: workflow-test
workers:
  - name: a
    spec: a.yaml
  - name: b
    spec: b.yaml
flow:
  type: workflow
  tasks:
    - name: a
      depends_on: []
    - name: b
      depends_on: [a]
  synthesis: b
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(parsed.id.as_str(), "workflow-test");

        if let FlowPattern::Workflow { tasks, synthesis } = &parsed.flow {
            assert_eq!(tasks.len(), 2);
            assert_eq!(tasks[0].name, "a");
            assert_eq!(tasks[0].depends_on, Vec::<String>::new());
            assert_eq!(tasks[1].name, "b");
            assert_eq!(tasks[1].depends_on, vec!["a"]);
            assert_eq!(synthesis, &Some("b".to_string()));
        } else {
            panic!("Expected Workflow pattern");
        }
    }

    #[test]
    fn test_workflow_validation_cycle_detection() {
        // A -> B -> C -> A (cycle)
        let swarm = SwarmFile::new(
            "cycle-test",
            FlowPattern::Workflow {
                tasks: vec![
                    WorkflowTask::new("a").with_depends_on(vec!["c".into()]),
                    WorkflowTask::new("b").with_depends_on(vec!["a".into()]),
                    WorkflowTask::new("c").with_depends_on(vec!["b".into()]),
                ],
                synthesis: None,
            },
        )
        .with_worker(Worker::new("a", "a.yaml"))
        .with_worker(Worker::new("b", "b.yaml"))
        .with_worker(Worker::new("c", "c.yaml"));

        let result = swarm.validate();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("cycle"));
    }

    #[test]
    fn test_workflow_validation_undefined_dependency() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Workflow {
                tasks: vec![
                    WorkflowTask::new("a"),
                    WorkflowTask::new("b").with_depends_on(vec!["nonexistent".into()]),
                ],
                synthesis: None,
            },
        )
        .with_worker(Worker::new("a", "a.yaml"))
        .with_worker(Worker::new("b", "b.yaml"));

        let result = swarm.validate();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("undefined task"));
    }

    #[test]
    fn test_workflow_validation_duplicate_task_name() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Workflow {
                tasks: vec![
                    WorkflowTask::new("a"),
                    WorkflowTask::new("a"), // duplicate
                ],
                synthesis: None,
            },
        )
        .with_worker(Worker::new("a", "a.yaml"));

        let result = swarm.validate();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("duplicate"));
    }
}