axon-lang 1.21.1

AXON v1.5.1 — first crates.io publication of the AXON language full-stack runtime. Lexer/parser/type-checker/IR generator (re-exported from axon-frontend) plus the native Rust runtime: typed channels (TypedEventBus with QoS×5, π-calculus mobility, capability extrusion via shield D8 — Fase 13.f.2), Free Monad CPS handlers (Fase 2), lease kernel + reconcile loop (Fase 3+5), Epistemic Security Kernel (ESK Fase 6), Trust Types + ReplayLog (Fase 11.a+11.c), Stateful PEM over WebSocket (Fase 11.d), Ontological Tool Synthesis (Fase 11.e), Mobile Typed Channels (Fase 13). Crate publishes as `axon-lang` to mirror the Python PyPI package; library import remains `use axon::*` so existing call sites keep working unchanged.
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
//! Parallel step scheduler — depth-based wave execution with threads.
//!
//! Organizes steps into execution waves based on dependency depth (from D15's
//! `DependencyGraph`). Steps at the same depth have no mutual dependencies
//! and can safely execute in parallel.
//!
//! Execution model:
//!   Wave 0: all root steps (no dependencies) — execute in parallel
//!   Wave 1: steps that depend only on wave-0 steps — execute in parallel
//!   Wave N: steps at depth N — execute after waves 0..N-1 complete
//!
//! Between waves, results synchronize back into the shared context so that
//! the next wave can read them via `${StepName}` interpolation.
//!
//! Thread model: uses `std::thread::scope` for safe, borrow-friendly parallelism
//! within each wave. No heap allocation for thread handles needed.

use std::collections::HashMap;

use crate::step_deps::{DependencyGraph, StepDependency};

// ── Schedule structures ───────────────────────────────────────────────────

/// A single execution wave — a group of steps that can run concurrently.
#[derive(Debug, Clone)]
pub struct Wave {
    /// Depth level of this wave (0 = root steps).
    pub depth: usize,
    /// Step names in this wave, sorted alphabetically.
    pub steps: Vec<String>,
    /// Whether this wave has multiple steps (actual parallelism possible).
    pub is_parallel: bool,
}

/// Execution schedule — ordered sequence of waves derived from dependency analysis.
#[derive(Debug, Clone)]
pub struct Schedule {
    /// Waves in execution order (depth 0 first).
    pub waves: Vec<Wave>,
    /// Total number of steps across all waves.
    pub total_steps: usize,
    /// Number of waves with actual parallelism (more than 1 step).
    pub parallel_waves: usize,
    /// Maximum parallelism (largest wave size).
    pub max_parallelism: usize,
}

impl Schedule {
    /// Check if the schedule contains any parallelizable waves.
    pub fn has_parallelism(&self) -> bool {
        self.parallel_waves > 0
    }

    /// Get the wave index for a given step name.
    pub fn wave_of(&self, step_name: &str) -> Option<usize> {
        for (i, wave) in self.waves.iter().enumerate() {
            if wave.steps.iter().any(|s| s == step_name) {
                return Some(i);
            }
        }
        None
    }

    /// Format the schedule as a compact summary string.
    pub fn summary(&self) -> String {
        if self.waves.is_empty() {
            return "empty schedule".to_string();
        }
        let wave_desc: Vec<String> = self
            .waves
            .iter()
            .map(|w| {
                if w.is_parallel {
                    format!("[{}]", w.steps.join(" | "))
                } else {
                    w.steps[0].clone()
                }
            })
            .collect();
        format!(
            "{}{} waves, {} parallel",
            wave_desc.join(""),
            self.waves.len(),
            self.parallel_waves,
        )
    }
}

// ── Schedule builder ──────────────────────────────────────────────────────

