axon-lang 1.38.5

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
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Health Check — structured health assessment for AxonServer subsystems.
//!
//! Provides readiness/liveness checks with per-component status:
//!   - `event_bus` — event bus operational (has published or has subscribers)
//!   - `supervisor` — daemon supervisor (no dead daemons)
//!   - `session_store` — session store accessible
//!   - `version_registry` — flow version registry accessible
//!   - `rate_limiter` — rate limiter status and configuration
//!   - `request_logger` — request log buffer utilization
//!   - `api_keys` — API key manager status
//!   - `webhooks` — webhook registry and delivery health
//!   - `audit_log` — audit trail buffer utilization
//!
//! Endpoints:
//!   - `/v1/health` — full health report with component details
//!   - `/v1/health/live` — liveness probe (always up if responding)
//!   - `/v1/health/ready` — readiness probe (all components healthy or degraded)

use serde::Serialize;
use std::collections::HashMap;

// ── Types ────────────────────────────────────────────────────────────────

/// Overall health status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum HealthStatus {
    /// All components operational.
    Healthy,
    /// Some components impaired but server can still serve requests.
    Degraded,
    /// Critical failure — server cannot serve requests reliably.
    Unhealthy,
}

impl HealthStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            HealthStatus::Healthy => "healthy",
            HealthStatus::Degraded => "degraded",
            HealthStatus::Unhealthy => "unhealthy",
        }
    }
}

/// Result of checking a single component.
#[derive(Debug, Clone, Serialize)]
pub struct ComponentCheck {
    pub name: String,
    pub status: HealthStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<serde_json::Value>,
}

/// Full health report.
#[derive(Debug, Clone, Serialize)]
pub struct HealthReport {
    pub status: HealthStatus,
    pub uptime_secs: u64,
    pub axon_version: String,
    pub components: Vec<ComponentCheck>,
}

// ── Input snapshot ───────────────────────────────────────────────────────

/// Lightweight snapshot of server state for health evaluation.
/// Decouples health logic from the locked ServerState.
pub struct HealthInput {
    pub uptime_secs: u64,
    pub axon_version: String,
    pub daemon_count: usize,
    pub daemon_state_counts: HashMap<String, usize>,
    pub bus_events_published: u64,
    pub bus_subscriber_count: usize,
    pub session_memory_count: usize,
    pub session_store_count: usize,
    pub flows_tracked: usize,
    pub versions_total: usize,
    // D45: new component fields
    pub rate_limiter_enabled: bool,
    pub rate_limiter_max_requests: u32,
    pub rate_limiter_window_secs: u64,
    pub request_log_enabled: bool,
    pub request_log_entries: usize,
    pub request_log_capacity: usize,
    pub api_keys_enabled: bool,
    pub api_keys_active: usize,
    pub api_keys_total: usize,
    pub webhooks_active: usize,
    pub webhooks_total: usize,
    pub webhooks_total_failures: u64,
    pub audit_log_entries: usize,
    pub audit_log_total_recorded: u64,
}

// ── Evaluation ───────────────────────────────────────────────────────────

/// Evaluate full health from a server snapshot.
pub fn evaluate(input: &HealthInput) -> HealthReport {
    let mut components = Vec::new();

    // Event bus check
    components.push(check_event_bus(input));

    // Supervisor check
    components.push(check_supervisor(input));

    // Session store check
    components.push(check_session_store(input));

    // Version registry check
    components.push(check_version_registry(input));

    // Rate limiter check
    components.push(check_rate_limiter(input));

    // Request logger check
    components.push(check_request_logger(input));

    // API keys check
    components.push(check_api_keys(input));

    // Webhooks check
    components.push(check_webhooks(input));

    // Audit log check
    components.push(check_audit_log(input));

    // Aggregate status: unhealthy if any unhealthy, degraded if any degraded
    let status = aggregate_status(&components);

    HealthReport {
        status,
        uptime_secs: input.uptime_secs,
        axon_version: input.axon_version.clone(),
        components,
    }
}

/// Liveness check — always alive if the server is responding.
pub fn liveness() -> serde_json::Value {
    serde_json::json!({
        "status": "alive"
    })
}

