axon-lang 4.3.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
//! v1.24.0 integration tests — Lambda + UseTool (the FINAL
//! 2 variants needed to reach 45/45 IRFlowNode graduation).
//!
//! After this step: every IRFlowNode variant has a NAMED async
//! handler in `dispatch_node`; `legacy_shim` is structurally
//! unreachable from the dispatcher entry; 33.y.l retires the shim
//! + LegacyShimHandled outcome variant in lockstep cleanup.
//!
//! D-letter coverage:
//! - D1 — 45 of 45 variants graduated (FINAL).
//! - D3 — cancel propagation across both handlers.
//! - D7 — every error case routes through DispatchError.
//! - D8 (preview) — UseTool is the 33.y.k cross-cutting anchor;
//!   33.y.j ships the explicit `use_tool: <name>` IR variant
//!   wire shape; 33.y.k extends pure_shape::run_pure_shape to
//!   plumb ChatRequest.tools through every Step with `apply:
//!   <tool>` declared.
//! - D10 — sync-runner parity: lambda + tool produce deterministic
//!   placeholders for OSS path; enterprise integration preserves
//!   SAME wire envelope.

use axon::cancel_token::CancellationFlag;
use axon::flow_dispatcher::lambda_tools::invoke_tool;
use axon::flow_dispatcher::{dispatch_node, DispatchCtx, DispatchError, NodeOutcome};
use axon::flow_execution_event::FlowExecutionEvent;
use axon::ir_nodes::*;
use tokio::sync::mpsc;

fn lambda_spec(name: &str) -> axon::ir_nodes::IRLambdaData {
    axon::ir_nodes::IRLambdaData {
        node_type: "lambda_data",
        source_line: 0,
        source_column: 0,
        name: name.into(),
        ontology: "test.ontology".into(),
        certainty: 0.8,
        temporal_frame_start: String::new(),
        temporal_frame_end: String::new(),
        provenance: "test".into(),
        derivation: "derived".into(),
    }
}

fn fresh_ctx() -> (
    DispatchCtx,
    mpsc::UnboundedReceiver<FlowExecutionEvent>,
) {
    let (tx, rx) = mpsc::unbounded_channel();
    let mut ctx = DispatchCtx::new(
        "TestFlow",
        "stub",
        "",
        CancellationFlag::new(),
        tx,
    );
    // v2.83.0 — the ΛD declarations these fixtures apply. The handler
    // elevates for real now; an undeclared name refuses (covered by the
    // fuzz arm below), so the named fixtures must resolve.
    ctx.lambda_data_specs = std::sync::Arc::new(vec![
        lambda_spec("normalize"),
        lambda_spec("clean"),
        lambda_spec("x"),
        lambda_spec("polish"),
        lambda_spec("process"),
    ]);
    (ctx, rx)
}

fn lambda_node(name: &str, target: &str, output_type: &str) -> IRFlowNode {
    IRFlowNode::LambdaDataApply(IRLambdaDataApply {
        node_type: "lambda_data_apply",
        source_line: 0,
        source_column: 0,
        lambda_data_name: name.into(),
        target: target.into(),
        output_type: output_type.into(),
    })
}

fn use_tool_node(tool: &str, arg: &str) -> IRFlowNode {
    IRFlowNode::UseTool(IRUseToolStep {
        node_type: "use_tool",
        source_line: 0,
        source_column: 0,
        tool_name: tool.into(),
        argument: arg.into(),
        named_args: Vec::new(),
    })
}

// ────────────────────────────────────────────────────────────────────
// section 1 — Public helpers
// ────────────────────────────────────────────────────────────────────

// v2.83.0 — `apply_lambda_data_resolves_target` and
// `apply_lambda_data_literal_when_target_unset` were DELETED here. They
// pinned the placeholder string "lambda:<name>(<target>)" in green — the
// v2.67.0 F18 shape — while the real evaluator sat unreached on the dead sync
// path. The elevation suite lives in `flow_dispatcher::lambda_tools::tests`,
// and its fail-closed inversion is
// `an_undeclared_lambda_fails_closed_never_placeholder`.

