matrixcode-core 0.4.40

MatrixCode Agent Core - Pure logic, no UI
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
//! Workflow Definition Structures
//!
//! 定义工作流的核心数据结构,包括节点、边、类型和失败策略。
//!
//! ## Execution Modes (Pipeline vs Parallel)
//!
//! **Pipeline** (流式处理,无屏障):
//! - 任务完成后立即流转到下一阶段
//! - 不等待其他任务完成
//! - Wall-clock = 最慢的单任务链
//! - 适用场景:批量文件处理、流式数据转换
//!
//! **Parallel** (并行执行,有屏障):
//! - 所有任务并行启动
//! - 必须等待全部完成才能继续
//! - 适用场景:多维度审查、跨源数据收集、结果汇总

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// 节点类型
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NodeType {
    /// 开始节点
    Start,
    /// 结束节点
    End,
    /// 任务节点
    Task,
    /// 条件分支节点
    Condition,
    /// 并行节点
    Parallel,
    /// 流式节点 (无屏障等待)
    Pipeline,
    /// 子工作流节点
    SubWorkflow,
    /// 等待节点
    Wait,
    /// 人工审批节点
    Approval,
}

/// 执行模式 - 控制并行分支的执行策略
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionMode {
    /// Pipeline: 流式处理,无屏障等待
    /// 任务 A 完成后立即流转到下一阶段,不等待其他任务
    /// Wall-clock = 最慢的单任务链
    /// 适用场景:批量文件处理、流式数据转换
    Pipeline,

    /// Parallel: 并行执行,有屏障等待 (默认)
    /// 所有任务必须全部完成才能继续下一阶段
    /// 适用场景:多维度审查、跨源数据收集、结果汇总
    #[default]
    Parallel,
}

impl ExecutionMode {
    /// 是否需要屏障等待
    pub fn has_barrier(&self) -> bool {
        match self {
            Self::Pipeline => false,
            Self::Parallel => true,
        }
    }

    /// 获取显示名称
    pub fn display_name(&self) -> &'static str {
        match self {
            Self::Pipeline => "流式",
            Self::Parallel => "并行",
        }
    }

    /// 获取描述
    pub fn description(&self) -> &'static str {
        match self {
            Self::Pipeline => "任务流转执行,不等待其他任务",
            Self::Parallel => "所有任务并行执行,等待全部完成",
        }
    }
}

/// 失败策略类型
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FailureStrategyType {
    Retry,
    Ignore,
    Abort,
    Goto,
}

/// 失败策略配置(用于 YAML 解析)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailureStrategyConfig {
    /// 策略类型
    #[serde(rename = "type", default = "default_failure_strategy_type")]
    pub strategy_type: FailureStrategyType,
    /// 最大重试次数(仅 retry)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_attempts: Option<u32>,
    /// 重试间隔(毫秒,仅 retry)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval_ms: Option<u64>,
    /// 目标节点ID(仅 goto)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
}

fn default_failure_strategy_type() -> FailureStrategyType {
    FailureStrategyType::Abort
}

impl From<FailureStrategyConfig> for FailureStrategy {
    fn from(config: FailureStrategyConfig) -> Self {
        match config.strategy_type {
            FailureStrategyType::Retry => FailureStrategy::Retry {
                max_attempts: config.max_attempts.unwrap_or(1),
                interval_ms: config.interval_ms,
            },
            FailureStrategyType::Ignore => FailureStrategy::Ignore,
            FailureStrategyType::Abort => FailureStrategy::Abort,
            FailureStrategyType::Goto => FailureStrategy::Goto {
                target: config.target.unwrap_or_default(),
            },
        }
    }
}

impl From<FailureStrategy> for FailureStrategyConfig {
    fn from(strategy: FailureStrategy) -> Self {
        match strategy {
            FailureStrategy::Retry {
                max_attempts,
                interval_ms,
            } => FailureStrategyConfig {
                strategy_type: FailureStrategyType::Retry,
                max_attempts: Some(max_attempts),
                interval_ms,
                target: None,
            },
            FailureStrategy::Ignore => FailureStrategyConfig {
                strategy_type: FailureStrategyType::Ignore,
                max_attempts: None,
                interval_ms: None,
                target: None,
            },
            FailureStrategy::Abort => FailureStrategyConfig {
                strategy_type: FailureStrategyType::Abort,
                max_attempts: None,
                interval_ms: None,
                target: None,
            },
            FailureStrategy::Goto { target } => FailureStrategyConfig {
                strategy_type: FailureStrategyType::Goto,
                max_attempts: None,
                interval_ms: None,
                target: Some(target),
            },
        }
    }
}

