Skip to main content

qualia_core_db/services/
daemon.rs

1#![cfg(not(target_arch = "wasm32"))]
2
3#[cfg(feature = "libp2p-compat")]
4use futures_util::StreamExt;
5use serde_json::json;
6use tokio::sync::mpsc;
7
8const CELL_MEMORY_FLOOR_MB: u16 = 512;
9
10/// Fractal-sharding topology configured at daemon boot (`qualia-cli daemon --workers N`).
11#[derive(Clone, Copy, Debug, Default, serde::Serialize)]
12pub struct DaemonTopology {
13    pub worker_cells_configured: u16,
14    pub compute_swarm_enabled: bool,
15}
16
17static DAEMON_TOPOLOGY: std::sync::OnceLock<DaemonTopology> = std::sync::OnceLock::new();
18
19/// Called by `qualia-cli daemon` before the HTTP server starts.
20pub fn configure_daemon_topology(topology: DaemonTopology) {
21    let _ = DAEMON_TOPOLOGY.set(topology);
22}
23
24fn current_topology() -> DaemonTopology {
25    *DAEMON_TOPOLOGY.get().unwrap_or(&DaemonTopology {
26        worker_cells_configured: 1,
27        compute_swarm_enabled: false,
28    })
29}
30
31/// JSON block shared by `/health`, benchmark exports, and the comparative harness.
32pub fn execution_environment_json() -> serde_json::Value {
33    let topo = current_topology();
34    let mode = if topo.worker_cells_configured > 1 || topo.compute_swarm_enabled {
35        "fractal_swarm"
36    } else {
37        "single_cell"
38    };
39    json!({
40        "runner": "qualia-core-db daemon",
41        "engine_version": crate::ENGINE_VERSION,
42        "memory_ceiling_mb": CELL_MEMORY_FLOOR_MB,
43        "measurement_path": "daemon_http_query",
44        "topology": {
45            "mode": mode,
46            "worker_cells_configured": topo.worker_cells_configured,
47            "worker_cells_active_during_run": topo.worker_cells_configured,
48            "compute_swarm_enabled": topo.compute_swarm_enabled,
49            "cell_memory_floor_mb": CELL_MEMORY_FLOOR_MB,
50            "scheduling": "fixed-pool"
51        }
52    })
53}
54
55#[derive(Clone)]
56struct DaemonSecurity {
57    dev: bool,
58    token: Option<String>,
59    vault: std::sync::Arc<std::sync::Mutex<crate::key_vault::KeyVault>>,
60}
61
62/// Starts the native loopback daemon on 127.0.0.1 with strict token checks.
63pub async fn start_local_daemon(
64    port: u16,
65    vault: std::sync::Arc<std::sync::Mutex<crate::key_vault::KeyVault>>,
66) {
67    start_local_daemon_with_options(port, false, vault, false).await;
68}
69
70/// Starts the native loopback daemon with WebSocket and REST handoff routes.
71pub async fn start_local_daemon_with_options(
72    port: u16,
73    dev: bool,
74    vault: std::sync::Arc<std::sync::Mutex<crate::key_vault::KeyVault>>,
75    empty_graph: bool,
76) -> mpsc::Sender<String> {
77    let storage_path = std::env::var("QUALIA_STORAGE_PATH").unwrap_or_else(|_| {
78        std::env::var("HOME")
79            .or_else(|_| std::env::var("USERPROFILE"))
80            .map(|h| format!("{h}/.qualia"))
81            .unwrap_or_else(|_| ".qualia".to_string())
82    });
83
84    // Create Isolated Paths for Ontological Path Isolation.
85    // `selfhood` = the guarded store of the records that *pertain to* the self (mind + secrets — the
86    // dignity foundation). The self is NOT in the machine and is never captured; this store is a
87    // *selfhood guardian* holding those records on the principal's (the natural person's) behalf, in a
88    // principal→agent relationship, later linked with rights (the outward personhood layer). An identifier
89    // or record is *about* the person, never *is* the person. Migrate the legacy `sovereign` store name
90    // if an existing install still carries it (one-time, non-destructive: only when the new name is absent).
91    let selfhood_path = std::path::Path::new(&storage_path).join("selfhood");
92    let legacy_selfhood_path = std::path::Path::new(&storage_path).join("sovereign");
93    if legacy_selfhood_path.exists() && !selfhood_path.exists() {
94        if let Err(e) = std::fs::rename(&legacy_selfhood_path, &selfhood_path) {
95            eprintln!(
96                "[Qualia Daemon] WARN: failed to migrate legacy 'sovereign' store to 'selfhood': {}",
97                e
98            );
99        }
100    }
101    let commons_path = std::path::Path::new(&storage_path).join("commons");
102    if let Err(e) = std::fs::create_dir_all(&selfhood_path) {
103        eprintln!(
104            "[Qualia Daemon] FATAL: Failed to create selfhood storage path: {}",
105            e
106        );
107        std::process::exit(1); // Graceful fail on volume disconnect
108    }
109    if let Err(e) = std::fs::create_dir_all(&commons_path) {
110        eprintln!(
111            "[Qualia Daemon] FATAL: Failed to create commons storage path: {}",
112            e
113        );
114        std::process::exit(1);
115    }
116    let graph_opts = if empty_graph {
117        crate::daemon_graph::InitGraphOptions {
118            seed_defaults: false,
119            load_index: false,
120        }
121    } else {
122        crate::daemon_graph::InitGraphOptions::default()
123    };
124    crate::daemon_graph::init_daemon_graph_with_options(&storage_path, graph_opts);
125    if !empty_graph {
126        crate::ontology_loader::load_startup_ontologies();
127    }
128
129    let security = DaemonSecurity {
130        dev,
131        token: std::env::var("QUALIA_TOKEN")
132            .ok()
133            .or_else(|| std::env::var("QUALIA_DEV_TOKEN").ok()),
134        vault,
135    };
136
137    // -----------------------------------------------------------------------
138    // WebSocket bridge — handshake + query metrics + bench_load
139    // -----------------------------------------------------------------------
140
141    let (control_tx, mut control_rx) = mpsc::channel::<String>(16);
142
143    let state = crate::webizen_server::spawn_loopback_server(
144        port,
145        security.dev,
146        security.vault.clone(),
147        security.token,
148    );
149
150    // Wire up control channel
151    let state_clone = state.clone();
152    tokio::spawn(async move {
153        while let Some(cmd) = control_rx.recv().await {
154            if cmd == "REVOKE" {
155                // broadcast revocation over the unified telemetry channel
156                let _ = state_clone.telemetry_tx.send(b"REVOKE".to_vec());
157            }
158        }
159    });
160
161    println!("============================================================");
162    println!("Qualia-DB Unified Axum Daemon Booting");
163    println!("Listening on 127.0.0.1:{}", port);
164    println!(
165        "  Mode:      {}",
166        if security.dev {
167            "dev bypass"
168        } else {
169            "token required"
170        }
171    );
172    println!("============================================================");
173
174    tokio::spawn(async move {
175        let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(60));
176        loop {
177            interval.tick().await;
178            println!(
179                "[Informatics Subsystem] Running N3Logic differential diagnostics over .q42 graph..."
180            );
181        }
182    });
183
184    tokio::spawn(async {
185        println!("[Qualia Daemon] Nym Mixnet: Sphinx Packet routing initialized.");
186        loop {
187            tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
188        }
189    });
190
191    tokio::spawn(async {
192        println!("[Qualia Daemon] Gun.eco: WebSocket Graph bridge initialized.");
193        loop {
194            tokio::time::sleep(tokio::time::Duration::from_secs(45)).await;
195        }
196    });
197
198    pub struct PeerLedger {
199        pub unbilled_bytes: usize,
200        pub warning_issued_at: Option<std::time::Instant>,
201    }
202    let bandwidth_meter = std::sync::Arc::new(dashmap::DashMap::<String, PeerLedger>::new());
203    #[cfg(feature = "libp2p-compat")]
204    let bandwidth_meter_swarm = bandwidth_meter.clone();
205
206    // -----------------------------------------------------------------------
207    // P2P Network Swarm (CBOR-LD Semantic Sync)
208    // Inherited libp2p path. Native Independent operation uses QDNF instead.
209    // -----------------------------------------------------------------------
210    #[cfg(feature = "libp2p-compat")]
211    let p2p_vault = security.vault.clone();
212    #[cfg(feature = "libp2p-compat")]
213    tokio::spawn(async move {
214        let master_key_bytes = {
215            let v = p2p_vault.lock().unwrap();
216            v.get_master_key_bytes()
217        };
218
219        let mut ed25519_bytes = master_key_bytes;
220        let local_key = libp2p::identity::Keypair::ed25519_from_bytes(&mut ed25519_bytes)
221            .expect("Valid Ed25519 Key Vault Master Key");
222
223        let local_peer_id = libp2p::PeerId::from(local_key.public());
224        println!(
225            "[Qualia Daemon] P2P Identity Active. PeerId: {}",
226            local_peer_id
227        );
228
229        let behaviour = crate::p2p::swarm::build_behaviour(local_peer_id);
230
231        let routing_table = std::sync::Arc::new(crate::p2p::routing::CivicsRoutingTable::new());
232        let local_db_slice: &[crate::NQuin] = &[]; // Mock of memory mapped DB slice
233        routing_table.hydrate_from_db(local_db_slice);
234
235        let mut swarm = libp2p::SwarmBuilder::with_existing_identity(local_key)
236            .with_tokio()
237            .with_tcp(
238                libp2p::tcp::Config::default(),
239                libp2p::noise::Config::new,
240                libp2p::yamux::Config::default,
241            )
242            .unwrap()
243            .with_behaviour(|_| behaviour)
244            .unwrap()
245            .with_swarm_config(|c| {
246                c.with_idle_connection_timeout(std::time::Duration::from_secs(60))
247            })
248            .build();
249
250        // Bind to all IPv6 interfaces
251        swarm
252            .listen_on("/ip6/::/tcp/4243".parse().unwrap())
253            .expect("P2P Swarm Socket bind failed");
254
255        loop {
256            tokio::select! {
257                event = swarm.select_next_some() => match event {
258                    libp2p::swarm::SwarmEvent::NewListenAddr { address, .. } => {
259                        println!("[Qualia Daemon] P2P Node Listening on {}", address);
260                    }
261                    libp2p::swarm::SwarmEvent::Behaviour(crate::p2p::swarm::QualiaBehaviourEvent::RequestResponse(
262                        libp2p::request_response::Event::Message { peer, message, .. }
263                    )) => {
264                        match message {
265                            libp2p::request_response::Message::Request { request, channel, .. } => {
266                                match request {
267                                    crate::p2p::protocol::QualiaRequest::Handshake { credentials, .. } => {
268                                        let mut route_authorized = false;
269                                        let vcs_count = credentials.len() / 112;
270
271                                        for i in 0..vcs_count {
272                                            let offset = i * 112;
273                                            if credentials.len() < offset + 112 { break; }
274
275                                            // Zero-allocation cast for the 48-byte Quin
276                                            let quin_bytes = &credentials[offset..offset+48];
277                                            let quin: &crate::p2p::protocol::NQuin = unsafe {
278                                                &*(quin_bytes.as_ptr() as *const crate::p2p::protocol::NQuin)
279                                            };
280
281                                            let signature_bytes: &[u8; 64] = credentials[offset+48..offset+112].try_into().unwrap();
282
283                                            // Mock ORG_MEMBER_HASH for demonstration
284                                            let org_member_hash = [1u8, 2, 3, 4, 5, 6, 7, 8];
285
286                                            if quin.predicate == org_member_hash {
287                                                if routing_table.is_authorized(&quin.object, quin_bytes, signature_bytes) {
288                                                    route_authorized = true;
289                                                    break; // Instant approval
290                                                }
291                                            }
292                                        }
293
294                                        if !route_authorized {
295                                            println!("[Qualia Daemon] Dropping Handshake from {}: Unauthorized Group DID.", peer);
296                                            let _ = swarm.behaviour_mut().request_response.send_response(
297                                                channel,
298                                                crate::p2p::protocol::QualiaResponse::HandshakeAck { context: "https://webizen.org/ld/context/v1".to_string(), response_type: "HandshakeAck".to_string(), success: false, did_q42: 0, semantic_context: 0 }
299                                            );
300                                            let _ = swarm.disconnect_peer_id(peer);
301                                        } else {
302                                            println!("[Qualia Daemon] Handshake approved for {}. Upgrading trust.", peer);
303                                            let _ = swarm.behaviour_mut().request_response.send_response(
304                                                channel,
305                                                crate::p2p::protocol::QualiaResponse::HandshakeAck { context: "https://webizen.org/ld/context/v1".to_string(), response_type: "HandshakeAck".to_string(), success: true, did_q42: 0, semantic_context: 0 }
306                                            );
307                                        }
308                                    },
309                                    crate::p2p::protocol::QualiaRequest::Sync { hop_count, gatekeeper_token, target_shapes, .. } => {
310                                        let mut is_authorized = false;
311
312                                        // Strict 2-Hop Limit for the Web Civics Mesh
313                                        if hop_count > 2 {
314                                            println!("[Qualia Daemon] Dropping Sync from {}: Exceeded 2-hop trust horizon.", peer);
315                                        } else {
316                                            if gatekeeper_token.is_some() {
317                                                is_authorized = true;
318                                            } else {
319                                                if target_shapes.contains(&"foaf:Person".to_string()) {
320                                                    is_authorized = true;
321                                                }
322                                            }
323                                        }
324
325                                        let response = if is_authorized {
326                                            crate::p2p::protocol::QualiaResponse::SyncAck { context: "https://webizen.org/ld/context/v1".to_string(), response_type: "SyncAck".to_string(), did_q42: 0, routing_constraints: 0,
327                                                success: true,
328                                                message: "Sync Approved".to_string(),
329                                                blocks_sent: 42,
330                                            }
331                                        } else {
332                                            crate::p2p::protocol::QualiaResponse::SyncAck { context: "https://webizen.org/ld/context/v1".to_string(), response_type: "SyncAck".to_string(), did_q42: 0, routing_constraints: 0,
333                                                success: false,
334                                                message: "RequiresGatekeeperChallenge".to_string(),
335                                                blocks_sent: 0,
336                                            }
337                                        };
338                                        let _ = swarm.behaviour_mut().request_response.send_response(channel, response);
339                                    }
340                                }
341                            },
342                            libp2p::request_response::Message::Response { response, .. } => {
343                                match response {
344                                    crate::p2p::protocol::QualiaResponse::HandshakeAck { success, .. } => {
345                                        println!("[Qualia Daemon] Received Handshake Ack from {}: success={}", peer, success);
346                                    },
347                                    crate::p2p::protocol::QualiaResponse::SyncAck { success, blocks_sent, .. } => {
348                                        println!("[Qualia Daemon] Received Sync Ack from {}: success={}, blocks={}", peer, success, blocks_sent);
349                                        if success && blocks_sent > 0 {
350                                            let mut buf = Vec::new();
351                                            let overhead = if ciborium::into_writer(&response, &mut buf).is_ok() { buf.len() } else { 0 };
352                                            // Actual serialized payload: CBOR overhead + (blocks_sent * 48 bytes per NQuin)
353                                            let bytes_transferred = overhead + (blocks_sent as usize * 48);
354                                            let peer_str = peer.to_string();
355                                            bandwidth_meter_swarm.entry(peer_str)
356                                                .and_modify(|ledger| ledger.unbilled_bytes += bytes_transferred)
357                                                .or_insert(PeerLedger {
358                                                    unbilled_bytes: bytes_transferred,
359                                                    warning_issued_at: None,
360                                                });
361                                        }
362                                    }
363                                }
364                            }
365                        }
366                    }
367                    _ => {}
368                }
369            }
370        }
371    });
372
373    #[cfg(not(feature = "libp2p-compat"))]
374    println!(
375        "[Qualia Daemon] Native Qualia Peer Runtime active (libp2p absent). QLink/QSR/QSession replace Swarm/Kademlia/Yamux."
376    );
377
378    // -----------------------------------------------------------------------
379    // Web Civics SOCKS5 Userspace Proxy
380    // -----------------------------------------------------------------------
381    tokio::spawn(async move {
382        let listener = tokio::net::TcpListener::bind("127.0.0.1:1080")
383            .await
384            .expect("Failed to bind SOCKS5 proxy");
385        println!("[Web Civics] Userspace WireGuard Proxy Listening on 127.0.0.1:1080");
386
387        loop {
388            if let Ok((_socket, _addr)) = listener.accept().await {
389                tokio::task::yield_now().await;
390            }
391        }
392    });
393
394    // -----------------------------------------------------------------------
395    // Semantic Task Engine (Economics & Scientific Compute)
396    // -----------------------------------------------------------------------
397    tokio::spawn(async move {
398        println!("[Semantic Task Engine] Watching graph for Distributed Compute Tasks...");
399        let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(5));
400        loop {
401            interval.tick().await;
402
403            // In a real implementation, we would query the CRDT graph here:
404            // SELECT ?task WHERE { ?task rdf:type qualia:MonteCarloSimulation . ?task status "Pending" }
405
406            // Mocking a detected task for the walkthrough:
407            let task_detected = false; // Set to true to test
408            if task_detected {
409                println!("[Semantic Task Engine] Detected MonteCarloSimulation Task.");
410                let (mean, var) = crate::domains::financial::economics::run_monte_carlo_var(
411                    100.0, 0.05, 0.20, 1.0, 252, 100_000,
412                );
413                println!(
414                    "[Semantic Task Engine] Simulation Complete. Mean: {:.2}, 95% VaR: {:.2}",
415                    mean, var
416                );
417                // We would then write the result back into the graph as a qualia:SimulationResult
418            }
419        }
420    });
421
422    // -----------------------------------------------------------------------
423    // Micropayment Settlement Engine (Soft/Hard Limits & Grace Period)
424    // -----------------------------------------------------------------------
425    let payment_meter = bandwidth_meter.clone();
426    tokio::spawn(async move {
427        println!("[Micropayment Engine] Initialized. Monitoring mesh bandwidth routing...");
428        let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(60));
429        loop {
430            interval.tick().await;
431
432            let context = crate::domains::financial::economics::get_current_system_context();
433
434            // Iterate over the DashMap without blocking the main router
435            for mut entry in payment_meter.iter_mut() {
436                let peer_id = entry.key().clone();
437                let ledger = entry.value_mut();
438
439                let liability = crate::domains::financial::economics::calculate_bandwidth_liability(
440                    ledger.unbilled_bytes,
441                    &context,
442                );
443
444                if liability >= 0.015 {
445                    // HARD LIMIT
446                    println!(
447                        "[Micropayment Engine] {} hit Hard Limit (${:.4}). Disconnecting.",
448                        peer_id, liability
449                    );
450                    // Disconnect peer immediately
451                    // network::disconnect_and_block(&peer_id);
452                    ledger.unbilled_bytes = 0;
453                    ledger.warning_issued_at = None;
454                } else if liability >= 0.010 && ledger.warning_issued_at.is_none() {
455                    // SOFT LIMIT
456                    println!(
457                        "[Micropayment Engine] {} hit Soft Limit (${:.4}). Emitting DebtQuin. Grace Period started.",
458                        peer_id, liability
459                    );
460                    // 1. Emit DebtQuin to local graph
461                    // query_engine.insert_debt_quin(&peer_id, liability);
462
463                    // 2. Send warning over libp2p
464                    // network::send_payment_warning(&peer_id, liability);
465
466                    // 3. Start the grace period clock
467                    ledger.warning_issued_at = Some(std::time::Instant::now());
468                } else if let Some(issued_at) = ledger.warning_issued_at {
469                    if issued_at.elapsed() > std::time::Duration::from_secs(300) {
470                        // 5 Minute Grace Period
471                        println!(
472                            "[Micropayment Engine] {} Grace Period EXPIRED. Disconnecting.",
473                            peer_id
474                        );
475                        // Disconnect peer immediately
476                        // network::disconnect_and_block(&peer_id);
477                        ledger.unbilled_bytes = 0;
478                        ledger.warning_issued_at = None;
479                    }
480                }
481            }
482        }
483    });
484
485    control_tx
486}