#[test]
fn invoke_tool_resolves_argument() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("query".into(), "weather".into());
    assert_eq!(
        invoke_tool("web_search", "query", &ctx),
        "tool:web_search(weather)"
    );
}

#[test]
fn invoke_tool_literal_when_argument_unset() {
    let (ctx, _rx) = fresh_ctx();
    assert_eq!(
        invoke_tool("eval", "2+2", &ctx),
        "tool:eval(2+2)"
    );
}

// ────────────────────────────────────────────────────────────────────
// section 2 — LambdaDataApply through dispatch_node
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn dispatch_node_routes_lambda_with_explicit_output() {
    let (mut ctx, mut rx) = fresh_ctx();
    ctx.let_bindings.insert("data".into(), "raw_input".into());
    dispatch_node(&lambda_node("normalize", "data", "normalized"), &mut ctx)
        .await
        .unwrap();
    let psi: serde_json::Value =
        serde_json::from_str(ctx.let_bindings.get("normalized").unwrap()).expect("ψ JSON");
    assert_eq!(psi["V"], "raw_input", "the elevation carries the resolved target");
    let first = rx.try_recv().unwrap();
    match first {
        FlowExecutionEvent::StepStart { step_type, .. } => {
            assert_eq!(step_type, "lambda_data_apply");
        }
        e => panic!("expected StepStart, got {e:?}"),
    }
}

#[tokio::test]
async fn lambda_canonical_fallback_when_output_empty() {
    let (mut ctx, _rx) = fresh_ctx();
    dispatch_node(&lambda_node("clean", "doc", ""), &mut ctx).await.unwrap();
    let psi: serde_json::Value =
        serde_json::from_str(ctx.let_bindings.get("doc_lambda_applied").unwrap())
            .expect("ψ JSON");
    assert_eq!(psi["V"], "doc", "unresolved binding elevates the literal");
}

// ────────────────────────────────────────────────────────────────────
// section 3 — UseTool through dispatch_node
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn dispatch_node_routes_use_tool_with_literal_arg() {
    let (mut ctx, mut rx) = fresh_ctx();
    dispatch_node(&use_tool_node("calc", "5*3"), &mut ctx).await.unwrap();
    assert_eq!(
        ctx.let_bindings.get("calc_result").unwrap(),
        "tool:calc(5*3)"
    );
    let first = rx.try_recv().unwrap();
    match first {
        FlowExecutionEvent::StepStart { step_type, .. } => {
            assert_eq!(step_type, "use_tool");
        }
        e => panic!("expected StepStart, got {e:?}"),
    }
}

#[tokio::test]
async fn use_tool_resolves_argument_through_let_bindings() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("user_query".into(), "what is rust".into());
    dispatch_node(&use_tool_node("search", "user_query"), &mut ctx)
        .await
        .unwrap();
    assert_eq!(
        ctx.let_bindings.get("search_result").unwrap(),
        "tool:search(what is rust)"
    );
}

