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
//! Flow Versioning — version tracking and rollback for deployed flows.
//!
//! Each deploy of a flow creates a new version entry. The version registry
//! tracks the full history per flow, supporting:
//!   - Version listing with metadata (source hash, timestamp, deploy count)
//!   - Active version tracking (which version is currently live)
//!   - Rollback to any previous version
//!   - Source diff between versions (via stored source snapshots)
//!
//! Versions are identified by a monotonic counter per flow (v1, v2, v3...).
//! The active version is always the most recently deployed unless rolled back.

use std::collections::HashMap;
use std::time::{Duration, Instant};

// ── Version types ────────────────────────────────────────────────────────

/// A single version of a deployed flow.
#[derive(Debug, Clone, serde::Serialize)]
pub struct FlowVersion {
    /// Version number (1-indexed, monotonic per flow).
    pub version: u32,
    /// SHA-256 hash of the source code (first 12 hex chars).
    pub source_hash: String,
    /// Full source snapshot for rollback.
    #[serde(skip_serializing)]
    pub source: String,
    /// Original filename.
    pub source_file: String,
    /// Backend used for compilation.
    pub backend: String,
    /// Flow names extracted from this source.
    pub flow_names: Vec<String>,
    /// Time of deployment (elapsed since registry creation).
    pub deployed_at: Duration,
    /// Whether this version is currently active.
    pub active: bool,
}

/// Version history for a single flow.
#[derive(Debug, Clone)]
pub struct FlowHistory {
    /// Flow name (key).
    pub flow_name: String,
    /// All versions, ordered by version number.
    pub versions: Vec<FlowVersion>,
    /// Currently active version number.
    pub active_version: u32,
    /// Total deploy count.
    pub deploy_count: u32,
}

impl FlowHistory {
    fn new(flow_name: &str) -> Self {
        FlowHistory {
            flow_name: flow_name.to_string(),
            versions: Vec::new(),
            active_version: 0,
            deploy_count: 0,
        }
    }

    /// Add a new version. Returns the version number.
    fn push_version(&mut self, source: &str, source_file: &str, backend: &str, flow_names: &[String], deployed_at: Duration) -> u32 {
        self.deploy_count += 1;
        let version = self.deploy_count;

        // Deactivate previous active version
        for v in &mut self.versions {
            v.active = false;
        }

        let hash = hash_source(source);
        self.versions.push(FlowVersion {
            version,
            source_hash: hash,
            source: source.to_string(),
            source_file: source_file.to_string(),
            backend: backend.to_string(),
            flow_names: flow_names.to_vec(),
            deployed_at,
            active: true,
        });
        self.active_version = version;
        version
    }

    /// Get a specific version.
    fn get_version(&self, version: u32) -> Option<&FlowVersion> {
        self.versions.iter().find(|v| v.version == version)
    }

    /// Get the active version.
    pub fn active(&self) -> Option<&FlowVersion> {
        self.versions.iter().find(|v| v.active)
    }

    /// Rollback to a specific version. Returns Ok(source) or Err if version not found.
    fn rollback(&mut self, target_version: u32) -> Result<String, String> {
        let exists = self.versions.iter().any(|v| v.version == target_version);
        if !exists {
            return Err(format!("version {} not found for flow '{}'", target_version, self.flow_name));
        }

        for v in &mut self.versions {
            v.active = v.version == target_version;
        }
        self.active_version = target_version;

        let source = self.versions.iter()
            .find(|v| v.version == target_version)
            .map(|v| v.source.clone())
            .unwrap();

        Ok(source)
    }
}

// ── Version Registry ─────────────────────────────────────────────────────

/// Registry tracking version history for all deployed flows.
pub struct VersionRegistry {
    histories: HashMap<String, FlowHistory>,
    created_at: Instant,
}

impl VersionRegistry {
    /// Create a new empty registry.
    pub fn new() -> Self {
        VersionRegistry {
            histories: HashMap::new(),
            created_at: Instant::now(),
        }
    }

    /// Record a new deployment. Returns (flow_name, version_number) pairs.
    pub fn record_deploy(
        &mut self,
        flow_names: &[String],
        source: &str,
        source_file: &str,
        backend: &str,
    ) -> Vec<(String, u32)> {
        let deployed_at = self.created_at.elapsed();
        let mut results = Vec::new();

        for name in flow_names {
            let history = self.histories
                .entry(name.clone())
                .or_insert_with(|| FlowHistory::new(name));

            let version = history.push_version(source, source_file, backend, flow_names, deployed_at);
            results.push((name.clone(), version));
        }

        results
    }

