clm-kernel 0.0.11

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
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
//! Layer 1: Pocket Flow Monadic Workflow DAG Orchestrator
//! Canonical Path: kernel/clm_rust_core/src/layer1/workflow.rs

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use regex::Regex;

use crate::layer1::action::{ActionManifest, HoareSandwichEngine, HoareSandwichResult};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowMetadata {
    #[serde(default = "default_workflow_type")]
    pub r#type: String,
    pub name: String,
    pub description: Option<String>,
    #[serde(default = "default_author")]
    pub author: String,
}

fn default_workflow_type() -> String { "workflow".to_string() }
fn default_author() -> String { "did:clm:system".to_string() }

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowInput {
    pub name: String,
    pub format: Option<String>,
    pub description: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowStep {
    pub id: String,
    pub action: String,
    #[serde(default)]
    pub inputs: HashMap<String, String>,
    #[serde(default)]
    pub depends_on: Vec<String>,
}

impl WorkflowStep {
    pub fn extract_implicit_dependencies(&self) -> HashSet<String> {
        let mut deps = HashSet::new();
        let re = Regex::new(r"^\$([a-z0-9_\-]+)\.output").unwrap();
        for val in self.inputs.values() {
            if let Some(caps) = re.captures(val.trim())
                && let Some(m) = caps.get(1) {
                    let ref_name = m.as_str();
                    if ref_name != "workflow" {
                        deps.insert(ref_name.to_string());
                    }
                }
        }
        deps
    }

    pub fn all_dependencies(&self) -> HashSet<String> {
        let mut all: HashSet<String> = self.depends_on.iter().cloned().collect();
        for d in self.extract_implicit_dependencies() {
            all.insert(d);
        }
        all
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowOutput {
    pub name: String,
    pub source: String,
    pub format: Option<String>,
    pub description: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowManifest {
    #[serde(default = "default_version")]
    pub version: String,
    pub clm: WorkflowMetadata,
    #[serde(default)]
    pub inputs: Vec<WorkflowInput>,
    pub steps: Vec<WorkflowStep>,
    #[serde(default)]
    pub outputs: Vec<WorkflowOutput>,
}

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

impl WorkflowManifest {
    pub fn from_yaml_str(yaml_str: &str) -> Result<Self, String> {
        let manifest: WorkflowManifest = serde_yaml::from_str(yaml_str)
            .map_err(|e| format!("Failed to parse YAML WorkflowManifest: {}", e))?;
        manifest.validate_dag()?;
        Ok(manifest)
    }

    pub fn from_yaml_file<P: AsRef<Path>>(path: P) -> Result<Self, String> {
        let content = std::fs::read_to_string(path.as_ref())
            .map_err(|e| format!("Cannot read file {}: {}", path.as_ref().display(), e))?;
        Self::from_yaml_str(&content)
    }

    pub fn validate_dag(&self) -> Result<(), String> {
        let mut step_ids = HashSet::new();
        for s in &self.steps {
            if step_ids.contains(&s.id) {
                return Err(format!("Duplicate step id '{}' in workflow '{}'", s.id, self.clm.name));
            }
            step_ids.insert(s.id.clone());
        }

        let mut adj: HashMap<String, HashSet<String>> = HashMap::new();
        let mut in_degree: HashMap<String, usize> = HashMap::new();
        for sid in &step_ids {
            adj.insert(sid.clone(), HashSet::new());
            in_degree.insert(sid.clone(), 0);
        }

        for s in &self.steps {
            for dep in s.all_dependencies() {
                if !step_ids.contains(&dep) {
                    return Err(format!("Step '{}' references unknown dependency '{}'", s.id, dep));
                }
                if dep == s.id {
                    return Err(format!("Step '{}' has self-referential dependency", s.id));
                }
                if let Some(neighbors) = adj.get_mut(&dep) {
                    neighbors.insert(s.id.clone());
                }
            }
        }

        for neighbors in adj.values() {
            for neighbor in neighbors {
                if let Some(deg) = in_degree.get_mut(neighbor) {
                    *deg += 1;
                }
            }
        }

        // Kahn's algorithm
        let mut queue: Vec<String> = in_degree
            .iter()
            .filter(|(_, deg)| **deg == 0)
            .map(|(sid, _)| sid.clone())
            .collect();
        queue.sort(); // deterministic ordering

        let mut sorted_order = Vec::new();
        while !queue.is_empty() {
            let curr = queue.remove(0);
            sorted_order.push(curr.clone());
            if let Some(neighbors) = adj.get(&curr) {
                let mut next_neighbors: Vec<String> = neighbors.iter().cloned().collect();
                next_neighbors.sort();
                for n in next_neighbors {
                    if let Some(deg) = in_degree.get_mut(&n) {
                        *deg -= 1;
                        if *deg == 0 {
                            queue.push(n);
                        }
                    }
                }
            }
        }

        if sorted_order.len() != step_ids.len() {
            let cycle_nodes: Vec<String> = in_degree
                .iter()
                .filter(|(_, deg)| **deg > 0)
                .map(|(sid, _)| sid.clone())
                .collect();
            return Err(format!(
                "Workflow '{}' contains a circular dependency involving steps: {:?}",
                self.clm.name, cycle_nodes
            ));
        }

        Ok(())
    }

    pub fn get_topological_order(&self) -> Result<Vec<String>, String> {
        self.validate_dag()?;
        let step_ids: HashSet<String> = self.steps.iter().map(|s| s.id.clone()).collect();
        let mut adj: HashMap<String, HashSet<String>> = HashMap::new();
        let mut in_degree: HashMap<String, usize> = HashMap::new();
        for sid in &step_ids {
            adj.insert(sid.clone(), HashSet::new());
            in_degree.insert(sid.clone(), 0);
        }
        for s in &self.steps {
            for dep in s.all_dependencies() {
                if let Some(neighbors) = adj.get_mut(&dep) {
                    neighbors.insert(s.id.clone());
                }
            }
        }
        for neighbors in adj.values() {
            for neighbor in neighbors {
                if let Some(deg) = in_degree.get_mut(neighbor) {
                    *deg += 1;
                }
            }
        }

        let mut queue: Vec<String> = in_degree
            .iter()
            .filter(|(_, deg)| **deg == 0)
            .map(|(sid, _)| sid.clone())
            .collect();
        queue.sort();

        let mut order = Vec::new();
        while !queue.is_empty() {
            let curr = queue.remove(0);
            order.push(curr.clone());
            if let Some(neighbors) = adj.get(&curr) {
                let mut next_neighbors: Vec<String> = neighbors.iter().cloned().collect();
                next_neighbors.sort();
                for n in next_neighbors {
                    if let Some(deg) = in_degree.get_mut(&n) {
                        *deg -= 1;
                        if *deg == 0 {
                            queue.push(n);
                        }
                    }
                }
            }
        }
        Ok(order)
    }

    pub fn get_execution_stages(&self) -> Result<Vec<Vec<String>>, String> {
        let order = self.get_topological_order()?;
        let step_map: HashMap<String, &WorkflowStep> = self.steps.iter().map(|s| (s.id.clone(), s)).collect();
        let mut depths: HashMap<String, usize> = HashMap::new();

        for sid in &order {
            let step = step_map.get(sid).unwrap();
            let deps = step.all_dependencies();
            if deps.is_empty() {
                depths.insert(sid.clone(), 0);
            } else {
                let max_d = deps.iter().map(|d| depths.get(d).cloned().unwrap_or(0)).max().unwrap_or(0);
                depths.insert(sid.clone(), max_d + 1);
            }
        }

        let max_depth = depths.values().cloned().max().unwrap_or(0);
        let mut stages: Vec<Vec<String>> = vec![vec![]; max_depth + 1];
        for sid in order {
            let d = depths[&sid];
            stages[d].push(sid);
        }
        Ok(stages)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowExecutionResult {
    pub status: String,
    pub workflow_name: String,
    pub outputs: HashMap<String, String>,
    pub step_results: HashMap<String, HoareSandwichResult>,
    pub receipts: HashMap<String, String>,
    pub failed_step: Option<String>,
    pub error: Option<String>,
    pub metrics: HashMap<String, Value>,
}

pub struct PocketFlowWorkflowOrchestrator {
    pub base_dir: PathBuf,
}

impl PocketFlowWorkflowOrchestrator {
    pub fn new<P: AsRef<Path>>(base_dir: P) -> Self {
        Self {
            base_dir: base_dir.as_ref().to_path_buf(),
        }
    }

    pub fn execute(
        &self,
        manifest: &WorkflowManifest,
        inputs: &HashMap<String, String>,
    ) -> WorkflowExecutionResult {
        let t_start = std::time::Instant::now();

        // 1. Initialize scope
        let mut scope: HashMap<String, String> = HashMap::new();
        for (k, v) in inputs {
            scope.insert(format!("workflow.input.{}", k), v.clone());
            scope.insert(format!("$workflow.input.{}", k), v.clone());
            scope.insert(k.clone(), v.clone());
        }
        if let Some((_, first_val)) = inputs.iter().next() {
            scope.insert("workflow.input".to_string(), first_val.clone());
            scope.insert("$workflow.input".to_string(), first_val.clone());
        }

        // 2. Validate DAG and get topological order
        let order = match manifest.get_topological_order() {
            Ok(ord) => ord,
            Err(e) => {
                let mut metrics = HashMap::new();
                metrics.insert("wall_time_ms".to_string(), json!(0.0));
                return WorkflowExecutionResult {
                    status: "failed".to_string(),
                    workflow_name: manifest.clm.name.clone(),
                    outputs: HashMap::new(),
                    step_results: HashMap::new(),
                    receipts: HashMap::new(),
                    failed_step: None,
                    error: Some(e),
                    metrics,
                };
            }
        };

        let step_map: HashMap<String, &WorkflowStep> = manifest.steps.iter().map(|s| (s.id.clone(), s)).collect();
        let mut step_results: HashMap<String, HoareSandwichResult> = HashMap::new();
        let mut receipts: HashMap<String, String> = HashMap::new();

        for sid in &order {
            let step = step_map[sid];

            // Resolve action path with multi-fallback
            let action_p = Path::new(&step.action);
            let mut resolved_action_path = None;

            if action_p.is_file() {
                resolved_action_path = Some(action_p.to_path_buf());
            } else if self.base_dir.join(action_p).is_file() {
                resolved_action_path = Some(self.base_dir.join(action_p));
            } else if let Some(fname) = action_p.file_name()
                && self.base_dir.join(fname).is_file() {
                    resolved_action_path = Some(self.base_dir.join(fname));
                }

            if resolved_action_path.is_none()
                && let Ok(mut dir) = std::env::current_dir() {
                    for _ in 0..5 {
                        if dir.join(action_p).is_file() {
                            resolved_action_path = Some(dir.join(action_p));
                            break;
                        }
                        if !dir.pop() {
                            break;
                        }
                    }
                }

            let action_path = resolved_action_path.unwrap_or_else(|| self.base_dir.join(&step.action));

            let action_manifest = match ActionManifest::from_yaml_file(&action_path) {
                Ok(m) => m,
                Err(e) => {
                    let elapsed_ms = t_start.elapsed().as_secs_f64() * 1000.0;
                    let mut metrics = HashMap::new();
                    metrics.insert("wall_time_ms".to_string(), json!((elapsed_ms * 1000.0).round() / 1000.0));
                    return WorkflowExecutionResult {
                        status: "failed".to_string(),
                        workflow_name: manifest.clm.name.clone(),
                        outputs: HashMap::new(),
                        step_results,
                        receipts,
                        failed_step: Some(sid.clone()),
                        error: Some(format!("Failed to load action '{}': {}", step.action, e)),
                        metrics,
                    };
                }
            };

            // Bind step inputs from scope
            let mut step_bindings = HashMap::new();
            for (inp_name, binding_expr) in &step.inputs {
                let expr = binding_expr.trim();
                let resolved = scope.get(expr)
                    .or_else(|| scope.get(expr.trim_start_matches('$')))
                    .cloned()
                    .unwrap_or_else(|| {
                        // If binding_expr is a path to a file or literal
                        if Path::new(expr).is_file() {
                            std::fs::read_to_string(expr).unwrap_or_else(|_| expr.to_string())
                        } else {
                            expr.to_string()
                        }
                    });
                step_bindings.insert(inp_name.clone(), resolved);
            }

            // Execute Hoare Sandwich for step
            let step_res = HoareSandwichEngine::execute(&action_manifest, &step_bindings);

            if step_res.status != "success" {
                let elapsed_ms = t_start.elapsed().as_secs_f64() * 1000.0;
                let mut metrics = HashMap::new();
                metrics.insert("wall_time_ms".to_string(), json!((elapsed_ms * 1000.0).round() / 1000.0));
                step_results.insert(sid.clone(), step_res.clone());
                return WorkflowExecutionResult {
                    status: "failed".to_string(),
                    workflow_name: manifest.clm.name.clone(),
                    outputs: HashMap::new(),
                    step_results,
                    receipts,
                    failed_step: Some(sid.clone()),
                    error: step_res.error,
                    metrics,
                };
            }

            // Record receipt
            if let Some(r) = &step_res.receipt {
                receipts.insert(sid.clone(), r.uri.clone());
            }

            // Record outputs into scope
            if let Some((_, first_out)) = step_res.outputs.iter().next() {
                scope.insert(format!("{}.output", sid), first_out.clone());
                scope.insert(format!("${}.output", sid), first_out.clone());
            }
            for (out_name, out_payload) in &step_res.outputs {
                scope.insert(format!("{}.output.{}", sid, out_name), out_payload.clone());
                scope.insert(format!("${}.output.{}", sid, out_name), out_payload.clone());
            }

            step_results.insert(sid.clone(), step_res);
        }

        // Map declared workflow outputs
        let mut workflow_outputs = HashMap::new();
        for wf_out in &manifest.outputs {
            let source_expr = wf_out.source.trim();
            let clean_expr = source_expr.trim_start_matches('$');
            let resolved = scope.get(source_expr)
                .or_else(|| scope.get(clean_expr))
                .cloned()
                .unwrap_or_default();
            workflow_outputs.insert(wf_out.name.clone(), resolved);
        }

        let elapsed_ms = t_start.elapsed().as_secs_f64() * 1000.0;
        let mut metrics = HashMap::new();
        metrics.insert("wall_time_ms".to_string(), json!((elapsed_ms * 1000.0).round() / 1000.0));
        metrics.insert("completed_steps".to_string(), json!(step_results.len()));

        WorkflowExecutionResult {
            status: "success".to_string(),
            workflow_name: manifest.clm.name.clone(),
            outputs: workflow_outputs,
            step_results,
            receipts,
            failed_step: None,
            error: None,
            metrics,
        }
    }
}