spec-ai 0.6.12

A framework for building AI agents with structured outputs, policy enforcement, and execution tracking
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
//! Multi-agent workflow orchestration.
//!
//! This module provides infrastructure for coordinating complex
//! multi-agent workflows with sequential, parallel, and consensus stages.

use crate::spec_ai_collective::types::{CollectiveError, Domain, ExecutionId, InstanceId, Result, WorkflowId};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Type of workflow stage.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum StageType {
    /// Single agent executes the stage
    Sequential,
    /// Multiple agents execute the same task in parallel
    Parallel { min_agents: usize },
    /// Split work, process in parallel, combine results
    MapReduce { chunks: usize },
    /// Require agreement from multiple agents
    Consensus { min_agreement: f32 },
    /// Branch based on previous stage result
    ConditionalBranch { condition: String },
}

/// State of a workflow stage.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum StageState {
    /// Stage is waiting for dependencies
    Pending,
    /// Stage is ready to execute
    Ready,
    /// Stage is currently executing
    Running,
    /// Stage completed successfully
    Completed,
    /// Stage failed
    Failed { reason: String },
    /// Stage was skipped (conditional branch)
    Skipped,
}

/// A stage in a workflow.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowStage {
    /// Unique stage identifier within the workflow
    pub stage_id: String,

    /// Human-readable name
    pub name: String,

    /// Description of what this stage does
    pub description: String,

    /// Type of stage
    pub stage_type: StageType,

    /// Capabilities required to execute this stage
    pub required_capabilities: Vec<Domain>,

    /// Stage IDs that must complete before this stage can start
    pub dependencies: Vec<String>,

    /// Timeout for this stage
    pub timeout: Duration,

    /// Payload/configuration for this stage
    pub config: serde_json::Value,
}

impl WorkflowStage {
    /// Create a new sequential stage.
    pub fn sequential(
        stage_id: impl Into<String>,
        name: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        Self {
            stage_id: stage_id.into(),
            name: name.into(),
            description: description.into(),
            stage_type: StageType::Sequential,
            required_capabilities: Vec::new(),
            dependencies: Vec::new(),
            timeout: Duration::minutes(30),
            config: serde_json::json!({}),
        }
    }

    /// Create a parallel stage.
    pub fn parallel(
        stage_id: impl Into<String>,
        name: impl Into<String>,
        description: impl Into<String>,
        min_agents: usize,
    ) -> Self {
        Self {
            stage_id: stage_id.into(),
            name: name.into(),
            description: description.into(),
            stage_type: StageType::Parallel { min_agents },
            required_capabilities: Vec::new(),
            dependencies: Vec::new(),
            timeout: Duration::minutes(30),
            config: serde_json::json!({}),
        }
    }

    /// Create a map-reduce stage.
    pub fn map_reduce(
        stage_id: impl Into<String>,
        name: impl Into<String>,
        description: impl Into<String>,
        chunks: usize,
    ) -> Self {
        Self {
            stage_id: stage_id.into(),
            name: name.into(),
            description: description.into(),
            stage_type: StageType::MapReduce { chunks },
            required_capabilities: Vec::new(),
            dependencies: Vec::new(),
            timeout: Duration::minutes(60),
            config: serde_json::json!({}),
        }
    }

    /// Create a consensus stage.
    pub fn consensus(
        stage_id: impl Into<String>,
        name: impl Into<String>,
        description: impl Into<String>,
        min_agreement: f32,
    ) -> Self {
        Self {
            stage_id: stage_id.into(),
            name: name.into(),
            description: description.into(),
            stage_type: StageType::Consensus { min_agreement },
            required_capabilities: Vec::new(),
            dependencies: Vec::new(),
            timeout: Duration::hours(1),
            config: serde_json::json!({}),
        }
    }

    /// Set required capabilities.
    pub fn with_capabilities(mut self, capabilities: Vec<String>) -> Self {
        self.required_capabilities = capabilities;
        self
    }

    /// Set dependencies.
    pub fn with_dependencies(mut self, dependencies: Vec<String>) -> Self {
        self.dependencies = dependencies;
        self
    }

    /// Set timeout.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set configuration.
    pub fn with_config(mut self, config: serde_json::Value) -> Self {
        self.config = config;
        self
    }
}

/// State of a workflow.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum WorkflowState {
    /// Workflow is defined but not started
    Draft,
    /// Workflow is currently executing
    Running,
    /// Workflow completed successfully
    Completed,
    /// Workflow failed
    Failed { reason: String },
    /// Workflow was cancelled
    Cancelled,
    /// Workflow is paused
    Paused,
}