/// Readiness check — ready if no component is unhealthy.
pub fn readiness(input: &HealthInput) -> serde_json::Value {
    let report = evaluate(input);
    let ready = report.status != HealthStatus::Unhealthy;
    serde_json::json!({
        "ready": ready,
        "status": report.status.as_str()
    })
}

// ── Component checks ─────────────────────────────────────────────────────

fn check_event_bus(input: &HealthInput) -> ComponentCheck {
    let details = serde_json::json!({
        "events_published": input.bus_events_published,
        "subscriber_count": input.bus_subscriber_count,
    });

    // Bus is always healthy — it's an in-process channel, never "down"
    ComponentCheck {
        name: "event_bus".to_string(),
        status: HealthStatus::Healthy,
        message: None,
        details: Some(details),
    }
}

fn check_supervisor(input: &HealthInput) -> ComponentCheck {
    let dead = input.daemon_state_counts.get("dead").copied().unwrap_or(0);
    let total = input.daemon_count;

    let details = serde_json::json!({
        "daemon_count": total,
        "states": input.daemon_state_counts,
    });

    let (status, message) = if dead > 0 && dead == total && total > 0 {
        (HealthStatus::Unhealthy, Some(format!("all {} daemons dead", total)))
    } else if dead > 0 {
        (HealthStatus::Degraded, Some(format!("{} of {} daemons dead", dead, total)))
    } else {
        (HealthStatus::Healthy, None)
    };

    ComponentCheck {
        name: "supervisor".to_string(),
        status,
        message,
        details: Some(details),
    }
}

fn check_session_store(input: &HealthInput) -> ComponentCheck {
    let details = serde_json::json!({
        "memory_entries": input.session_memory_count,
        "persistent_entries": input.session_store_count,
    });

    // Session store is in-process HashMap + file — always accessible
    ComponentCheck {
        name: "session_store".to_string(),
        status: HealthStatus::Healthy,
        message: None,
        details: Some(details),
    }
}

fn check_version_registry(input: &HealthInput) -> ComponentCheck {
    let details = serde_json::json!({
        "flows_tracked": input.flows_tracked,
        "versions_total": input.versions_total,
    });

    ComponentCheck {
        name: "version_registry".to_string(),
        status: HealthStatus::Healthy,
        message: None,
        details: Some(details),
    }
}

fn check_rate_limiter(input: &HealthInput) -> ComponentCheck {
    let details = serde_json::json!({
        "enabled": input.rate_limiter_enabled,
        "max_requests": input.rate_limiter_max_requests,
        "window_secs": input.rate_limiter_window_secs,
    });

    ComponentCheck {
        name: "rate_limiter".to_string(),
        status: HealthStatus::Healthy,
        message: if !input.rate_limiter_enabled { Some("disabled".to_string()) } else { None },
        details: Some(details),
    }
}

fn check_request_logger(input: &HealthInput) -> ComponentCheck {
    let details = serde_json::json!({
        "enabled": input.request_log_enabled,
        "entries": input.request_log_entries,
        "capacity": input.request_log_capacity,
    });

    // Degraded if buffer is >90% full
    let (status, message) = if !input.request_log_enabled {
        (HealthStatus::Healthy, Some("disabled".to_string()))
    } else if input.request_log_capacity > 0 && input.request_log_entries * 100 / input.request_log_capacity > 90 {
        (HealthStatus::Degraded, Some(format!("buffer {}% full ({}/{})", input.request_log_entries * 100 / input.request_log_capacity, input.request_log_entries, input.request_log_capacity)))
    } else {
        (HealthStatus::Healthy, None)
    };

    ComponentCheck {
        name: "request_logger".to_string(),
        status,
        message,
        details: Some(details),
    }
}

fn check_api_keys(input: &HealthInput) -> ComponentCheck {
    let details = serde_json::json!({
        "enabled": input.api_keys_enabled,
        "active_keys": input.api_keys_active,
        "total_keys": input.api_keys_total,
    });

    // Degraded if auth enabled but no active keys (locked out risk)
    let (status, message) = if input.api_keys_enabled && input.api_keys_active == 0 && input.api_keys_total > 0 {
        (HealthStatus::Degraded, Some("all keys revoked — only master token works".to_string()))
    } else {
        (HealthStatus::Healthy, None)
    };

    ComponentCheck {
        name: "api_keys".to_string(),
        status,
        message,
        details: Some(details),
    }
}