/// 失败策略
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum FailureStrategy {
    /// 重试
    Retry {
        /// 最大重试次数
        max_attempts: u32,
        /// 重试间隔(毫秒)
        interval_ms: Option<u64>,
    },
    /// 忽略继续
    Ignore,
    /// 终止工作流
    #[default]
    Abort,
    /// 跳转到指定节点
    Goto {
        /// 目标节点ID
        target: String,
    },
}

impl Serialize for FailureStrategy {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let config: FailureStrategyConfig = self.clone().into();
        config.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for FailureStrategy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let config: FailureStrategyConfig = FailureStrategyConfig::deserialize(deserializer)?;
        Ok(config.into())
    }
}

/// 边定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EdgeDef {
    /// 边ID
    #[serde(default = "generate_edge_id")]
    pub id: String,
    /// 源节点ID
    pub from: String,
    /// 目标节点ID
    pub to: String,
    /// 条件表达式(可选)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub condition: Option<String>,
    /// 边标签
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

fn generate_edge_id() -> String {
    format!("edge_{}", uuid::Uuid::new_v4())
}

/// 节点定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeDef {
    /// 节点ID
    pub id: String,
    /// 节点类型
    #[serde(rename = "type")]
    pub node_type: NodeType,
    /// 节点名称
    pub name: String,
    /// 节点描述
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// 任务名称(仅任务节点)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task: Option<String>,
    /// 任务参数
    #[serde(default)]
    pub params: HashMap<String, serde_json::Value>,
    /// 失败策略
    #[serde(default)]
    pub on_failure: FailureStrategy,
    /// 超时时间(毫秒)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
    /// 条件分支(仅条件节点)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branches: Option<Vec<BranchDef>>,
    /// 并行分支(仅并行节点和流式节点)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parallel_branches: Option<Vec<ParallelBranchDef>>,
    /// 执行模式(仅并行/流式节点,默认从节点类型推断)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_mode: Option<ExecutionMode>,
    /// 子工作流名称(仅子工作流节点)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow: Option<String>,
    /// 等待时间(毫秒,仅等待节点)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wait_ms: Option<u64>,
    /// 审批人列表(仅审批节点)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub approvers: Option<Vec<String>>,
}

impl NodeDef {
    /// 获取节点的执行模式
    /// - 对于 Pipeline 类型节点,返回 Pipeline 模式
    /// - 对于 Parallel 类型节点,返回 Parallel 模式(或自定义模式)
    /// - 其他类型节点返回 None
    pub fn get_execution_mode(&self) -> Option<ExecutionMode> {
        match self.node_type {
            NodeType::Pipeline => Some(ExecutionMode::Pipeline),
            NodeType::Parallel => Some(
                self.execution_mode.unwrap_or(ExecutionMode::Parallel)
            ),
            _ => None,
        }
    }

    /// 是否需要屏障等待
    pub fn has_barrier(&self) -> bool {
        self.get_execution_mode()
            .map(|m| m.has_barrier())
            .unwrap_or(false)
    }
}

/// 条件分支定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BranchDef {
    /// 分支名称
    pub name: String,
    /// 条件表达式
    pub condition: String,
    /// 目标节点ID
    pub target: String,
}

/// 并行分支定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParallelBranchDef {
    /// 分支名称
    pub name: String,
    /// 分支节点列表
    pub nodes: Vec<NodeDef>,
    /// 执行模式(可选,默认为 Parallel)
    /// - Pipeline: 流式处理,无屏障等待
    /// - Parallel: 并行执行,等待全部完成
    #[serde(default)]
    pub mode: ExecutionMode,
}

impl ParallelBranchDef {
    /// 创建默认并行分支(Parallel 模式)
    pub fn new(name: String, nodes: Vec<NodeDef>) -> Self {
        Self {
            name,
            nodes,
            mode: ExecutionMode::default(),
        }
    }

    /// 创建 Pipeline 模式分支(流式处理)
    pub fn pipeline(name: String, nodes: Vec<NodeDef>) -> Self {
        Self {
            name,
            nodes,
            mode: ExecutionMode::Pipeline,
        }
    }

    /// 创建 Parallel 模式分支(有屏障等待)
    pub fn parallel(name: String, nodes: Vec<NodeDef>) -> Self {
        Self {
            name,
            nodes,
            mode: ExecutionMode::Parallel,
        }
    }

    /// 是否需要屏障等待
    pub fn has_barrier(&self) -> bool {
        self.mode.has_barrier()
    }