/// A workflow definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Workflow {
    /// Unique workflow identifier
    pub workflow_id: WorkflowId,

    /// Human-readable name
    pub name: String,

    /// Description of the workflow
    pub description: String,

    /// Stages in this workflow
    pub stages: Vec<WorkflowStage>,

    /// Current state
    pub state: WorkflowState,

    /// The agent that created this workflow
    pub created_by: InstanceId,

    /// When the workflow was created
    pub created_at: DateTime<Utc>,

    /// Input data for the workflow
    pub input: serde_json::Value,
}

impl Workflow {
    /// Create a new workflow.
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        created_by: InstanceId,
    ) -> Self {
        Self {
            workflow_id: uuid::Uuid::new_v4().to_string(),
            name: name.into(),
            description: description.into(),
            stages: Vec::new(),
            state: WorkflowState::Draft,
            created_by,
            created_at: Utc::now(),
            input: serde_json::json!({}),
        }
    }

    /// Add a stage to the workflow.
    pub fn add_stage(mut self, stage: WorkflowStage) -> Self {
        self.stages.push(stage);
        self
    }

    /// Set input data.
    pub fn with_input(mut self, input: serde_json::Value) -> Self {
        self.input = input;
        self
    }

    /// Validate the workflow (check for cycles, missing dependencies, etc.).
    pub fn validate(&self) -> Result<()> {
        let stage_ids: std::collections::HashSet<_> =
            self.stages.iter().map(|s| s.stage_id.as_str()).collect();

        // Check all dependencies exist
        for stage in &self.stages {
            for dep in &stage.dependencies {
                if !stage_ids.contains(dep.as_str()) {
                    return Err(CollectiveError::WorkflowExecutionFailed(format!(
                        "Stage {} depends on unknown stage {}",
                        stage.stage_id, dep
                    )));
                }
            }
        }

        // Check for cycles (simple check)
        // TODO: Implement proper cycle detection
        for stage in &self.stages {
            if stage.dependencies.contains(&stage.stage_id) {
                return Err(CollectiveError::WorkflowExecutionFailed(format!(
                    "Stage {} has a self-dependency",
                    stage.stage_id
                )));
            }
        }

        Ok(())
    }
}

/// Tracks the execution state of a stage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StageExecution {
    /// Stage ID
    pub stage_id: String,

    /// Current state
    pub state: StageState,

    /// Agents assigned to this stage
    pub assigned_agents: Vec<InstanceId>,

    /// Results from each agent
    pub results: HashMap<InstanceId, serde_json::Value>,

    /// When the stage started
    pub started_at: Option<DateTime<Utc>>,

    /// When the stage completed
    pub completed_at: Option<DateTime<Utc>>,

    /// Error message if failed
    pub error: Option<String>,
}

impl StageExecution {
    /// Create a new stage execution.
    pub fn new(stage_id: String) -> Self {
        Self {
            stage_id,
            state: StageState::Pending,
            assigned_agents: Vec::new(),
            results: HashMap::new(),
            started_at: None,
            completed_at: None,
            error: None,
        }
    }
}

/// Tracks the execution of a workflow.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowExecution {
    /// The workflow being executed
    pub workflow_id: WorkflowId,

    /// Unique execution ID
    pub execution_id: ExecutionId,

    /// Stage execution states
    pub stages: HashMap<String, StageExecution>,

    /// Combined results from all stages
    pub results: HashMap<String, serde_json::Value>,

    /// When execution started
    pub started_at: DateTime<Utc>,

    /// When execution completed
    pub completed_at: Option<DateTime<Utc>>,

    /// Final state
    pub state: WorkflowState,
}

impl WorkflowExecution {
    /// Create a new workflow execution.
    pub fn new(workflow: &Workflow) -> Self {
        let mut stages = HashMap::new();
        for stage in &workflow.stages {
            stages.insert(
                stage.stage_id.clone(),
                StageExecution::new(stage.stage_id.clone()),
            );
        }

        Self {
            workflow_id: workflow.workflow_id.clone(),
            execution_id: uuid::Uuid::new_v4().to_string(),
            stages,
            results: HashMap::new(),
            started_at: Utc::now(),
            completed_at: None,
            state: WorkflowState::Running,
        }
    }