fn check_webhooks(input: &HealthInput) -> ComponentCheck {
    let details = serde_json::json!({
        "active_webhooks": input.webhooks_active,
        "total_webhooks": input.webhooks_total,
        "total_failures": input.webhooks_total_failures,
    });

    // Degraded if >50% of webhooks have failures
    let (status, message) = if input.webhooks_total > 0 && input.webhooks_total_failures > input.webhooks_total as u64 * 5 {
        (HealthStatus::Degraded, Some(format!("{} delivery failures across {} webhooks", input.webhooks_total_failures, input.webhooks_total)))
    } else {
        (HealthStatus::Healthy, None)
    };

    ComponentCheck {
        name: "webhooks".to_string(),
        status,
        message,
        details: Some(details),
    }
}

fn check_audit_log(input: &HealthInput) -> ComponentCheck {
    let details = serde_json::json!({
        "buffered_entries": input.audit_log_entries,
        "total_recorded": input.audit_log_total_recorded,
    });

    ComponentCheck {
        name: "audit_log".to_string(),
        status: HealthStatus::Healthy,
        message: None,
        details: Some(details),
    }
}

fn aggregate_status(components: &[ComponentCheck]) -> HealthStatus {
    let mut worst = HealthStatus::Healthy;
    for c in components {
        match c.status {
            HealthStatus::Unhealthy => return HealthStatus::Unhealthy,
            HealthStatus::Degraded => worst = HealthStatus::Degraded,
            HealthStatus::Healthy => {}
        }
    }
    worst
}

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

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

    fn sample_input() -> HealthInput {
        let mut states = HashMap::new();
        states.insert("running".to_string(), 2);
        states.insert("waiting".to_string(), 1);

        HealthInput {
            uptime_secs: 3600,
            axon_version: "0.31.0".to_string(),
            daemon_count: 3,
            daemon_state_counts: states,
            bus_events_published: 100,
            bus_subscriber_count: 3,
            session_memory_count: 5,
            session_store_count: 2,
            flows_tracked: 4,
            versions_total: 10,
            rate_limiter_enabled: true,
            rate_limiter_max_requests: 100,
            rate_limiter_window_secs: 60,
            request_log_enabled: true,
            request_log_entries: 50,
            request_log_capacity: 1000,
            api_keys_enabled: true,
            api_keys_active: 3,
            api_keys_total: 5,
            webhooks_active: 2,
            webhooks_total: 3,
            webhooks_total_failures: 0,
            audit_log_entries: 100,
            audit_log_total_recorded: 150,
        }
    }

    #[test]
    fn healthy_report_all_green() {
        let report = evaluate(&sample_input());
        assert_eq!(report.status, HealthStatus::Healthy);
        assert_eq!(report.components.len(), 9);
        for c in &report.components {
            assert_eq!(c.status, HealthStatus::Healthy, "component {} not healthy", c.name);
        }
    }

    #[test]
    fn degraded_when_some_daemons_dead() {
        let mut input = sample_input();
        input.daemon_state_counts.insert("dead".to_string(), 1);
        let report = evaluate(&input);
        assert_eq!(report.status, HealthStatus::Degraded);
        let sup = report.components.iter().find(|c| c.name == "supervisor").unwrap();
        assert_eq!(sup.status, HealthStatus::Degraded);
        assert!(sup.message.as_ref().unwrap().contains("1 of"));
    }

    #[test]
    fn unhealthy_when_all_daemons_dead() {
        let mut states = HashMap::new();
        states.insert("dead".to_string(), 3);
        let mut input = sample_input();
        input.daemon_count = 3;
        input.daemon_state_counts = states;
        let report = evaluate(&input);
        assert_eq!(report.status, HealthStatus::Unhealthy);
        let sup = report.components.iter().find(|c| c.name == "supervisor").unwrap();
        assert_eq!(sup.status, HealthStatus::Unhealthy);
        assert!(sup.message.as_ref().unwrap().contains("all 3 daemons dead"));
    }

    #[test]
    fn healthy_when_no_daemons() {
        let mut input = sample_input();
        input.daemon_count = 0;
        input.daemon_state_counts.clear();
        let report = evaluate(&input);
        assert_eq!(report.status, HealthStatus::Healthy);
    }

    #[test]
    fn liveness_always_alive() {
        let live = liveness();
        assert_eq!(live["status"], "alive");
    }

    #[test]
    fn readiness_true_when_healthy() {
        let ready = readiness(&sample_input());
        assert_eq!(ready["ready"], true);
        assert_eq!(ready["status"], "healthy");
    }

    #[test]
    fn readiness_true_when_degraded() {
        let mut input = sample_input();
        input.daemon_state_counts.insert("dead".to_string(), 1);
        let ready = readiness(&input);
        assert_eq!(ready["ready"], true);
        assert_eq!(ready["status"], "degraded");
    }

    #[test]
    fn readiness_false_when_unhealthy() {
        let mut states = HashMap::new();
        states.insert("dead".to_string(), 2);
        let mut input = sample_input();
        input.daemon_count = 2;
        input.daemon_state_counts = states;
        let ready = readiness(&input);
        assert_eq!(ready["ready"], false);
        assert_eq!(ready["status"], "unhealthy");
    }

    #[test]
    fn report_includes_uptime_and_version() {
        let report = evaluate(&sample_input());
        assert_eq!(report.uptime_secs, 3600);
        assert_eq!(report.axon_version, "0.31.0");
    }

    #[test]
    fn component_details_present() {
        let report = evaluate(&sample_input());
        for c in &report.components {
            assert!(c.details.is_some(), "component {} missing details", c.name);
        }
    }

    #[test]
    fn event_bus_details_contain_counts() {
        let report = evaluate(&sample_input());
        let bus = report.components.iter().find(|c| c.name == "event_bus").unwrap();
        let d = bus.details.as_ref().unwrap();
        assert_eq!(d["events_published"], 100);
        assert_eq!(d["subscriber_count"], 3);
    }

    #[test]
    fn supervisor_details_contain_states() {
        let report = evaluate(&sample_input());
        let sup = report.components.iter().find(|c| c.name == "supervisor").unwrap();
        let d = sup.details.as_ref().unwrap();
        assert_eq!(d["daemon_count"], 3);
        assert!(d["states"].is_object());
    }

    #[test]
    fn session_store_details() {
        let report = evaluate(&sample_input());
        let sess = report.components.iter().find(|c| c.name == "session_store").unwrap();
        let d = sess.details.as_ref().unwrap();
        assert_eq!(d["memory_entries"], 5);
        assert_eq!(d["persistent_entries"], 2);
    }

    #[test]
    fn version_registry_details() {
        let report = evaluate(&sample_input());
        let ver = report.components.iter().find(|c| c.name == "version_registry").unwrap();
        let d = ver.details.as_ref().unwrap();
        assert_eq!(d["flows_tracked"], 4);
        assert_eq!(d["versions_total"], 10);
    }

    #[test]
    fn health_status_serialization() {
        let json = serde_json::to_string(&HealthStatus::Healthy).unwrap();
        assert_eq!(json, "\"healthy\"");
        let json = serde_json::to_string(&HealthStatus::Degraded).unwrap();
        assert_eq!(json, "\"degraded\"");
        let json = serde_json::to_string(&HealthStatus::Unhealthy).unwrap();
        assert_eq!(json, "\"unhealthy\"");
    }

    #[test]
    fn full_report_serializable() {
        let report = evaluate(&sample_input());
        let json = serde_json::to_string(&report).unwrap();
        assert!(json.contains("\"healthy\""));
        assert!(json.contains("\"event_bus\""));
        assert!(json.contains("\"supervisor\""));
        assert!(json.contains("\"session_store\""));
        assert!(json.contains("\"version_registry\""));
        assert!(json.contains("\"rate_limiter\""));
        assert!(json.contains("\"request_logger\""));
        assert!(json.contains("\"api_keys\""));
        assert!(json.contains("\"webhooks\""));
        assert!(json.contains("\"audit_log\""));
    }

    #[test]
    fn aggregate_picks_worst_status() {
        let checks = vec![
            ComponentCheck { name: "a".into(), status: HealthStatus::Healthy, message: None, details: None },
            ComponentCheck { name: "b".into(), status: HealthStatus::Degraded, message: None, details: None },
            ComponentCheck { name: "c".into(), status: HealthStatus::Healthy, message: None, details: None },
        ];
        assert_eq!(aggregate_status(&checks), HealthStatus::Degraded);

        let checks2 = vec![
            ComponentCheck { name: "a".into(), status: HealthStatus::Degraded, message: None, details: None },
            ComponentCheck { name: "b".into(), status: HealthStatus::Unhealthy, message: None, details: None },
        ];
        assert_eq!(aggregate_status(&checks2), HealthStatus::Unhealthy);
    }

    #[test]
    fn rate_limiter_details() {
        let report = evaluate(&sample_input());
        let rl = report.components.iter().find(|c| c.name == "rate_limiter").unwrap();
        assert_eq!(rl.status, HealthStatus::Healthy);
        let d = rl.details.as_ref().unwrap();
        assert_eq!(d["enabled"], true);
        assert_eq!(d["max_requests"], 100);
        assert_eq!(d["window_secs"], 60);
    }

    #[test]
    fn rate_limiter_disabled_shows_message() {
        let mut input = sample_input();
        input.rate_limiter_enabled = false;
        let report = evaluate(&input);
        let rl = report.components.iter().find(|c| c.name == "rate_limiter").unwrap();
        assert_eq!(rl.status, HealthStatus::Healthy);
        assert_eq!(rl.message.as_deref(), Some("disabled"));
    }

    #[test]
    fn request_logger_degraded_when_buffer_full() {
        let mut input = sample_input();
        input.request_log_entries = 950;
        input.request_log_capacity = 1000;
        let report = evaluate(&input);
        let rl = report.components.iter().find(|c| c.name == "request_logger").unwrap();
        assert_eq!(rl.status, HealthStatus::Degraded);
        assert!(rl.message.as_ref().unwrap().contains("95%"));
    }

    #[test]
    fn request_logger_healthy_when_low_usage() {
        let report = evaluate(&sample_input());
        let rl = report.components.iter().find(|c| c.name == "request_logger").unwrap();
        assert_eq!(rl.status, HealthStatus::Healthy);
        assert!(rl.message.is_none());
    }

    #[test]
    fn api_keys_degraded_when_all_revoked() {
        let mut input = sample_input();
        input.api_keys_active = 0;
        input.api_keys_total = 3;
        let report = evaluate(&input);
        let ak = report.components.iter().find(|c| c.name == "api_keys").unwrap();
        assert_eq!(ak.status, HealthStatus::Degraded);
        assert!(ak.message.as_ref().unwrap().contains("all keys revoked"));
    }

    #[test]
    fn api_keys_healthy_when_disabled() {
        let mut input = sample_input();
        input.api_keys_enabled = false;
        input.api_keys_active = 0;
        input.api_keys_total = 0;
        let report = evaluate(&input);
        let ak = report.components.iter().find(|c| c.name == "api_keys").unwrap();
        assert_eq!(ak.status, HealthStatus::Healthy);
    }

    #[test]
    fn webhooks_degraded_when_many_failures() {
        let mut input = sample_input();
        input.webhooks_total = 2;
        input.webhooks_total_failures = 20; // > 2*5 = 10
        let report = evaluate(&input);
        let wh = report.components.iter().find(|c| c.name == "webhooks").unwrap();
        assert_eq!(wh.status, HealthStatus::Degraded);
        assert!(wh.message.as_ref().unwrap().contains("20 delivery failures"));
    }

    #[test]
    fn webhooks_healthy_with_low_failures() {
        let report = evaluate(&sample_input());
        let wh = report.components.iter().find(|c| c.name == "webhooks").unwrap();
        assert_eq!(wh.status, HealthStatus::Healthy);
    }

    #[test]
    fn audit_log_details() {
        let report = evaluate(&sample_input());
        let al = report.components.iter().find(|c| c.name == "audit_log").unwrap();
        assert_eq!(al.status, HealthStatus::Healthy);
        let d = al.details.as_ref().unwrap();
        assert_eq!(d["buffered_entries"], 100);
        assert_eq!(d["total_recorded"], 150);
    }
}