    /// 获取执行模式描述
    pub fn mode_description(&self) -> &'static str {
        self.mode.description()
    }
}

/// 工作流定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowDef {
    /// 工作流ID
    pub id: String,
    /// 工作流名称
    pub name: String,
    /// 版本
    #[serde(default = "default_version")]
    pub version: String,
    /// 描述
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// 输入参数定义
    #[serde(default)]
    pub inputs: Vec<InputDef>,
    /// 输出参数定义
    #[serde(default)]
    pub outputs: Vec<OutputDef>,
    /// 节点列表
    pub nodes: Vec<NodeDef>,
    /// 边列表
    #[serde(default)]
    pub edges: Vec<EdgeDef>,
    /// 全局变量
    #[serde(default)]
    pub variables: HashMap<String, serde_json::Value>,
    /// 默认失败策略
    #[serde(default)]
    pub default_failure_strategy: FailureStrategy,
    /// 超时时间(毫秒)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
}

fn default_version() -> String {
    "1.0.0".to_string()
}

/// 输入参数定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InputDef {
    /// 参数名
    pub name: String,
    /// 参数类型
    #[serde(rename = "type", default = "default_input_type")]
    pub input_type: String,
    /// 是否必填
    #[serde(default)]
    pub required: bool,
    /// 默认值
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<serde_json::Value>,
    /// 描述
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

fn default_input_type() -> String {
    "string".to_string()
}