    /// Get stages that are ready to execute.
    pub fn ready_stages<'a>(&self, workflow: &'a Workflow) -> Vec<&'a str> {
        let mut ready = Vec::new();

        for stage in &workflow.stages {
            if let Some(execution) = self.stages.get(&stage.stage_id) {
                if execution.state != StageState::Pending {
                    continue;
                }

                // Check if all dependencies are completed
                let deps_completed = stage.dependencies.iter().all(|dep| {
                    self.stages
                        .get(dep)
                        .map(|s| s.state == StageState::Completed)
                        .unwrap_or(false)
                });

                if deps_completed {
                    ready.push(stage.stage_id.as_str());
                }
            }
        }

        ready
    }

    /// Check if the workflow is complete.
    pub fn is_complete(&self) -> bool {
        self.stages
            .values()
            .all(|s| matches!(s.state, StageState::Completed | StageState::Skipped))
    }

    /// Check if the workflow has failed.
    pub fn has_failed(&self) -> bool {
        self.stages
            .values()
            .any(|s| matches!(s.state, StageState::Failed { .. }))
    }
}

/// Orchestrates workflow execution.
#[derive(Debug)]
pub struct WorkflowEngine {
    /// This agent's instance ID
    instance_id: InstanceId,

    /// Workflow definitions
    workflows: HashMap<WorkflowId, Workflow>,

    /// Active workflow executions
    executions: HashMap<ExecutionId, WorkflowExecution>,

    /// Maximum concurrent workflows
    max_concurrent: usize,
}

impl WorkflowEngine {
    /// Create a new workflow engine.
    pub fn new(instance_id: InstanceId) -> Self {
        Self {
            instance_id,
            workflows: HashMap::new(),
            executions: HashMap::new(),
            max_concurrent: 5,
        }
    }

    /// Get this agent's instance ID.
    pub fn instance_id(&self) -> &str {
        &self.instance_id
    }

    /// Set maximum concurrent workflows.
    pub fn set_max_concurrent(&mut self, max: usize) {
        self.max_concurrent = max;
    }

    /// Register a workflow definition.
    pub fn register_workflow(&mut self, workflow: Workflow) -> Result<WorkflowId> {
        workflow.validate()?;
        let workflow_id = workflow.workflow_id.clone();
        self.workflows.insert(workflow_id.clone(), workflow);
        Ok(workflow_id)
    }

    /// Get a workflow definition.
    pub fn get_workflow(&self, workflow_id: &str) -> Option<&Workflow> {
        self.workflows.get(workflow_id)
    }

    /// Start executing a workflow.
    pub fn start_execution(&mut self, workflow_id: &str) -> Result<ExecutionId> {
        if self.executions.len() >= self.max_concurrent {
            return Err(CollectiveError::WorkflowExecutionFailed(
                "Maximum concurrent workflows reached".to_string(),
            ));
        }

        let workflow = self
            .workflows
            .get(workflow_id)
            .ok_or_else(|| CollectiveError::WorkflowNotFound(workflow_id.to_string()))?;

        let execution = WorkflowExecution::new(workflow);
        let execution_id = execution.execution_id.clone();
        self.executions.insert(execution_id.clone(), execution);

        Ok(execution_id)
    }

    /// Get an execution.
    pub fn get_execution(&self, execution_id: &str) -> Option<&WorkflowExecution> {
        self.executions.get(execution_id)
    }

    /// Get a mutable execution.
    pub fn get_execution_mut(&mut self, execution_id: &str) -> Option<&mut WorkflowExecution> {
        self.executions.get_mut(execution_id)
    }

    /// Mark a stage as started.
    pub fn start_stage(
        &mut self,
        execution_id: &str,
        stage_id: &str,
        agents: Vec<InstanceId>,
    ) -> Result<()> {
        let execution = self
            .executions
            .get_mut(execution_id)
            .ok_or_else(|| CollectiveError::WorkflowNotFound(execution_id.to_string()))?;

        if let Some(stage) = execution.stages.get_mut(stage_id) {
            stage.state = StageState::Running;
            stage.assigned_agents = agents;
            stage.started_at = Some(Utc::now());
        }

        Ok(())
    }

    /// Record a stage result from an agent.
    pub fn record_stage_result(
        &mut self,
        execution_id: &str,
        stage_id: &str,
        agent_id: InstanceId,
        result: serde_json::Value,
    ) -> Result<()> {
        let execution = self
            .executions
            .get_mut(execution_id)
            .ok_or_else(|| CollectiveError::WorkflowNotFound(execution_id.to_string()))?;

        if let Some(stage) = execution.stages.get_mut(stage_id) {
            stage.results.insert(agent_id, result);
        }

        Ok(())
    }