    /// Get version history for a flow.
    pub fn get_history(&self, flow_name: &str) -> Option<&FlowHistory> {
        self.histories.get(flow_name)
    }

    /// Get a specific version of a flow.
    pub fn get_version(&self, flow_name: &str, version: u32) -> Option<&FlowVersion> {
        self.histories.get(flow_name)?.get_version(version)
    }

    /// Get the active version of a flow.
    pub fn get_active(&self, flow_name: &str) -> Option<&FlowVersion> {
        self.histories.get(flow_name)?.active()
    }

    /// Rollback a flow to a specific version. Returns the source code.
    pub fn rollback(&mut self, flow_name: &str, target_version: u32) -> Result<String, String> {
        let history = self.histories.get_mut(flow_name)
            .ok_or_else(|| format!("flow '{}' not found", flow_name))?;
        history.rollback(target_version)
    }

    /// List all flows with their active version.
    pub fn list_flows(&self) -> Vec<FlowVersionSummary> {
        let mut flows: Vec<FlowVersionSummary> = self.histories.values().map(|h| {
            FlowVersionSummary {
                flow_name: h.flow_name.clone(),
                active_version: h.active_version,
                total_versions: h.versions.len() as u32,
                deploy_count: h.deploy_count,
                source_hash: h.active().map(|v| v.source_hash.clone()).unwrap_or_default(),
            }
        }).collect();
        flows.sort_by(|a, b| a.flow_name.cmp(&b.flow_name));
        flows
    }

    /// Total number of tracked flows.
    pub fn flow_count(&self) -> usize {
        self.histories.len()
    }

    /// Total number of versions across all flows.
    pub fn total_versions(&self) -> usize {
        self.histories.values().map(|h| h.versions.len()).sum()
    }
}

/// Summary of a flow's version state.
#[derive(Debug, Clone, serde::Serialize)]
pub struct FlowVersionSummary {
    pub flow_name: String,
    pub active_version: u32,
    pub total_versions: u32,
    pub deploy_count: u32,
    pub source_hash: String,
}

// ── Helpers ──────────────────────────────────────────────────────────────