// ────────────────────────────────────────────────────────────────────
// section 4 — Cancel propagation
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn cancel_propagates_into_both_handlers() {
    for node in vec![
        lambda_node("x", "y", "z"),
        use_tool_node("t", "a"),
    ] {
        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 5 — Composition with orchestration + cognitive
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn lambda_chain_with_remember_round_trip() {
    let (mut ctx, _rx) = fresh_ctx();
    // Bind a target via Remember
    dispatch_node(
        &IRFlowNode::Remember(IRRememberStep {
            node_type: "remember",
            source_line: 0,
            source_column: 0,
            expression: "intermediate-value".into(),
            memory_target: "draft".into(),
        }),
        &mut ctx,
    )
    .await
    .unwrap();

    // Now apply a lambda over the bound target
    dispatch_node(&lambda_node("polish", "draft", "final"), &mut ctx)
        .await
        .unwrap();
    // v2.83.0 — the recalled binding elevates to a REAL ψ whose V is the
    // remembered value; the placeholder shape is dead.
    let psi: serde_json::Value =
        serde_json::from_str(ctx.let_bindings.get("final").unwrap()).expect("ψ JSON");
    assert_eq!(psi["V"], "intermediate-value");
    assert_eq!(psi["spec_name"], "polish");
}

#[tokio::test]
async fn use_tool_inside_for_in_per_iter() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("queries".into(), "rust,python,go".into());
    let for_in = IRFlowNode::ForIn(IRForIn {
        node_type: "for_in",
        source_line: 0,
        source_column: 0,
        variable: "q".into(),
        iterable: "queries".into(),
        body: vec![use_tool_node("web_search", "q")],
    });
    dispatch_node(&for_in, &mut ctx).await.unwrap();
    // After last iter, web_search_result holds the last invocation.
    assert_eq!(
        ctx.let_bindings.get("web_search_result").unwrap(),
        "tool:web_search(go)"
    );
}

#[tokio::test]
async fn lambda_then_use_tool_chain() {
    let (mut ctx, _rx) = fresh_ctx();
    ctx.let_bindings.insert("input".into(), "raw".into());

    // Apply lambda → bind to "processed"
    dispatch_node(&lambda_node("process", "input", "processed"), &mut ctx)
        .await
        .unwrap();
    // Now use a tool on the processed result
    dispatch_node(&use_tool_node("validate", "processed"), &mut ctx)
        .await
        .unwrap();

    // v2.83.0 — the chain now threads a REAL ψ into the tool: the bound
    // value is `tool:validate(<ψ JSON>)`, not the old nested placeholder.
    let bound = ctx.let_bindings.get("validate_result").unwrap();
    assert!(bound.starts_with("tool:validate("), "{bound}");
    assert!(
        bound.contains("\"V\":\"raw\"") && bound.contains("\"spec_name\":\"process\""),
        "the elevated ψ must flow through the chain: {bound}"
    );
}

// ────────────────────────────────────────────────────────────────────
// section 6 — Step counter discipline
// ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn both_handlers_advance_step_counter() {
    let (mut ctx, _rx) = fresh_ctx();
    assert_eq!(ctx.step_counter, 0);
    dispatch_node(&lambda_node("x", "y", "z"), &mut ctx).await.unwrap();
    assert_eq!(ctx.step_counter, 1);
    dispatch_node(&use_tool_node("t", "a"), &mut ctx).await.unwrap();
    assert_eq!(ctx.step_counter, 2);
}

// ────────────────────────────────────────────────────────────────────
// section 7 — Fuzz pack (~800 LCG iters)
// ────────────────────────────────────────────────────────────────────

struct Lcg(u64);

impl Lcg {
    fn new(seed: u64) -> Self {
        let mixed = seed
            .wrapping_mul(0x9E37_79B9_7F4A_7C15)
            .wrapping_add(0xBB67_AE85_84CA_A73B);
        Self(mixed.max(1))
    }
    fn next_u64(&mut self) -> u64 {
        self.0 = self
            .0
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1_442_695_040_888_963_407);
        self.0
    }
    fn range(&mut self, max: usize) -> usize {
        (self.next_u64() as usize) % max.max(1)
    }
    fn ascii_string(&mut self, len: usize) -> String {
        let mut s = String::with_capacity(len);
        for _ in 0..len {
            let c = (self.range(95) + 32) as u8;
            s.push(c as char);
        }
        s
    }
    fn ascii_with_random_len(&mut self, max: usize) -> String {
        let len = self.range(max) + 1;
        self.ascii_string(len)
    }
    fn boolean(&mut self) -> bool {
        self.next_u64() & 1 == 1
    }
}

fn assert_no_panic(label: &str, outcome: &Result<NodeOutcome, DispatchError>) {
    match outcome {
        Ok(_) => {}
        Err(DispatchError::UpstreamCancelled) => {}
        Err(DispatchError::ChannelClosed) => {}
        // v2.83.0 — a random name is an UNDECLARED ΛD, and refusing is
        // the correct total outcome (this fuzz used to "pass" because the
        // handler fabricated a placeholder string for any input at all).
        Err(DispatchError::BackendError { name, .. }) if name.starts_with("lambda:") => {}
        Err(other) => panic!("{label}: unexpected: {other:?}"),
    }
}