/// Build an execution schedule from a dependency graph.
pub fn build_schedule(graph: &DependencyGraph) -> Schedule {
    if graph.steps.is_empty() {
        return Schedule {
            waves: Vec::new(),
            total_steps: 0,
            parallel_waves: 0,
            max_parallelism: 0,
        };
    }

    // Calculate depth for each step
    let depths = calculate_depths(&graph.steps);

    // Group steps by depth level
    let max_depth = depths.values().copied().max().unwrap_or(0);
    let mut waves: Vec<Wave> = Vec::new();

    for d in 0..=max_depth {
        let mut steps: Vec<String> = depths
            .iter()
            .filter(|(_, &dep)| dep == d)
            .map(|(name, _)| name.clone())
            .collect();
        if steps.is_empty() {
            continue;
        }
        steps.sort();
        let is_parallel = steps.len() > 1;
        waves.push(Wave {
            depth: d,
            steps,
            is_parallel,
        });
    }

    let total_steps = graph.steps.len();
    let parallel_waves = waves.iter().filter(|w| w.is_parallel).count();
    let max_parallelism = waves.iter().map(|w| w.steps.len()).max().unwrap_or(0);

    Schedule {
        waves,
        total_steps,
        parallel_waves,
        max_parallelism,
    }
}

/// Calculate depth for each step via transitive dependency resolution.
fn calculate_depths(deps: &[StepDependency]) -> HashMap<String, usize> {
    let dep_map: HashMap<&str, &StepDependency> =
        deps.iter().map(|d| (d.name.as_str(), d)).collect();
    let mut cache: HashMap<String, usize> = HashMap::new();

    fn step_depth(
        name: &str,
        dep_map: &HashMap<&str, &StepDependency>,
        cache: &mut HashMap<String, usize>,
    ) -> usize {
        if let Some(&cached) = cache.get(name) {
            return cached;
        }
        let d = match dep_map.get(name) {
            Some(d) => d,
            None => return 0,
        };
        if d.depends_on.is_empty() {
            cache.insert(name.to_string(), 0);
            return 0;
        }
        let max_child = d
            .depends_on
            .iter()
            .map(|dep| step_depth(dep, dep_map, cache))
            .max()
            .unwrap_or(0);
        let result = max_child + 1;
        cache.insert(name.to_string(), result);
        result
    }

    for d in deps {
        step_depth(&d.name, &dep_map, &mut cache);
    }

    cache
}

// ── Wave executor ─────────────────────────────────────────────────────────

/// Result of a single step execution within a wave.
#[derive(Debug, Clone)]
pub struct WaveStepResult {
    pub step_name: String,
    pub output: String,
    pub success: bool,
}

/// Execute a wave of steps in parallel using scoped threads.
///
/// The `execute_fn` closure is called once per step, receiving the step name.
/// It must be `Send + Sync` since it runs across threads.
///
/// Returns results for all steps in the wave (order not guaranteed for parallel).
pub fn execute_wave<F>(wave: &Wave, execute_fn: F) -> Vec<WaveStepResult>
where
    F: Fn(&str) -> WaveStepResult + Send + Sync,
{
    if !wave.is_parallel || wave.steps.len() <= 1 {
        // Sequential execution — no threads needed
        return wave.steps.iter().map(|s| execute_fn(s)).collect();
    }

    // Parallel execution with scoped threads
    let mut results: Vec<WaveStepResult> = Vec::with_capacity(wave.steps.len());

    std::thread::scope(|scope| {
        let handles: Vec<_> = wave
            .steps
            .iter()
            .map(|step_name| {
                let func = &execute_fn;
                scope.spawn(move || func(step_name))
            })
            .collect();

        for handle in handles {
            match handle.join() {
                Ok(result) => results.push(result),
                Err(_) => results.push(WaveStepResult {
                    step_name: "unknown".to_string(),
                    output: "thread panicked".to_string(),
                    success: false,
                }),
            }
        }
    });

    results
}

// ── Tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::step_deps::{analyze, StepInfo};

    // ── Schedule building ─────────────────────────────────────────

    #[test]
    fn schedule_empty() {
        let graph = analyze(&[]);
        let sched = build_schedule(&graph);
        assert!(sched.waves.is_empty());
        assert_eq!(sched.total_steps, 0);
        assert_eq!(sched.parallel_waves, 0);
        assert!(!sched.has_parallelism());
    }

    #[test]
    fn schedule_single_step() {
        let steps = vec![StepInfo {
            name: "A".into(),
            step_type: "step".into(),
            user_prompt: "do A".into(),
            argument: String::new(),
        }];
        let graph = analyze(&steps);
        let sched = build_schedule(&graph);

        assert_eq!(sched.waves.len(), 1);
        assert_eq!(sched.waves[0].steps, vec!["A"]);
        assert!(!sched.waves[0].is_parallel);
        assert_eq!(sched.parallel_waves, 0);
        assert!(!sched.has_parallelism());
    }

    #[test]
    fn schedule_linear_chain() {
        // A → B → C (all sequential)
        let steps = vec![
            StepInfo { name: "A".into(), step_type: "step".into(), user_prompt: "do A".into(), argument: String::new() },
            StepInfo { name: "B".into(), step_type: "step".into(), user_prompt: "use $A".into(), argument: String::new() },
            StepInfo { name: "C".into(), step_type: "step".into(), user_prompt: "use $B".into(), argument: String::new() },
        ];
        let graph = analyze(&steps);
        let sched = build_schedule(&graph);

        assert_eq!(sched.waves.len(), 3);
        assert_eq!(sched.waves[0].steps, vec!["A"]);
        assert_eq!(sched.waves[1].steps, vec!["B"]);
        assert_eq!(sched.waves[2].steps, vec!["C"]);
        assert_eq!(sched.parallel_waves, 0);
        assert!(!sched.has_parallelism());
    }

    #[test]
    fn schedule_diamond_pattern() {
        // A → B, A → C, B+C → D
        let steps = vec![
            StepInfo { name: "A".into(), step_type: "step".into(), user_prompt: "start".into(), argument: String::new() },
            StepInfo { name: "B".into(), step_type: "step".into(), user_prompt: "use $A path1".into(), argument: String::new() },
            StepInfo { name: "C".into(), step_type: "step".into(), user_prompt: "use $A path2".into(), argument: String::new() },
            StepInfo { name: "D".into(), step_type: "step".into(), user_prompt: "combine $B and $C".into(), argument: String::new() },
        ];
        let graph = analyze(&steps);
        let sched = build_schedule(&graph);

        assert_eq!(sched.waves.len(), 3);
        assert_eq!(sched.waves[0].steps, vec!["A"]);          // depth 0
        assert_eq!(sched.waves[1].steps, vec!["B", "C"]);     // depth 1 — PARALLEL
        assert_eq!(sched.waves[2].steps, vec!["D"]);           // depth 2
        assert!(sched.waves[1].is_parallel);
        assert_eq!(sched.parallel_waves, 1);
        assert_eq!(sched.max_parallelism, 2);
        assert!(sched.has_parallelism());
    }

    #[test]
    fn schedule_all_independent() {
        // A, B, C — no dependencies, all can run in parallel
        let steps = vec![
            StepInfo { name: "A".into(), step_type: "step".into(), user_prompt: "do A".into(), argument: String::new() },
            StepInfo { name: "B".into(), step_type: "step".into(), user_prompt: "do B".into(), argument: String::new() },
            StepInfo { name: "C".into(), step_type: "step".into(), user_prompt: "do C".into(), argument: String::new() },
        ];
        let graph = analyze(&steps);
        let sched = build_schedule(&graph);

        assert_eq!(sched.waves.len(), 1);
        assert_eq!(sched.waves[0].steps, vec!["A", "B", "C"]);
        assert!(sched.waves[0].is_parallel);
        assert_eq!(sched.max_parallelism, 3);
    }

    #[test]
    fn schedule_wide_diamond() {
        // Root → B, C, D (parallel) → E
        let steps = vec![
            StepInfo { name: "Root".into(), step_type: "step".into(), user_prompt: "start".into(), argument: String::new() },
            StepInfo { name: "B".into(), step_type: "step".into(), user_prompt: "$Root b".into(), argument: String::new() },
            StepInfo { name: "C".into(), step_type: "step".into(), user_prompt: "$Root c".into(), argument: String::new() },
            StepInfo { name: "D".into(), step_type: "step".into(), user_prompt: "$Root d".into(), argument: String::new() },
            StepInfo { name: "E".into(), step_type: "step".into(), user_prompt: "$B $C $D".into(), argument: String::new() },
        ];
        let graph = analyze(&steps);
        let sched = build_schedule(&graph);

        assert_eq!(sched.waves.len(), 3);
        assert_eq!(sched.waves[0].steps, vec!["Root"]);
        assert_eq!(sched.waves[1].steps, vec!["B", "C", "D"]);
        assert!(sched.waves[1].is_parallel);
        assert_eq!(sched.waves[2].steps, vec!["E"]);
        assert_eq!(sched.max_parallelism, 3);
    }

    // ── Wave of ───────────────────────────────────────────────────

    #[test]
    fn wave_of_lookup() {
        let steps = vec![
            StepInfo { name: "A".into(), step_type: "step".into(), user_prompt: "start".into(), argument: String::new() },
            StepInfo { name: "B".into(), step_type: "step".into(), user_prompt: "$A".into(), argument: String::new() },
        ];
        let graph = analyze(&steps);
        let sched = build_schedule(&graph);

        assert_eq!(sched.wave_of("A"), Some(0));
        assert_eq!(sched.wave_of("B"), Some(1));
        assert_eq!(sched.wave_of("Z"), None);
    }

    // ── Summary ───────────────────────────────────────────────────

    #[test]
    fn schedule_summary_format() {
        let steps = vec![
            StepInfo { name: "A".into(), step_type: "step".into(), user_prompt: "start".into(), argument: String::new() },
            StepInfo { name: "B".into(), step_type: "step".into(), user_prompt: "$A b".into(), argument: String::new() },
            StepInfo { name: "C".into(), step_type: "step".into(), user_prompt: "$A c".into(), argument: String::new() },
            StepInfo { name: "D".into(), step_type: "step".into(), user_prompt: "$B $C".into(), argument: String::new() },
        ];
        let graph = analyze(&steps);
        let sched = build_schedule(&graph);
        let summary = sched.summary();

        assert!(summary.contains("A"));
        assert!(summary.contains("B | C"));
        assert!(summary.contains("D"));
        assert!(summary.contains("3 waves"));
        assert!(summary.contains("1 parallel"));
    }

    // ── Wave execution ────────────────────────────────────────────

    #[test]
    fn execute_wave_sequential() {
        let wave = Wave {
            depth: 0,
            steps: vec!["A".into()],
            is_parallel: false,
        };

        let results = execute_wave(&wave, |name| WaveStepResult {
            step_name: name.to_string(),
            output: format!("result_{name}"),
            success: true,
        });

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].step_name, "A");
        assert_eq!(results[0].output, "result_A");
    }

    #[test]
    fn execute_wave_parallel() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let wave = Wave {
            depth: 1,
            steps: vec!["B".into(), "C".into(), "D".into()],
            is_parallel: true,
        };

        let counter = AtomicUsize::new(0);

        let results = execute_wave(&wave, |name| {
            counter.fetch_add(1, Ordering::SeqCst);
            // Simulate some work
            std::thread::sleep(std::time::Duration::from_millis(10));
            WaveStepResult {
                step_name: name.to_string(),
                output: format!("done_{name}"),
                success: true,
            }
        });

        // All 3 steps executed
        assert_eq!(results.len(), 3);
        assert_eq!(counter.load(Ordering::SeqCst), 3);

        // All results present (order may vary)
        let mut names: Vec<String> = results.iter().map(|r| r.step_name.clone()).collect();
        names.sort();
        assert_eq!(names, vec!["B", "C", "D"]);
    }

    #[test]
    fn execute_wave_thread_safety() {
        use std::sync::{Arc, Mutex};

        let wave = Wave {
            depth: 0,
            steps: vec!["X".into(), "Y".into()],
            is_parallel: true,
        };

        let log = Arc::new(Mutex::new(Vec::<String>::new()));

        let results = execute_wave(&wave, |name| {
            log.lock().unwrap().push(name.to_string());
            WaveStepResult {
                step_name: name.to_string(),
                output: "ok".to_string(),
                success: true,
            }
        });

        assert_eq!(results.len(), 2);
        let entries = log.lock().unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.contains(&"X".to_string()));
        assert!(entries.contains(&"Y".to_string()));
    }
}