Skip to main content

lean_ctx_cli/http_server/
kernel_api.rs

1// SPDX-License-Identifier: Apache-2.0
2//! HTTP handlers exposing Context Kernel runtime state.
3
4use axum::{Json, http::StatusCode};
5use serde::{Deserialize, Serialize};
6
7use lean_ctx::core::context_kernel::{
8    envelope_wiring, kernel_config, live_dashboard, mcp_bridge, proxy_bridge,
9};
10
11/// Point-in-time ETPAO values for the proxy and MCP hot paths.
12#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
13pub struct EtpaoResponse {
14    /// Current proxy effective tokens per accepted outcome.
15    pub proxy_etpao: f64,
16    /// Current MCP effective tokens per accepted outcome.
17    pub mcp_etpao: f64,
18    /// Arithmetic mean of the proxy and MCP ETPAO values.
19    pub combined_etpao: f64,
20}
21
22/// Returns the live Context Kernel dashboard snapshot.
23#[allow(clippy::unused_async)]
24pub async fn dashboard() -> Json<serde_json::Value> {
25    let snapshot = live_dashboard::snapshot_json();
26    let report = lean_ctx::core::context_kernel::dashboard_report::generate_report();
27    let mut base = serde_json::from_str::<serde_json::Value>(&snapshot)
28        .unwrap_or_else(|_| serde_json::json!({}));
29    if let (Some(obj), Ok(report_val)) = (base.as_object_mut(), serde_json::to_value(&report)) {
30        obj.insert("report".to_string(), report_val);
31    }
32    Json(base)
33}
34
35/// Returns current ETPAO values for both active integration paths.
36#[allow(clippy::unused_async)]
37pub async fn etpao() -> Json<EtpaoResponse> {
38    let proxy_etpao = proxy_bridge::current_etpao();
39    let mcp_etpao = mcp_bridge::mcp_etpao();
40    Json(EtpaoResponse {
41        proxy_etpao,
42        mcp_etpao,
43        combined_etpao: f64::midpoint(proxy_etpao, mcp_etpao),
44    })
45}
46
47/// Returns the current Context Kernel runtime feature configuration.
48#[allow(clippy::unused_async)]
49pub async fn get_config() -> Json<serde_json::Value> {
50    Json(
51        serde_json::to_value(kernel_config::features()).unwrap_or_else(|error| {
52            serde_json::json!({
53                "error": "invalid kernel configuration",
54                "detail": error.to_string(),
55            })
56        }),
57    )
58}
59
60/// Replaces the Context Kernel runtime feature configuration.
61#[allow(clippy::unused_async)]
62pub async fn set_config(
63    Json(body): Json<serde_json::Value>,
64) -> Result<Json<serde_json::Value>, StatusCode> {
65    let features = serde_json::from_value(body).map_err(|_| StatusCode::BAD_REQUEST)?;
66    kernel_config::update_features(features);
67    Ok(get_config().await)
68}
69
70/// Returns aggregate evidence from the active Context Kernel pipeline.
71#[allow(clippy::unused_async)]
72pub async fn evidence() -> Json<serde_json::Value> {
73    Json(
74        serde_json::to_value(envelope_wiring::evidence_summary()).unwrap_or_else(|error| {
75            serde_json::json!({
76                "error": "invalid kernel evidence",
77                "detail": error.to_string(),
78            })
79        }),
80    )
81}
82
83/// Clears live kernel evidence and ETPAO state.
84#[allow(clippy::unused_async)]
85pub async fn reset_state() -> Json<&'static str> {
86    envelope_wiring::reset_evidence();
87    proxy_bridge::reset_state();
88    mcp_bridge::reset_mcp_state();
89    Json("ok")
90}
91
92/// Returns the aggregated Context Kernel health report.
93#[allow(clippy::unused_async)]
94pub async fn health() -> Json<serde_json::Value> {
95    let json_str = lean_ctx::core::context_kernel::health_api::health_json();
96    Json(serde_json::from_str(&json_str).unwrap_or_else(|error| {
97        serde_json::json!({
98            "error": "invalid health snapshot",
99            "detail": error.to_string(),
100        })
101    }))
102}
103
104/// Returns a structured kernel dashboard report.
105#[allow(clippy::unused_async)]
106pub async fn report() -> Json<serde_json::Value> {
107    let r = lean_ctx::core::context_kernel::dashboard_report::generate_report();
108    Json(serde_json::to_value(&r).unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() })))
109}
110
111#[cfg(test)]
112mod tests {
113    use axum::{body::to_bytes, response::IntoResponse};
114
115    use super::*;
116
117    async fn response_json(response: impl IntoResponse) -> serde_json::Value {
118        let response = response.into_response();
119        let bytes = to_bytes(response.into_body(), 1_000_000)
120            .await
121            .expect("response body should be readable");
122        serde_json::from_slice(&bytes).expect("response body should contain JSON")
123    }
124
125    #[tokio::test]
126    async fn dashboard_returns_valid_json() {
127        let value = response_json(dashboard().await).await;
128        assert!(value.is_object());
129    }
130
131    #[tokio::test]
132    async fn etpao_returns_numbers() {
133        let value = response_json(etpao().await).await;
134        assert!(value["proxy_etpao"].is_f64());
135        assert!(value["mcp_etpao"].is_f64());
136        assert!(value["combined_etpao"].is_f64());
137    }
138
139    #[tokio::test]
140    #[allow(clippy::await_holding_lock)]
141    async fn config_roundtrip() {
142        let _guard = kernel_config::KERNEL_TEST_LOCK
143            .lock()
144            .unwrap_or_else(std::sync::PoisonError::into_inner);
145        let original = response_json(get_config().await).await;
146        let mut modified = original.clone();
147        modified["content_dedup"] = serde_json::Value::Bool(
148            !original["content_dedup"]
149                .as_bool()
150                .expect("content_dedup should be boolean"),
151        );
152
153        let response = set_config(Json(modified.clone()))
154            .await
155            .expect("valid configuration should be accepted");
156        assert_eq!(response_json(response).await, modified);
157        assert_eq!(response_json(get_config().await).await, modified);
158
159        let _ = set_config(Json(original))
160            .await
161            .expect("original configuration should be restored");
162    }
163
164    #[tokio::test]
165    async fn evidence_returns_summary() {
166        let value = response_json(evidence().await).await;
167        for field in [
168            "proxy_requests",
169            "mcp_calls",
170            "total_envelopes",
171            "chain_entries",
172            "compression_ratio",
173            "kernel_hit_rate",
174        ] {
175            assert!(value.get(field).is_some(), "missing field: {field}");
176        }
177    }
178}