#[tokio::test]
async fn fuzz_lambda_never_panics() {
    let mut lcg = Lcg::new(0xAB_CD_EF_12_34_56_78_9A);
    for iter in 0..200 {
        let (mut ctx, _rx) = fresh_ctx();
        let node = IRFlowNode::LambdaDataApply(IRLambdaDataApply {
            node_type: "lambda_data_apply",
            source_line: 0,
            source_column: 0,
            lambda_data_name: lcg.ascii_with_random_len(20),
            target: lcg.ascii_with_random_len(20),
            output_type: lcg.ascii_with_random_len(15),
        });
        let outcome = dispatch_node(&node, &mut ctx).await;
        assert_no_panic(&format!("lambda iter={iter}"), &outcome);
    }
}

#[tokio::test]
async fn fuzz_use_tool_never_panics() {
    let mut lcg = Lcg::new(0xBC_DE_F1_23_45_67_89_AB);
    for iter in 0..200 {
        let (mut ctx, _rx) = fresh_ctx();
        let node = IRFlowNode::UseTool(IRUseToolStep {
            node_type: "use_tool",
            source_line: 0,
            source_column: 0,
            tool_name: lcg.ascii_with_random_len(20),
            argument: lcg.ascii_with_random_len(30),
            named_args: Vec::new(),
        });
        let outcome = dispatch_node(&node, &mut ctx).await;
        assert_no_panic(&format!("use_tool iter={iter}"), &outcome);
    }
}

#[tokio::test]
async fn fuzz_lambda_use_tool_cancel_random_pre_dispatch() {
    let mut lcg = Lcg::new(0xCD_EF_12_34_56_78_9A_BC);
    for iter in 0..200 {
        let cancel = CancellationFlag::new();
        let pre_cancel = lcg.boolean();
        if pre_cancel {
            cancel.cancel();
        }
        let (tx, _rx) = mpsc::unbounded_channel();
        let mut ctx = DispatchCtx::new("F", "stub", "", cancel, tx);

        let node = if lcg.boolean() {
            IRFlowNode::LambdaDataApply(IRLambdaDataApply {
                node_type: "lambda_data_apply",
                source_line: 0,
                source_column: 0,
                lambda_data_name: "n".into(),
                target: "t".into(),
                output_type: "o".into(),
            })
        } else {
            IRFlowNode::UseTool(IRUseToolStep {
                node_type: "use_tool",
                source_line: 0,
                source_column: 0,
                tool_name: "t".into(),
                argument: "a".into(),
                named_args: Vec::new(),
            })
        };

        let outcome = dispatch_node(&node, &mut ctx).await;
        if pre_cancel {
            assert!(
                matches!(outcome, Err(DispatchError::UpstreamCancelled)),
                "iter={iter}: expected UpstreamCancelled, got {outcome:?}"
            );
        } else {
            assert_no_panic(&format!("cancel iter={iter}"), &outcome);
        }
    }
}

#[tokio::test]
async fn fuzz_lambda_tool_chains_never_panic() {
    let mut lcg = Lcg::new(0xDE_F1_23_45_67_89_AB_CD);
    for iter in 0..200 {
        let (mut ctx, _rx) = fresh_ctx();
        // Optionally pre-seed a target.
        if lcg.boolean() {
            ctx.let_bindings.insert("base".into(), lcg.ascii_with_random_len(15));
        }
        // Chain: lambda(base) → use_tool(lambda_output)
        let l1 = lambda_node("step1", "base", "after_lambda");
        let t1 = use_tool_node("validator", "after_lambda");
        let _ = dispatch_node(&l1, &mut ctx).await;
        let outcome = dispatch_node(&t1, &mut ctx).await;
        assert_no_panic(&format!("chain iter={iter}"), &outcome);
    }
}

#[test]
fn fuzz_pack_total_iter_count() {
    let total = (2 * 200) + 200 + 200;
    assert_eq!(total, 800, "33.y.j fuzz pack target: 800 LCG iters");
}