axon-lang 4.2.0

AXON β€” the formal cognitive language: a deterministic, proof-carrying AI runtime. Native Rust lexer/parser/type-checker/IR generator (re-exported from axon-frontend) plus the runtime: typed channels (Ο€-calculus mobility, capability extrusion), algebraic effects via Free Monad CPS handlers, lease kernel + reconcile loop, the Epistemic Security Kernel, Trust Types, Proof-Carrying Code (independently verifiable proof objects), and the closed-catalog extension mechanism. Crate publishes as `axon-lang`; library import is `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
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
//! v1.24.0 integration tests β€” wire integrations (Ο€-calc +
//! persistence + multi-agent deliberation).
//!
//! Exercises the 10 graduated wire-integration handlers through
//! `dispatch_node`:
//!
//! - Ο€-calc typed channels: Emit / Publish / Discover (v1.6.0)
//! - Persistence: Persist / Retrieve / Mutate / Purge / Transact
//! - Multi-agent blocks: Deliberate / Consensus
//!
//! D-letter coverage:
//! - D1 β€” 40 of 45 variants graduated (cumulative).
//! - D3 β€” cancel propagation across each handler.
//! - D7 β€” every error case routes through DispatchError.
//! - D10 β€” sync-runner parity: in-memory let_bindings backing
//!   matches the principled persistence + channel discipline.

use axon::cancel_token::CancellationFlag;
use axon::flow_dispatcher::wire_integrations::{
    discover_capability, emit_to_channel, mutate_store, persist_to_store,
    publish_capability, purge_from_store, retrieve_from_store,
};
use axon::flow_dispatcher::{dispatch_node, DispatchCtx, DispatchError, NodeOutcome};
use axon::flow_execution_event::FlowExecutionEvent;
use axon::ir_nodes::*;
use tokio::sync::mpsc;

fn fresh_ctx() -> (
    DispatchCtx,
    mpsc::UnboundedReceiver<FlowExecutionEvent>,
) {
    let (tx, rx) = mpsc::unbounded_channel();
    let ctx = DispatchCtx::new(
        "TestFlow",
        "stub",
        "",
        CancellationFlag::new(),
        tx,
    );
    (ctx, rx)
}

fn emit_node(channel: &str, value: &str) -> IRFlowNode {
    IRFlowNode::Emit(IREmit {
        node_type: "emit",
        source_line: 0,
        source_column: 0,
        channel_ref: channel.into(),
        value_ref: value.into(),
        value_is_channel: false,
        shield_ref: String::new(),
    
        breach_policy: None,
        scan: Vec::new(),
    })
}

fn publish_node(channel: &str, shield: &str) -> IRFlowNode {
    IRFlowNode::Publish(IRPublish {
        node_type: "publish",
        source_line: 0,
        source_column: 0,
        channel_ref: channel.into(),
        shield_ref: shield.into(),
        sign: String::new(),
    })
}

fn discover_node(capability: &str, alias: &str) -> IRFlowNode {
    IRFlowNode::Discover(IRDiscover {
        node_type: "discover",
        source_line: 0,
        source_column: 0,
        capability_ref: capability.into(),
        alias: alias.into(),
    })
}

fn persist_node(store: &str) -> IRFlowNode {
    IRFlowNode::Persist(IRPersistStep {
        node_type: "persist",
            fields: Vec::new(),
        source_line: 0,
        source_column: 0,
        store_name: store.into(),
    })
}

fn retrieve_node(store: &str, where_expr: &str, alias: &str) -> IRFlowNode {
    IRFlowNode::Retrieve(IRRetrieveStep {
        node_type: "retrieve",
        source_line: 0,
        source_column: 0,
        store_name: store.into(),
        where_expr: where_expr.into(),
        alias: alias.into(),
        order_by: String::new(),
        limit_expr: String::new(),
        aggregate: String::new(),
        group_by: String::new(),
        cache: String::new(),
    })
}

fn mutate_node(store: &str, where_expr: &str) -> IRFlowNode {
    IRFlowNode::Mutate(IRMutateStep {
        node_type: "mutate",
            fields: Vec::new(),
        source_line: 0,
        source_column: 0,
        store_name: store.into(),
        where_expr: where_expr.into(),
    })
}

fn purge_node(store: &str, where_expr: &str) -> IRFlowNode {
    IRFlowNode::Purge(IRPurgeStep {
        node_type: "purge",
        source_line: 0,
        source_column: 0,
        store_name: store.into(),
        where_expr: where_expr.into(),
    })
}

fn transact_node() -> IRFlowNode {
    IRFlowNode::Transact(IRTransactBlock {
        node_type: "transact",
        source_line: 0,
        source_column: 0,
    })
}

fn deliberate_node() -> IRFlowNode {
    IRFlowNode::Deliberate(IRDeliberateBlock {
        node_type: "deliberate",
        source_line: 0,
        source_column: 0,
    })
}

fn consensus_node() -> IRFlowNode {
    IRFlowNode::Consensus(IRConsensusBlock {
        node_type: "consensus",
        source_line: 0,
        source_column: 0,
    })
}

// ────────────────────────────────────────────────────────────────────
// section 1 β€” Public helpers (OSS reference impl)
// ────────────────────────────────────────────────────────────────────

#[test]
fn emit_to_channel_buffer_accumulates() {
    let (mut ctx, _rx) = fresh_ctx();
    emit_to_channel("c", "a", &mut ctx);
    emit_to_channel("c", "b", &mut ctx);
    emit_to_channel("c", "c", &mut ctx);
    assert_eq!(ctx.let_bindings.get("__channel_c").unwrap(), "a\nb\nc");
}

#[test]
fn publish_then_discover_returns_shield_ref() {
    let (mut ctx, _rx) = fresh_ctx();
    publish_capability("ch", "shield_x", &mut ctx);
    assert_eq!(discover_capability("ch", &ctx), "shield_x");
}

#[test]
fn persist_snapshots_user_level_bindings_only() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("a".into(), "1".into());
    ctx.let_bindings.insert("b".into(), "2".into());
    ctx.let_bindings.insert("__internal".into(), "hidden".into());
    let count = persist_to_store("s", &mut ctx);
    assert_eq!(count, 2);
}

#[test]
fn retrieve_returns_persisted_value() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("key".into(), "value".into());
    persist_to_store("s", &mut ctx);
    assert_eq!(retrieve_from_store("s", "key", &ctx), "value");
}

#[test]
fn mutate_updates_then_purge_removes() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("c".into(), "1".into());
    persist_to_store("s", &mut ctx);
    ctx.let_bindings.insert("c".into(), "2".into());
    assert_eq!(mutate_store("s", "c", &mut ctx), 1);
    assert_eq!(retrieve_from_store("s", "c", &ctx), "2");
    assert_eq!(purge_from_store("s", "c", &mut ctx), 1);
    assert_eq!(retrieve_from_store("s", "c", &ctx), "");
}

// ────────────────────────────────────────────────────────────────────
// section 2 β€” Emit through dispatch_node
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn dispatch_node_routes_emit_with_literal_value() {
    let (mut ctx, mut rx) = fresh_ctx();
    dispatch_node(&emit_node("outbox", "hello"), &mut ctx)
        .await
        .unwrap();
    assert_eq!(ctx.let_bindings.get("__channel_outbox").unwrap(), "hello");
    let first = rx.try_recv().unwrap();
    match first {
        FlowExecutionEvent::StepStart { step_type, .. } => {
            assert_eq!(step_type, "emit");
        }
        e => panic!("expected StepStart, got {e:?}"),
    }
}

#[tokio::test]
async fn emit_resolves_value_through_let_bindings() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("payload".into(), "real-value".into());
    dispatch_node(&emit_node("ch", "payload"), &mut ctx).await.unwrap();
    assert_eq!(ctx.let_bindings.get("__channel_ch").unwrap(), "real-value");
}

// ────────────────────────────────────────────────────────────────────
// section 3 β€” Publish + Discover through dispatch_node
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn publish_then_discover_chain() {
    let (mut ctx, _rx) = fresh_ctx();
    dispatch_node(&publish_node("secure_chan", "hipaa_shield"), &mut ctx)
        .await
        .unwrap();
    dispatch_node(&discover_node("secure_chan", "found"), &mut ctx)
        .await
        .unwrap();
    assert_eq!(ctx.let_bindings.get("found").unwrap(), "hipaa_shield");
}

#[tokio::test]
async fn discover_missing_capability_binds_empty() {
    let (mut ctx, _rx) = fresh_ctx();
    dispatch_node(&discover_node("never_published", "alias"), &mut ctx)
        .await
        .unwrap();
    assert_eq!(ctx.let_bindings.get("alias").unwrap(), "");
}

// ────────────────────────────────────────────────────────────────────
// section 4 β€” Persist through dispatch_node
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn persist_snapshots_and_retrieve_returns_value() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("user_id".into(), "42".into());
    ctx.let_bindings.insert("status".into(), "active".into());

    dispatch_node(&persist_node("users"), &mut ctx).await.unwrap();
    dispatch_node(&retrieve_node("users", "user_id", "retrieved_id"), &mut ctx)
        .await
        .unwrap();
    assert_eq!(ctx.let_bindings.get("retrieved_id").unwrap(), "42");
}

#[tokio::test]
async fn persist_returns_entry_count_in_output() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("a".into(), "1".into());
    ctx.let_bindings.insert("b".into(), "2".into());
    let outcome = dispatch_node(&persist_node("s"), &mut ctx).await.unwrap();
    match outcome {
        NodeOutcome::Completed { output, .. } => {
            assert!(output.contains("persisted 2 entries"));
        }
        other => panic!("expected Completed, got {other:?}"),
    }
}

// ────────────────────────────────────────────────────────────────────
// section 5 β€” Mutate + Purge through dispatch_node
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn mutate_chain_changes_persisted_value() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("ver".into(), "1.0".into());
    dispatch_node(&persist_node("releases"), &mut ctx).await.unwrap();

    ctx.let_bindings.insert("ver".into(), "2.0".into());
    dispatch_node(&mutate_node("releases", "ver"), &mut ctx).await.unwrap();

    // Re-retrieve from store
    dispatch_node(&retrieve_node("releases", "ver", "latest"), &mut ctx)
        .await
        .unwrap();
    assert_eq!(ctx.let_bindings.get("latest").unwrap(), "2.0");
}

#[tokio::test]
async fn purge_removes_persisted_entry() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("tmp".into(), "scratch".into());
    dispatch_node(&persist_node("workspace"), &mut ctx).await.unwrap();

    dispatch_node(&purge_node("workspace", "tmp"), &mut ctx).await.unwrap();

    dispatch_node(&retrieve_node("workspace", "tmp", "retrieved"), &mut ctx)
        .await
        .unwrap();
    assert_eq!(ctx.let_bindings.get("retrieved").unwrap(), "");
}

#[tokio::test]
async fn mutate_missing_entry_outputs_zero_count() {
    let (mut ctx, _rx) = fresh_ctx();
    let outcome = dispatch_node(&mutate_node("nonexistent", "k"), &mut ctx)
        .await
        .unwrap();
    match outcome {
        NodeOutcome::Completed { output, .. } => {
            assert!(output.contains("mutated 0 entries"));
        }
        other => panic!("expected Completed, got {other:?}"),
    }
}

// ────────────────────────────────────────────────────────────────────
// section 6 β€” Transact through dispatch_node
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn transact_sets_active_marker() {
    let (mut ctx, mut rx) = fresh_ctx();
    dispatch_node(&transact_node(), &mut ctx).await.unwrap();
    assert_eq!(ctx.let_bindings.get("__txn_active").unwrap(), "true");
    let first = rx.try_recv().unwrap();
    match first {
        FlowExecutionEvent::StepStart { step_type, .. } => {
            assert_eq!(step_type, "transact");
        }
        e => panic!("expected StepStart, got {e:?}"),
    }
}

// ────────────────────────────────────────────────────────────────────
// section 7 β€” Deliberate + Consensus through dispatch_node
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn dispatch_node_routes_deliberate() {
    let (mut ctx, mut rx) = fresh_ctx();
    let outcome = dispatch_node(&deliberate_node(), &mut ctx).await.unwrap();
    match outcome {
        NodeOutcome::Completed { output, tokens_emitted, .. } => {
            assert_eq!(output, "");
            assert_eq!(tokens_emitted, 0);
        }
        other => panic!("expected Completed, got {other:?}"),
    }
    let first = rx.try_recv().unwrap();
    match first {
        FlowExecutionEvent::StepStart { step_type, .. } => {
            assert_eq!(step_type, "deliberate");
        }
        e => panic!("expected StepStart, got {e:?}"),
    }
}

#[tokio::test]
async fn dispatch_node_routes_consensus() {
    let (mut ctx, mut rx) = fresh_ctx();
    let outcome = dispatch_node(&consensus_node(), &mut ctx).await.unwrap();
    match outcome {
        NodeOutcome::Completed { output, tokens_emitted, .. } => {
            assert_eq!(output, "");
            assert_eq!(tokens_emitted, 0);
        }
        other => panic!("expected Completed, got {other:?}"),
    }
    let first = rx.try_recv().unwrap();
    match first {
        FlowExecutionEvent::StepStart { step_type, .. } => {
            assert_eq!(step_type, "consensus");
        }
        e => panic!("expected StepStart, got {e:?}"),
    }
}

// ────────────────────────────────────────────────────────────────────
// section 8 β€” Cancel propagation
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn cancel_propagates_into_every_wire_handler() {
    let nodes: Vec<IRFlowNode> = vec![
        emit_node("c", "v"),
        publish_node("c", "s"),
        discover_node("c", "a"),
        persist_node("s"),
        retrieve_node("s", "w", "a"),
        mutate_node("s", "w"),
        purge_node("s", "w"),
        transact_node(),
        deliberate_node(),
        consensus_node(),
    ];

    for node in nodes {
        let cancel = CancellationFlag::new();
        cancel.cancel();
        let (tx, _rx) = mpsc::unbounded_channel();
        let mut ctx = DispatchCtx::new("F", "stub", "", cancel, tx);
        let outcome = dispatch_node(&node, &mut ctx).await;
        assert!(
            matches!(outcome, Err(DispatchError::UpstreamCancelled)),
            "expected UpstreamCancelled for {node:?}, got {outcome:?}"
        );
    }
}

// ────────────────────────────────────────────────────────────────────
// section 9 β€” Composition with cognitive + orchestration
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn emit_inside_for_in_per_iter_accumulates_buffer() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("xs".into(), "alpha,beta,gamma".into());
    let for_in = IRFlowNode::ForIn(IRForIn {
        node_type: "for_in",
        source_line: 0,
        source_column: 0,
        variable: "current".into(),
        iterable: "xs".into(),
        body: vec![emit_node("audit_log", "current")],
    });
    dispatch_node(&for_in, &mut ctx).await.unwrap();
    let buffer = ctx.let_bindings.get("__channel_audit_log").unwrap();
    // 3 iters β†’ 3 emissions newline-joined.
    let parts: Vec<&str> = buffer.split('\n').collect();
    assert_eq!(parts.len(), 3);
    assert_eq!(parts, vec!["alpha", "beta", "gamma"]);
}

#[tokio::test]
async fn persist_chain_with_cognitive_remember() {
    let (mut ctx, _rx) = fresh_ctx();
    // Use Remember to set up state
    dispatch_node(
        &IRFlowNode::Remember(IRRememberStep {
            node_type: "remember",
            source_line: 0,
            source_column: 0,
            expression: "snapshot-data".into(),
            memory_target: "snap".into(),
        }),
        &mut ctx,
    )
    .await
    .unwrap();

    // Now persist
    dispatch_node(&persist_node("session_snaps"), &mut ctx).await.unwrap();

    // And retrieve
    dispatch_node(&retrieve_node("session_snaps", "snap", "loaded"), &mut ctx)
        .await
        .unwrap();
    assert_eq!(ctx.let_bindings.get("loaded").unwrap(), "snapshot-data");
}

#[tokio::test]
async fn transact_then_persist_inside_block() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("k".into(), "v".into());
    dispatch_node(&transact_node(), &mut ctx).await.unwrap();
    dispatch_node(&persist_node("tx_store"), &mut ctx).await.unwrap();
    // txn_active should be true; persistence completed inside tx.
    assert_eq!(ctx.let_bindings.get("__txn_active").unwrap(), "true");
    assert_eq!(ctx.let_bindings.get("__store_tx_store_k").unwrap(), "v");
}

// ────────────────────────────────────────────────────────────────────
// v1.4.0 β€” Step counter discipline
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn all_wire_handlers_advance_step_counter() {
    let (mut ctx, _rx) = fresh_ctx();
    let nodes = vec![
        emit_node("c", "v"),
        publish_node("c", "s"),
        discover_node("c", "a"),
        persist_node("s"),
        retrieve_node("s", "w", "a"),
        mutate_node("s", "w"),
        purge_node("s", "w"),
        transact_node(),
        deliberate_node(),
        consensus_node(),
    ];
    for (i, node) in nodes.iter().enumerate() {
        dispatch_node(node, &mut ctx).await.unwrap();
        assert_eq!(ctx.step_counter, i + 1, "after {} handlers, counter={}", i + 1, ctx.step_counter);
    }
    assert_eq!(ctx.step_counter, 10);
}