/// 输出参数定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputDef {
    /// 参数名
    pub name: String,
    /// 值表达式
    pub value: String,
    /// 描述
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl WorkflowDef {
    /// 根据ID查找节点
    pub fn get_node(&self, id: &str) -> Option<&NodeDef> {
        self.nodes.iter().find(|n| n.id == id)
    }

    /// 获取开始节点
    pub fn get_start_node(&self) -> Option<&NodeDef> {
        self.nodes.iter().find(|n| n.node_type == NodeType::Start)
    }

    /// 获取结束节点
    pub fn get_end_node(&self) -> Option<&NodeDef> {
        self.nodes.iter().find(|n| n.node_type == NodeType::End)
    }

    /// 获取从指定节点出发的边
    pub fn get_outgoing_edges(&self, node_id: &str) -> Vec<&EdgeDef> {
        self.edges.iter().filter(|e| e.from == node_id).collect()
    }

    /// 验证工作流定义
    pub fn validate(&self) -> anyhow::Result<()> {
        // 检查必须有开始节点
        if self.get_start_node().is_none() {
            anyhow::bail!("Workflow must have a start node");
        }

        // 检查必须有结束节点
        if self.get_end_node().is_none() {
            anyhow::bail!("Workflow must have an end node");
        }

        // 检查节点ID唯一性
        let mut node_ids = std::collections::HashSet::new();
        for node in &self.nodes {
            if !node_ids.insert(&node.id) {
                anyhow::bail!("Duplicate node id: {}", node.id);
            }
        }

        // 检查边引用的节点是否存在
        for edge in &self.edges {
            if !node_ids.contains(&edge.from) {
                anyhow::bail!("Edge references unknown source node: {}", edge.from);
            }
            if !node_ids.contains(&edge.to) {
                anyhow::bail!("Edge references unknown target node: {}", edge.to);
            }
        }

        // 检查必填输入参数
        for input in &self.inputs {
            if input.required && input.default.is_none() {
                // 必填参数没有默认值,需要在运行时提供
            }
        }

        Ok(())
    }
}

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

    #[test]
    fn test_workflow_def_validation() {
        let workflow = WorkflowDef {
            id: "test-workflow".to_string(),
            name: "Test Workflow".to_string(),
            version: "1.0.0".to_string(),
            description: None,
            inputs: vec![],
            outputs: vec![],
            nodes: vec![
                NodeDef {
                    id: "start".to_string(),
                    node_type: NodeType::Start,
                    name: "Start".to_string(),
                    description: None,
                    task: None,
                    params: HashMap::new(),
                    on_failure: FailureStrategy::default(),
                    timeout_ms: None,
                    branches: None,
                    parallel_branches: None,
                    execution_mode: None,
                    workflow: None,
                    wait_ms: None,
                    approvers: None,
                },
                NodeDef {
                    id: "end".to_string(),
                    node_type: NodeType::End,
                    name: "End".to_string(),
                    description: None,
                    task: None,
                    params: HashMap::new(),
                    on_failure: FailureStrategy::default(),
                    timeout_ms: None,
                    branches: None,
                    parallel_branches: None,
                    execution_mode: None,
                    workflow: None,
                    wait_ms: None,
                    approvers: None,
                },
            ],
            edges: vec![EdgeDef {
                id: "e1".to_string(),
                from: "start".to_string(),
                to: "end".to_string(),
                condition: None,
                label: None,
            }],
            variables: HashMap::new(),
            default_failure_strategy: FailureStrategy::default(),
            timeout_ms: None,
        };

        assert!(workflow.validate().is_ok());
    }

    #[test]
    fn test_execution_mode_default() {
        let mode = ExecutionMode::default();
        assert_eq!(mode, ExecutionMode::Parallel);
        assert!(mode.has_barrier());
    }

    #[test]
    fn test_execution_mode_pipeline_no_barrier() {
        let mode = ExecutionMode::Pipeline;
        assert!(!mode.has_barrier());
        assert_eq!(mode.display_name(), "流式");
    }

    #[test]
    fn test_execution_mode_parallel_has_barrier() {
        let mode = ExecutionMode::Parallel;
        assert!(mode.has_barrier());
        assert_eq!(mode.display_name(), "并行");
    }

    #[test]
    fn test_parallel_branch_def_default_mode() {
        let branch = ParallelBranchDef::new("test".to_string(), vec![]);
        assert_eq!(branch.mode, ExecutionMode::Parallel);
        assert!(branch.has_barrier());
    }

    #[test]
    fn test_parallel_branch_def_pipeline_mode() {
        let branch = ParallelBranchDef::pipeline("test".to_string(), vec![]);
        assert_eq!(branch.mode, ExecutionMode::Pipeline);
        assert!(!branch.has_barrier());
    }

    #[test]
    fn test_parallel_branch_def_parallel_mode() {
        let branch = ParallelBranchDef::parallel("test".to_string(), vec![]);
        assert_eq!(branch.mode, ExecutionMode::Parallel);
        assert!(branch.has_barrier());
    }

    #[test]
    fn test_node_def_get_execution_mode_pipeline() {
        let node = NodeDef {
            id: "pipeline-node".to_string(),
            node_type: NodeType::Pipeline,
            name: "Pipeline Node".to_string(),
            description: None,
            task: None,
            params: HashMap::new(),
            on_failure: FailureStrategy::default(),
            timeout_ms: None,
            branches: None,
            parallel_branches: None,
            execution_mode: None,
            workflow: None,
            wait_ms: None,
            approvers: None,
        };
        assert_eq!(node.get_execution_mode(), Some(ExecutionMode::Pipeline));
        assert!(!node.has_barrier());
    }

    #[test]
    fn test_node_def_get_execution_mode_parallel() {
        let node = NodeDef {
            id: "parallel-node".to_string(),
            node_type: NodeType::Parallel,
            name: "Parallel Node".to_string(),
            description: None,
            task: None,
            params: HashMap::new(),
            on_failure: FailureStrategy::default(),
            timeout_ms: None,
            branches: None,
            parallel_branches: None,
            execution_mode: None,
            workflow: None,
            wait_ms: None,
            approvers: None,
        };
        assert_eq!(node.get_execution_mode(), Some(ExecutionMode::Parallel));
        assert!(node.has_barrier());
    }

    #[test]
    fn test_node_def_get_execution_mode_custom() {
        // Parallel node with custom Pipeline mode
        let node = NodeDef {
            id: "custom-node".to_string(),
            node_type: NodeType::Parallel,
            name: "Custom Node".to_string(),
            description: None,
            task: None,
            params: HashMap::new(),
            on_failure: FailureStrategy::default(),
            timeout_ms: None,
            branches: None,
            parallel_branches: None,
            execution_mode: Some(ExecutionMode::Pipeline), // Override
            workflow: None,
            wait_ms: None,
            approvers: None,
        };
        assert_eq!(node.get_execution_mode(), Some(ExecutionMode::Pipeline));
        assert!(!node.has_barrier());
    }

    #[test]
    fn test_node_def_get_execution_mode_other_types() {
        let node = NodeDef {
            id: "task-node".to_string(),
            node_type: NodeType::Task,
            name: "Task Node".to_string(),
            description: None,
            task: Some("do_something".to_string()),
            params: HashMap::new(),
            on_failure: FailureStrategy::default(),
            timeout_ms: None,
            branches: None,
            parallel_branches: None,
            execution_mode: None,
            workflow: None,
            wait_ms: None,
            approvers: None,
        };
        assert_eq!(node.get_execution_mode(), None);
    }
}