/// Compute a short hash of source code (first 12 hex chars of a simple hash).
fn hash_source(source: &str) -> String {
    // Simple FNV-1a hash (no crypto dependency needed)
    let mut hash: u64 = 0xcbf29ce484222325;
    for byte in source.bytes() {
        hash ^= byte as u64;
        hash = hash.wrapping_mul(0x100000001b3);
    }
    format!("{:016x}", hash)[..12].to_string()
}

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

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

    #[test]
    fn hash_deterministic() {
        let h1 = hash_source("persona P { tone: \"analytical\" }");
        let h2 = hash_source("persona P { tone: \"analytical\" }");
        assert_eq!(h1, h2);
        assert_eq!(h1.len(), 12);
    }

    #[test]
    fn hash_differs_for_different_source() {
        let h1 = hash_source("version 1");
        let h2 = hash_source("version 2");
        assert_ne!(h1, h2);
    }

    #[test]
    fn registry_record_deploy() {
        let mut reg = VersionRegistry::new();
        let flows = vec!["Flow1".to_string()];
        let results = reg.record_deploy(&flows, "source v1", "test.axon", "anthropic");

        assert_eq!(results.len(), 1);
        assert_eq!(results[0], ("Flow1".to_string(), 1));
        assert_eq!(reg.flow_count(), 1);
        assert_eq!(reg.total_versions(), 1);
    }

    #[test]
    fn registry_multiple_deploys() {
        let mut reg = VersionRegistry::new();
        let flows = vec!["F".to_string()];

        reg.record_deploy(&flows, "v1 source", "f.axon", "anthropic");
        reg.record_deploy(&flows, "v2 source", "f.axon", "anthropic");
        reg.record_deploy(&flows, "v3 source", "f.axon", "anthropic");

        assert_eq!(reg.flow_count(), 1);
        assert_eq!(reg.total_versions(), 3);

        let history = reg.get_history("F").unwrap();
        assert_eq!(history.deploy_count, 3);
        assert_eq!(history.active_version, 3);
        assert_eq!(history.versions.len(), 3);

        // Only v3 should be active
        assert!(!history.versions[0].active);
        assert!(!history.versions[1].active);
        assert!(history.versions[2].active);
    }

    #[test]
    fn registry_get_version() {
        let mut reg = VersionRegistry::new();
        let flows = vec!["F".to_string()];
        reg.record_deploy(&flows, "src1", "f.axon", "anthropic");
        reg.record_deploy(&flows, "src2", "f.axon", "anthropic");

        let v1 = reg.get_version("F", 1).unwrap();
        assert_eq!(v1.version, 1);
        assert_eq!(v1.source, "src1");
        assert!(!v1.active);

        let v2 = reg.get_version("F", 2).unwrap();
        assert_eq!(v2.version, 2);
        assert!(v2.active);

        assert!(reg.get_version("F", 99).is_none());
        assert!(reg.get_version("NoSuch", 1).is_none());
    }

    #[test]
    fn registry_get_active() {
        let mut reg = VersionRegistry::new();
        let flows = vec!["F".to_string()];
        reg.record_deploy(&flows, "src1", "f.axon", "anthropic");
        reg.record_deploy(&flows, "src2", "f.axon", "anthropic");

        let active = reg.get_active("F").unwrap();
        assert_eq!(active.version, 2);
        assert!(active.active);
    }

    #[test]
    fn registry_rollback() {
        let mut reg = VersionRegistry::new();
        let flows = vec!["F".to_string()];
        reg.record_deploy(&flows, "source v1", "f.axon", "anthropic");
        reg.record_deploy(&flows, "source v2", "f.axon", "anthropic");
        reg.record_deploy(&flows, "source v3", "f.axon", "anthropic");

        // Active is v3
        assert_eq!(reg.get_active("F").unwrap().version, 3);

        // Rollback to v1
        let source = reg.rollback("F", 1).unwrap();
        assert_eq!(source, "source v1");
        assert_eq!(reg.get_active("F").unwrap().version, 1);

        // v2 and v3 should be inactive
        let h = reg.get_history("F").unwrap();
        assert!(h.versions[0].active);  // v1
        assert!(!h.versions[1].active); // v2
        assert!(!h.versions[2].active); // v3
    }

    #[test]
    fn registry_rollback_not_found() {
        let mut reg = VersionRegistry::new();
        let flows = vec!["F".to_string()];
        reg.record_deploy(&flows, "src", "f.axon", "anthropic");

        assert!(reg.rollback("F", 99).is_err());
        assert!(reg.rollback("NoSuch", 1).is_err());
    }

    #[test]
    fn registry_list_flows() {
        let mut reg = VersionRegistry::new();
        reg.record_deploy(&vec!["Alpha".to_string()], "a", "a.axon", "anthropic");
        reg.record_deploy(&vec!["Beta".to_string()], "b", "b.axon", "anthropic");
        reg.record_deploy(&vec!["Alpha".to_string()], "a2", "a.axon", "anthropic");

        let list = reg.list_flows();
        assert_eq!(list.len(), 2);
        assert_eq!(list[0].flow_name, "Alpha");
        assert_eq!(list[0].active_version, 2);
        assert_eq!(list[0].total_versions, 2);
        assert_eq!(list[1].flow_name, "Beta");
        assert_eq!(list[1].active_version, 1);
    }

    #[test]
    fn registry_multi_flow_deploy() {
        let mut reg = VersionRegistry::new();
        let flows = vec!["A".to_string(), "B".to_string()];
        let results = reg.record_deploy(&flows, "multi", "m.axon", "anthropic");

        assert_eq!(results.len(), 2);
        assert_eq!(reg.flow_count(), 2);

        // Both should be at version 1
        assert_eq!(reg.get_active("A").unwrap().version, 1);
        assert_eq!(reg.get_active("B").unwrap().version, 1);
    }

    #[test]
    fn version_source_hash_stored() {
        let mut reg = VersionRegistry::new();
        let flows = vec!["F".to_string()];
        reg.record_deploy(&flows, "persona P { tone: \"x\" }", "f.axon", "anthropic");

        let v = reg.get_version("F", 1).unwrap();
        assert!(!v.source_hash.is_empty());
        assert_eq!(v.source_hash.len(), 12);
    }

    #[test]
    fn flow_version_summary_serializes() {
        let summary = FlowVersionSummary {
            flow_name: "Test".into(),
            active_version: 3,
            total_versions: 5,
            deploy_count: 5,
            source_hash: "abc123def456".into(),
        };
        let json = serde_json::to_value(&summary).unwrap();
        assert_eq!(json["flow_name"], "Test");
        assert_eq!(json["active_version"], 3);
    }
}