    /// Mark a stage as completed.
    pub fn complete_stage(
        &mut self,
        execution_id: &str,
        stage_id: &str,
        final_result: serde_json::Value,
    ) -> Result<()> {
        let execution = self
            .executions
            .get_mut(execution_id)
            .ok_or_else(|| CollectiveError::WorkflowNotFound(execution_id.to_string()))?;

        if let Some(stage) = execution.stages.get_mut(stage_id) {
            stage.state = StageState::Completed;
            stage.completed_at = Some(Utc::now());
        }

        execution.results.insert(stage_id.to_string(), final_result);

        // Check if workflow is complete
        if execution.is_complete() {
            execution.state = WorkflowState::Completed;
            execution.completed_at = Some(Utc::now());
        }

        Ok(())
    }

    /// Mark a stage as failed.
    pub fn fail_stage(&mut self, execution_id: &str, stage_id: &str, reason: String) -> Result<()> {
        let execution = self
            .executions
            .get_mut(execution_id)
            .ok_or_else(|| CollectiveError::WorkflowNotFound(execution_id.to_string()))?;

        if let Some(stage) = execution.stages.get_mut(stage_id) {
            stage.state = StageState::Failed {
                reason: reason.clone(),
            };
            stage.error = Some(reason.clone());
            stage.completed_at = Some(Utc::now());
        }

        execution.state = WorkflowState::Failed { reason };
        execution.completed_at = Some(Utc::now());

        Ok(())
    }

    /// Get stages ready for execution.
    pub fn get_ready_stages(&self, execution_id: &str) -> Result<Vec<String>> {
        let execution = self
            .executions
            .get(execution_id)
            .ok_or_else(|| CollectiveError::WorkflowNotFound(execution_id.to_string()))?;

        let workflow = self
            .workflows
            .get(&execution.workflow_id)
            .ok_or_else(|| CollectiveError::WorkflowNotFound(execution.workflow_id.clone()))?;

        Ok(execution
            .ready_stages(workflow)
            .into_iter()
            .map(String::from)
            .collect())
    }

    /// Get active executions.
    pub fn active_executions(&self) -> Vec<&WorkflowExecution> {
        self.executions
            .values()
            .filter(|e| e.state == WorkflowState::Running)
            .collect()
    }

    /// Clean up completed executions.
    pub fn cleanup_completed(&mut self, max_age: Duration) -> usize {
        let cutoff = Utc::now() - max_age;
        let before = self.executions.len();

        self.executions
            .retain(|_, e| e.completed_at.map(|t| t > cutoff).unwrap_or(true));

        before - self.executions.len()
    }
}

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

    #[test]
    fn test_workflow_creation() {
        let workflow = Workflow::new("test-workflow", "A test workflow", "agent-1".to_string())
            .add_stage(WorkflowStage::sequential(
                "stage-1",
                "First Stage",
                "Do first thing",
            ))
            .add_stage(
                WorkflowStage::parallel("stage-2", "Second Stage", "Do in parallel", 2)
                    .with_dependencies(vec!["stage-1".to_string()]),
            );

        assert_eq!(workflow.stages.len(), 2);
        assert!(workflow.validate().is_ok());
    }

    #[test]
    fn test_workflow_execution() {
        let mut engine = WorkflowEngine::new("agent-1".to_string());

        let workflow = Workflow::new("test", "Test", "agent-1".to_string())
            .add_stage(WorkflowStage::sequential("s1", "Stage 1", "First"))
            .add_stage(
                WorkflowStage::sequential("s2", "Stage 2", "Second")
                    .with_dependencies(vec!["s1".to_string()]),
            );

        let workflow_id = engine.register_workflow(workflow).unwrap();
        let execution_id = engine.start_execution(&workflow_id).unwrap();

        // Check ready stages
        let ready = engine.get_ready_stages(&execution_id).unwrap();
        assert_eq!(ready, vec!["s1"]);

        // Start and complete first stage
        engine
            .start_stage(&execution_id, "s1", vec!["agent-1".to_string()])
            .unwrap();
        engine
            .complete_stage(&execution_id, "s1", serde_json::json!({"done": true}))
            .unwrap();

        // Now s2 should be ready
        let ready = engine.get_ready_stages(&execution_id).unwrap();
        assert_eq!(ready, vec!["s2"]);
    }
}