coreason-runtime 0.1.0

Kinetic Plane execution engine for the CoReason Tripartite Cybernetic Manifold
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
// Copyright (c) 2026 CoReason, Inc.
// All rights reserved.

#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_variables)]
#![allow(unused_assignments)]
#![allow(clippy::type_complexity)]
#![allow(clippy::new_without_default)]
#![allow(clippy::unnecessary_map_or)]
#![allow(clippy::needless_return)]

mod api;

use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        Path, Query, State,
    },
    http::{header, HeaderValue, Method, StatusCode},
    response::{
        sse::{Event, KeepAlive, Sse},
        IntoResponse, Response,
    },
    routing::{get, post},
    Json, Router,
};
use chrono::Utc;
use clap::Parser;
use dashmap::DashMap;
use futures_util::{sink::SinkExt, stream, stream::StreamExt};
use rand::Rng;
use serde::{Deserialize, Serialize};
use sha2::Digest;
use std::{net::SocketAddr, sync::Arc, time::Duration};
use tokio::sync::broadcast;
use tower_http::cors::CorsLayer;

#[derive(Parser, Debug)]
#[command(
    name = "coreason",
    version = "0.1.0",
    about = "CoReason Zero-Trust Kinetic Execution Engine"
)]
struct Cli {
    #[clap(subcommand)]
    command: Commands,
}

#[derive(clap::Subcommand, Debug)]
enum Commands {
    Start {
        #[clap(subcommand)]
        action: StartCommands,
    },
    Execute {
        #[arg(help = "Path to a local JSON manifest to parse and dispatch")]
        manifest_path: std::path::PathBuf,
        #[arg(
            short,
            long,
            help = "Inject a dynamic user query into the root agent node"
        )]
        query: Option<String>,
        #[arg(long, help = "Parses structural inputs without hooking telemetry")]
        dry_run: bool,
    },
    Compute {
        #[arg(help = "The target execution plane module/function to run")]
        module: String,
        #[arg(help = "JSON payload containing input parameters")]
        payload: String,
    },
}

#[derive(clap::Subcommand, Debug)]
enum StartCommands {
    Api {
        #[arg(short, long, default_value_t = 8080)]
        port: u16,
        #[arg(long, default_value = "http://127.0.0.1:8000")]
        python_sidecar: String,
    },
    Node {
        #[arg(long, help = "Parses structural inputs without hooking telemetry")]
        dry_run: bool,
    },
}

type RoomName = String;
type ClientTx = broadcast::Sender<Message>;

struct GatewayState {
    rooms: DashMap<RoomName, ClientTx>,
    sidecar_url: String,
    speculative_metrics: tokio::sync::Mutex<Vec<serde_json::Value>>,
    active_inference_metrics: tokio::sync::Mutex<Vec<serde_json::Value>>,
}

#[derive(Serialize, Deserialize, Debug)]
struct TelemetryPayload {
    node_cid: String,
    metric_name: String,
    metric_value: f64,
    timestamp_ns: u64,
}

