1use serde::Serialize;
32use std::collections::HashMap;
33use thiserror::Error;
34
35#[derive(Debug, Clone)]
38
39pub struct SimulationNode {
40 pub node_id: String,
41
42 pub node_type: String,
43
44 pub inputs: serde_json::Value,
45
46 pub outputs: serde_json::Value,
47
48 pub dependencies: Vec<String>,
49
50 pub status: NodeStatus,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
56
57pub enum NodeStatus {
58 Pending,
59
60 Running,
61
62 Completed,
63
64 Blocked,
65
66 Failed,
67}
68
69impl std::fmt::Display for NodeStatus {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 match self {
72 NodeStatus::Pending => write!(f, "PENDING"),
73
74 NodeStatus::Running => write!(f, "RUNNING"),
75
76 NodeStatus::Completed => write!(f, "COMPLETED"),
77
78 NodeStatus::Blocked => write!(f, "BLOCKED"),
79
80 NodeStatus::Failed => write!(f, "FAILED"),
81 }
82 }
83}
84
85impl SimulationNode {
86 pub fn new(node_id: &str, node_type: &str) -> Self {
87 Self {
88 node_id: node_id.to_string(),
89
90 node_type: node_type.to_string(),
91
92 inputs: serde_json::Value::Object(serde_json::Map::new()),
93
94 outputs: serde_json::Value::Object(serde_json::Map::new()),
95
96 dependencies: Vec::new(),
97
98 status: NodeStatus::Pending,
99 }
100 }
101
102 pub fn with_dependencies(mut self, deps: Vec<&str>) -> Self {
103 self.dependencies = deps.into_iter().map(String::from).collect();
104
105 self
106 }
107}
108
109#[derive(Debug, Clone, Serialize)]
112
113pub struct SimulationResult {
114 pub success: bool,
115
116 pub executed_nodes: Vec<String>,
117
118 pub failed_nodes: Vec<String>,
119
120 pub execution_order: Vec<String>,
121
122 pub total_time_ms: f64,
123}
124
125#[derive(Debug, Clone, Serialize)]
128
129pub struct DagValidationReport {
130 pub valid: bool,
131
132 pub has_cycle: bool,
133
134 pub dangling_references: Vec<String>,
135
136 pub topological_order: Vec<String>,
137
138 pub node_count: usize,
139}
140
141pub fn verify_dag_integrity(dag: &HashMap<String, SimulationNode>) -> DagValidationReport {
152 use petgraph::graph::{DiGraph, NodeIndex};
153
154 let dangling: Vec<String> = dag
157 .iter()
158 .flat_map(|(node_id, node)| {
159 node.dependencies
160 .iter()
161 .filter(|dep| !dag.contains_key(*dep))
162 .map(move |dep| format!("{} → {}", node_id, dep))
163 })
164 .collect();
165
166 let mut graph = DiGraph::<&str, ()>::new();
169
170 let mut node_map: HashMap<&str, NodeIndex> = HashMap::new();
171
172 let mut sorted_keys: Vec<&str> = dag.keys().map(|k| k.as_str()).collect();
175
176 sorted_keys.sort();
177
178 for node_id in &sorted_keys {
179 let idx = graph.add_node(node_id);
180
181 node_map.insert(node_id, idx);
182 }
183
184 for node_id in &sorted_keys {
185 let node = &dag[*node_id];
186
187 let mut sorted_deps: Vec<&str> = node.dependencies.iter().map(|d| d.as_str()).collect();
190
191 sorted_deps.sort();
192
193 for dep in sorted_deps {
194 if let (Some(&dep_idx), Some(&node_idx)) = (node_map.get(dep), node_map.get(node_id)) {
195 graph.add_edge(dep_idx, node_idx, ());
198 }
199 }
200 }
201
202 match petgraph::algo::toposort(&graph, None) {
205 Ok(sorted_indices) => {
206 let topological_order: Vec<String> = sorted_indices
207 .iter()
208 .map(|&idx| graph[idx].to_string())
209 .collect();
210
211 DagValidationReport {
212 valid: dangling.is_empty(),
213
214 has_cycle: false,
215
216 dangling_references: dangling,
217
218 topological_order,
219
220 node_count: dag.len(),
221 }
222 }
223
224 Err(_cycle) => DagValidationReport {
225 valid: false,
226
227 has_cycle: true,
228
229 dangling_references: dangling,
230
231 topological_order: Vec::new(),
232
233 node_count: dag.len(),
234 },
235 }
236}
237
238pub fn simulate_execution(dag: &mut HashMap<String, SimulationNode>) -> SimulationResult {
241 let start = std::time::Instant::now();
242
243 let integrity = verify_dag_integrity(dag);
244
245 if !integrity.valid {
246 return SimulationResult {
247 success: false,
248
249 executed_nodes: Vec::new(),
250
251 failed_nodes: dag.keys().cloned().collect(),
252
253 execution_order: Vec::new(),
254
255 total_time_ms: 0.0,
256 };
257 }
258
259 let mut executed: Vec<String> = Vec::new();
260
261 let mut failed: Vec<String> = Vec::new();
262
263 let order = integrity.topological_order.clone();
266
267 for node_id in &order {
268 let deps_met = {
271 let node = &dag[node_id];
272 node.dependencies.iter().all(|dep| {
273 dag.get(dep)
274 .is_some_and(|n| n.status == NodeStatus::Completed)
275 })
276 };
277
278 if let Some(node) = dag.get_mut(node_id) {
279 node.status = NodeStatus::Running;
280 if deps_met {
281 node.status = NodeStatus::Completed;
282 executed.push(node_id.clone());
283 } else {
284 node.status = NodeStatus::Blocked;
285 failed.push(node_id.clone());
286 }
287 } else {
288 failed.push(node_id.clone());
289 }
290 }
291
292 let elapsed = start.elapsed().as_secs_f64() * 1000.0;
293
294 SimulationResult {
295 success: failed.is_empty(),
296
297 executed_nodes: executed,
298
299 failed_nodes: failed,
300
301 execution_order: order,
302
303 total_time_ms: (elapsed * 100.0).round() / 100.0,
304 }
305}
306
307pub fn stitch_fractal_urns(parent_urn: &str, child_urns: &[&str]) -> HashMap<String, String> {
316 child_urns
317 .iter()
318 .map(|&child_urn| {
319 let leaf = child_urn.rsplit(':').next().unwrap_or(child_urn);
320
321 let fractal_urn = format!("{}:{}", parent_urn, leaf);
322
323 (child_urn.to_string(), fractal_urn)
324 })
325 .collect()
326}
327
328pub struct CausalClockEnforcer {
339 pub clock_ticks: u64,
340}
341
342#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
345
346pub struct CausalIntervention {
347 pub node_id: String,
348
349 pub forced_outputs: serde_json::Value,
350}
351
352#[derive(Error, Debug, Clone, serde::Serialize)]
354pub enum CausalError {
355 #[error("Node not found in DAG: {0}")]
356 NodeNotFound(String),
357}
358
359pub struct DoOperator;
362
363impl DoOperator {
364 pub fn apply_intervention(
379 dag: &HashMap<String, SimulationNode>,
380
381 intervention: &CausalIntervention,
382 ) -> Result<SimulationResult, CausalError> {
383 if !dag.contains_key(&intervention.node_id) {
384 return Err(CausalError::NodeNotFound(intervention.node_id.clone()));
385 }
386
387 let mut mutilated_dag = dag.clone();
388
389 let target_node = mutilated_dag
391 .get_mut(&intervention.node_id)
392 .ok_or_else(|| CausalError::NodeNotFound(intervention.node_id.clone()))?;
393
394 target_node.dependencies.clear();
395
396 target_node.outputs = intervention.forced_outputs.clone();
397
398 target_node.status = NodeStatus::Completed;
399
400 let mut result = simulate_execution(&mut mutilated_dag);
403
404 if !result.executed_nodes.contains(&intervention.node_id) {
407 result
408 .executed_nodes
409 .insert(0, intervention.node_id.clone());
410 }
411
412 Ok(result)
413 }
414}
415
416#[cfg(test)]
417
418mod tests {
419
420 use super::*;
421
422 fn make_dag() -> HashMap<String, SimulationNode> {
423 let mut dag = HashMap::new();
424
425 dag.insert("a".into(), SimulationNode::new("a", "compute"));
426
427 dag.insert(
428 "b".into(),
429 SimulationNode::new("b", "compute").with_dependencies(vec!["a"]),
430 );
431
432 dag.insert(
433 "c".into(),
434 SimulationNode::new("c", "compute").with_dependencies(vec!["a"]),
435 );
436
437 dag.insert(
438 "d".into(),
439 SimulationNode::new("d", "output").with_dependencies(vec!["b", "c"]),
440 );
441
442 dag
443 }
444
445 #[test]
446
447 fn test_verify_dag_integrity_valid() {
448 let dag = make_dag();
449
450 let report = verify_dag_integrity(&dag);
451
452 assert!(report.valid);
453
454 assert!(!report.has_cycle);
455
456 assert!(report.dangling_references.is_empty());
457
458 assert_eq!(report.node_count, 4);
459
460 let order = &report.topological_order;
463
464 let a_pos = order.iter().position(|x| x == "a").unwrap();
465
466 let b_pos = order.iter().position(|x| x == "b").unwrap();
467
468 let c_pos = order.iter().position(|x| x == "c").unwrap();
469
470 let d_pos = order.iter().position(|x| x == "d").unwrap();
471
472 assert!(a_pos < b_pos);
473
474 assert!(a_pos < c_pos);
475
476 assert!(b_pos < d_pos);
477
478 assert!(c_pos < d_pos);
479 }
480
481 #[test]
482
483 fn test_verify_dag_detects_cycle() {
484 let mut dag = HashMap::new();
485
486 dag.insert(
487 "a".into(),
488 SimulationNode::new("a", "compute").with_dependencies(vec!["b"]),
489 );
490
491 dag.insert(
492 "b".into(),
493 SimulationNode::new("b", "compute").with_dependencies(vec!["a"]),
494 );
495
496 let report = verify_dag_integrity(&dag);
497
498 assert!(!report.valid);
499
500 assert!(report.has_cycle);
501
502 assert!(report.topological_order.is_empty());
503 }
504
505 #[test]
506
507 fn test_verify_dag_detects_dangling() {
508 let mut dag = HashMap::new();
509
510 dag.insert(
511 "a".into(),
512 SimulationNode::new("a", "compute").with_dependencies(vec!["missing"]),
513 );
514
515 let report = verify_dag_integrity(&dag);
516
517 assert!(!report.valid);
518
519 assert!(!report.dangling_references.is_empty());
520 }
521
522 #[test]
523
524 fn test_simulate_execution_valid() {
525 let mut dag = make_dag();
526
527 let result = simulate_execution(&mut dag);
528
529 assert!(result.success);
530
531 assert_eq!(result.executed_nodes.len(), 4);
532
533 assert!(result.failed_nodes.is_empty());
534 }
535
536 #[test]
537
538 fn test_simulate_execution_invalid_dag() {
539 let mut dag = HashMap::new();
540
541 dag.insert(
542 "a".into(),
543 SimulationNode::new("a", "compute").with_dependencies(vec!["b"]),
544 );
545
546 dag.insert(
547 "b".into(),
548 SimulationNode::new("b", "compute").with_dependencies(vec!["a"]),
549 );
550
551 let result = simulate_execution(&mut dag);
552
553 assert!(!result.success);
554
555 assert_eq!(result.failed_nodes.len(), 2);
556 }
557
558 #[test]
559
560 fn test_stitch_fractal_urns() {
561 let bindings = stitch_fractal_urns(
562 "urn:coreason:agent:orchestrator",
563 &["urn:coreason:tool:calculator", "urn:coreason:tool:search"],
564 );
565
566 assert_eq!(
567 bindings["urn:coreason:tool:calculator"],
568 "urn:coreason:agent:orchestrator:calculator"
569 );
570
571 assert_eq!(
572 bindings["urn:coreason:tool:search"],
573 "urn:coreason:agent:orchestrator:search"
574 );
575 }
576
577 #[test]
578
579 fn test_stitch_fractal_urns_no_colon() {
580 let bindings = stitch_fractal_urns("parent", &["child"]);
581
582 assert_eq!(bindings["child"], "parent:child");
583 }
584
585 #[test]
586
587 fn test_empty_dag() {
588 let dag: HashMap<String, SimulationNode> = HashMap::new();
589
590 let report = verify_dag_integrity(&dag);
591
592 assert!(report.valid);
593
594 assert_eq!(report.node_count, 0);
595 }
596
597 #[test]
598
599 fn test_single_node_dag() {
600 let mut dag = HashMap::new();
601
602 dag.insert("solo".into(), SimulationNode::new("solo", "compute"));
603
604 let mut dag_mut = dag.clone();
605
606 let result = simulate_execution(&mut dag_mut);
607
608 assert!(result.success);
609
610 assert_eq!(result.executed_nodes.len(), 1);
611 }
612
613 #[test]
614
615 fn test_do_operator_surgery() {
616 let dag = make_dag();
617
618 let intervention = CausalIntervention {
619 node_id: "c".to_string(),
620
621 forced_outputs: serde_json::json!({"injected": true}),
622 };
623
624 let result = DoOperator::apply_intervention(&dag, &intervention).unwrap();
625
626 assert!(result.success);
627
628 assert!(result.executed_nodes.contains(&"c".to_string()));
629 }
630
631 #[test]
632
633 fn test_do_operator_node_not_found() {
634 let dag = make_dag();
635
636 let intervention = CausalIntervention {
637 node_id: "missing".to_string(),
638
639 forced_outputs: serde_json::Value::Null,
640 };
641
642 let result = DoOperator::apply_intervention(&dag, &intervention);
643
644 assert!(result.is_err());
645 }
646}