#[derive(Serialize, Deserialize, Debug)]
struct ActuatorPayload {
    plugin_path: String,
    input_data: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct GenericResponse {
    status: String,
    message: String,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct CapabilityExecutePayload {
    tool_name: String,
    intent: serde_json::Value,
    state: serde_json::Value,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct SpeculativeMetricPayload {
    draft_tokens: Option<u64>,
    accepted_tokens: Option<u64>,
    valid_at_1: Option<bool>,
    draft_model_latency_ms: Option<f64>,
    target_model_latency_ms: Option<f64>,
    batch_size: Option<u64>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct ActiveInferenceMetricPayload {
    variational_free_energy: Option<f64>,
    expected_free_energy: Option<f64>,
    policy_coordinates: Option<Vec<f64>>,
    epistemic_value: Option<f64>,
    pragmatic_value: Option<f64>,
    agent_id: Option<String>,
}

#[derive(Deserialize)]
struct TelemetryQuery {
    intent: Option<String>,
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();
    match cli.command {
        Commands::Start { action } => match action {
            StartCommands::Api {
                port,
                python_sidecar,
            } => {
                println!("Initializing CoReason SOTA 2026 Rust/Axum Ingress Gateway...");
                println!("Listening on port: {}", port);
                println!(
                    "Proxying dynamic reasoning payloads to Python sidecar at: {}",
                    python_sidecar
                );

                let state = Arc::new(GatewayState {
                    rooms: DashMap::new(),
                    sidecar_url: python_sidecar,
                    speculative_metrics: tokio::sync::Mutex::new(Vec::new()),
                    active_inference_metrics: tokio::sync::Mutex::new(Vec::new()),
                });

                let cors = CorsLayer::new()
                    .allow_origin("*".parse::<HeaderValue>().unwrap())
                    .allow_methods([Method::GET, Method::POST])
                    .allow_headers([header::CONTENT_TYPE]);

                let app = Router::new()
                    // Core binary-level endpoints (stay in main.rs)
                    .route("/health", get(health_check))
                    .route("/telemetry", post(receive_telemetry))
                    .route("/actuator/execute", post(execute_actuator))
                    .route("/ws/:room_name", get(websocket_handler))
                    // All API domain routes from the api/ module tree
                    .merge(api::build_api_router())
                    .layer(cors)
                    .with_state(state);

                let addr = SocketAddr::from(([0, 0, 0, 0], port));
                let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
                axum::serve(listener, app).await.unwrap();
            }
            StartCommands::Node { dry_run } => {
                println!("Starting Temporal Worker node...");
                if dry_run {
                    println!("Dry run complete. Exiting.");
                    return;
                }
                println!("Connecting to Temporal cluster... (Mocked for Phase 1/2)");
                loop {
                    tokio::time::sleep(Duration::from_secs(3600)).await;
                }
            }
        },
        Commands::Execute {
            manifest_path,
            query,
            dry_run,
        } => {
            println!("Executing manifest at {:?}...", manifest_path);
            if dry_run {
                println!("Dry run complete. Exiting.");
                return;
            }
            let content = std::fs::read_to_string(&manifest_path).unwrap_or_else(|e| {
                eprintln!("Failed to read manifest file: {}", e);
                std::process::exit(1);
            });
            let manifest_json: serde_json::Value =
                serde_json::from_str(&content).unwrap_or_else(|e| {
                    eprintln!("Failed to parse manifest JSON: {}", e);
                    std::process::exit(1);
                });

            let sidecar_url = std::env::var("PYTHON_SIDECAR_URL")
                .unwrap_or_else(|_| "http://127.0.0.1:8080".to_string());
            let url = format!("{}/api/v1/state/execute", sidecar_url);
            let payload = serde_json::json!({
                "manifest": manifest_json,
                "query": query,
            });

            println!(
                "Dispatching manifest to execution engine sidecar at: {}",
                url
            );
            match ureq::post(&url).send_json(&payload) {
                Ok(res) => {
                    let body: serde_json::Value =
                        res.into_json().unwrap_or(serde_json::Value::Null);
                    println!("Manifest executed successfully: {:#?}", body);
                }
                Err(e) => {
                    eprintln!("Manifest execution failed: {}", e);
                    std::process::exit(1);
                }
            }
        }
        Commands::Compute { module, payload } => {
            let val: serde_json::Value = serde_json::from_str(&payload).unwrap_or_else(|e| {
                eprintln!("Invalid JSON payload: {}", e);
                std::process::exit(1);
            });

            match module.as_str() {
                "lmsr_prices" => {
                    let shares: Vec<f64> =
                        serde_json::from_value(val["shares"].clone()).unwrap_or_default();
                    let liquidity: f64 = val["liquidity"].as_f64().unwrap_or(100.0);
                    let mut market = coreason_runtime_rust::execution_plane::lmsr_consensus::LMSRMarketMaker::new(liquidity);
                    for (i, &s) in shares.iter().enumerate() {
                        let id = format!("outcome_{}", i);
                        let label = format!("Outcome {}", i);
                        market.outcomes.push(coreason_runtime_rust::execution_plane::lmsr_consensus::MarketOutcome::new(&id, &label));
                        market.outcomes[i].shares = s;
                    }
                    let prices: Vec<f64> = (0..shares.len()).map(|i| market.price(i)).collect();
                    println!("{}", serde_json::to_string(&prices).unwrap());
                }
                "consensus_score" => {
                    let agent_beliefs: std::collections::HashMap<String, Vec<f64>> =
                        serde_json::from_value(val["agent_beliefs"].clone()).unwrap_or_default();
                    let result = coreason_runtime_rust::execution_plane::lmsr_consensus::ConsensusMetrics::consensus_score(&agent_beliefs);
                    println!("{}", result);
                }
                "debate_round" => {
                    let agent_positions: std::collections::HashMap<String, Vec<f64>> =
                        serde_json::from_value(val["agent_positions"].clone()).unwrap_or_default();
                    let liquidity: f64 = val["liquidity"].as_f64().unwrap_or(100.0);
                    let mut round = coreason_runtime_rust::execution_plane::lmsr_consensus::DialecticDebateRound::new("cli_round", liquidity);
                    for (agent_id, position) in &agent_positions {
                        let confidence = position.first().copied().unwrap_or(0.5);
                        round.submit_argument(agent_id, "position", vec![], confidence);
                    }
                    let result = round.resolve_consensus();
                    println!("{}", result);
                }
                "compute_blast_radius" => {
                    let edges: Vec<(String, String)> =
                        serde_json::from_value(val["edges"].clone()).unwrap_or_default();
                    let target_node = val["target_node"].as_str().unwrap_or("").to_string();
                    let mut adjacency: std::collections::HashMap<String, Vec<String>> =
                        std::collections::HashMap::new();
                    for (parent, child) in &edges {
                        adjacency
                            .entry(parent.clone())
                            .or_default()
                            .push(child.clone());
                        adjacency.entry(child.clone()).or_default();
                    }
                    let result = coreason_runtime_rust::execution_plane::blast_radius::BlastRadiusCalculator::calculate_blast_radius(&target_node, &adjacency);
                    println!("{}", serde_json::to_string(&result).unwrap());
                }
                "compute_defeasibility_score" => {
                    let edges: Vec<(String, String)> =
                        serde_json::from_value(val["edges"].clone()).unwrap_or_default();
                    let target_node = val["target_node"].as_str().unwrap_or("").to_string();
                    let mut adjacency: std::collections::HashMap<String, Vec<String>> =
                        std::collections::HashMap::new();
                    for (parent, child) in &edges {
                        adjacency
                            .entry(parent.clone())
                            .or_default()
                            .push(child.clone());
                        adjacency.entry(child.clone()).or_default();
                    }
                    let score = coreason_runtime_rust::execution_plane::blast_radius::BlastRadiusCalculator::compute_defeasibility_score(&target_node, &adjacency);
                    println!("{}", score);
                }
                "worm_append" => {
                    let workflow_id = val["workflow_id"].as_str().unwrap_or("").to_string();
                    let delta = val["state_delta"].clone();
                    let ledger =
                        coreason_runtime_rust::execution_plane::worm_ledger::get_worm_ledger();
                    let mut guard = ledger.lock().unwrap();
                    let hash = guard.append(&workflow_id, &delta);
                    println!("{}", hash);
                }
                "worm_verify_chain" => {
                    let ledger =
                        coreason_runtime_rust::execution_plane::worm_ledger::get_worm_ledger();
                    let guard = ledger.lock().unwrap();
                    match guard.verify_chain() {
                        Ok(v) => println!("{}", v),
                        Err(e) => {
                            eprintln!("Verification failed: {}", e);
                            std::process::exit(2);
                        }
                    }
                }
                "worm_len" => {
                    let ledger =
                        coreason_runtime_rust::execution_plane::worm_ledger::get_worm_ledger();
                    let guard = ledger.lock().unwrap();
                    println!("{}", guard.len());
                }
                "worm_to_json" => {
                    let ledger =
                        coreason_runtime_rust::execution_plane::worm_ledger::get_worm_ledger();
                    let guard = ledger.lock().unwrap();
                    println!("{}", guard.to_json());
                }
                "verify_license" => {
                    let receipt_json = val["receipt_json"].as_str().unwrap_or("{}").to_string();
                    let public_key_hex = val["public_key_hex"].as_str().unwrap_or("").to_string();
                    let local_fingerprint =
                        val["local_fingerprint"].as_str().map(|s| s.to_string());
                    let receipt: coreason_runtime_rust::license::CommercialOverrideReceipt =
                        serde_json::from_str(&receipt_json).unwrap();
                    let verifier =
                        coreason_runtime_rust::license::LicenseVerifier::new(local_fingerprint);
                    let entitlements = verifier.verify_and_apply(&receipt, &public_key_hex);
                    println!("{}", serde_json::to_string(&entitlements).unwrap());
                }
                _ => {
                    eprintln!("Unknown compute module: {}", module);
                    std::process::exit(1);
                }
            }
        }
    }
}

async fn health_check() -> &'static str {
    "CoReason Ingress Gateway is healthy and running on Axum."
}

async fn receive_telemetry(Json(payload): Json<TelemetryPayload>) -> impl IntoResponse {
    println!(
        "[TELEMETRY] Node: {} | {} = {} | Time: {}ns",
        payload.node_cid, payload.metric_name, payload.metric_value, payload.timestamp_ns
    );
    (
        StatusCode::ACCEPTED,
        Json(GenericResponse {
            status: "success".to_string(),
            message: "Telemetry packet queued successfully.".to_string(),
        }),
    )
}

async fn execute_actuator(Json(payload): Json<ActuatorPayload>) -> Response {
    println!(
        "[ACTUATOR] Attempting execution of sandboxed WASM plugin: {}",
        payload.plugin_path
    );

    match coreason_runtime_rust::wasm_dispatcher::WasmDispatcher::execute_plugin(
        &payload.plugin_path,
        "run_actuator",
        &payload.input_data,
    ) {
        Ok(output) => (
            StatusCode::OK,
            Json(GenericResponse {
                status: "success".to_string(),
                message: output,
            }),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(GenericResponse {
                status: "error".to_string(),
                message: e,
            }),
        )
            .into_response(),
    }
}

async fn get_capabilities() -> Response {
    // DEPRECATED: This handler is now served by api::capabilities::router().
    // Keeping a stub to avoid breaking the binary build during migration.
    // TODO: Remove this once main.rs router no longer references it.
    Json(serde_json::json!(["redirected_to_api_module"])).into_response()
}

// ─── All other API routes are served by api::build_api_router() ───────
// See src/api/ module tree for: capabilities, state, telemetry, oracle,
// predict, auth, dlp, discovery, history, profile, semantic_space,
// shocks, temporal, and schema routers.

async fn websocket_handler(
    ws: WebSocketUpgrade,
    Path(room_name): Path<String>,
    State(state): State<Arc<GatewayState>>,
) -> impl IntoResponse {
    ws.on_upgrade(move |socket| handle_socket_stream(socket, room_name, state))
}

async fn handle_socket_stream(socket: WebSocket, room_name: String, state: Arc<GatewayState>) {
    let (mut sender, mut receiver) = socket.split();

    let rx = state
        .rooms
        .entry(room_name.clone())
        .or_insert_with(|| {
            let (tx, _rx) = broadcast::channel(128);
            tx
        })
        .value()
        .clone();

    let mut broadcast_rx = rx.subscribe();
    let tx_clone = rx.clone();

    let mut write_task = tokio::spawn(async move {
        while let Ok(msg) = broadcast_rx.recv().await {
            if sender.send(msg).await.is_err() {
                break;
            }
        }
    });

    let mut read_task = tokio::spawn(async move {
        while let Some(Ok(msg)) = receiver.next().await {
            match msg {
                Message::Text(_) | Message::Binary(_) => {
                    let _ = tx_clone.send(msg);
                }
                Message::Close(_) => {
                    break;
                }
                _ => {}
            }
        }
    });

    tokio::select! {
        _ = (&mut read_task) => {
            write_task.abort();
        }
        _ = (&mut write_task) => {
            read_task.abort();
        }
    }

    if let Some(entry) = state.rooms.get_mut(&room_name) {
        if entry.receiver_count() == 0 {
            drop(entry);
            state.rooms.remove(&room_name);
        }
    }
}