Skip to main content

qualia_core_db/services/
daemon_swarm.rs

1//! The Swarm (Native 64-bit Daemon)
2//! Implements Fractal Sharding (512MB worker cells) and Dense Linear Algebra (SIMD tensor contractions).
3//! DNSSEC to SocialWebNet bootstrapping pipeline for zero-allocation decentralized networking.
4
5#[cfg(not(target_arch = "wasm32"))]
6pub mod swarm {
7    use crate::governance::coordination::compute_priority;
8    use crate::identifier::parse_did_q42;
9    #[cfg(not(target_arch = "wasm32"))]
10    use crate::q42_lexicon::{CborLdError, Q42CborLdParser, Q42Context};
11    #[cfg(not(target_arch = "wasm32"))]
12    use crate::q42_volume::Q42Volume;
13    use crate::NQuin;
14    use crate::QualiaSuperBlock;
15    use crossbeam_channel::{bounded, Receiver, Sender};
16    use std::collections::HashMap;
17
18    use std::net::IpAddr;
19    use std::process::Command;
20    use std::sync::{Arc, Mutex};
21    use std::thread;
22    use std::time::{SystemTime, UNIX_EPOCH};
23
24    /// Agent candidate evaluated during daemon swarm compute routing.
25    #[derive(Debug, Clone, PartialEq, Eq)]
26    pub struct AgentComputeCandidate {
27        pub agent_did_hash: u64,
28        pub windowed_faults: u32,
29        pub usury_event: bool,
30    }
31
32    impl AgentComputeCandidate {
33        /// Creates a default `?`.
34        pub const fn new(agent_did_hash: u64, windowed_faults: u32, usury_event: bool) -> Self {
35            Self {
36                agent_did_hash,
37                windowed_faults,
38                usury_event,
39            }
40        }
41
42        /// Dynamic Darwinian compute priority from recent faults and usury status.
43        #[inline]
44        pub fn priority(&self) -> u64 {
45            compute_priority(self.windowed_faults, self.usury_event)
46        }
47    }
48
49    /// Ring buffer capacity for SPSC lock-free communication between Isolates
50    const SPSC_BUFFER_CAPACITY: usize = 1024;
51
52    /// DNSSEC record types for CBOR-LD semantic payloads
53    const DNSSEC_TXT_RECORD: u16 = 16;
54    const DNSSEC_CERT_RECORD: u16 = 37;
55
56    /// WireGuard public key length (32 bytes)
57    const WG_PUBKEY_LEN: usize = 32;
58
59    /// CBOR-LD semantic payload maximum size (512 bytes for DNSSEC constraints)
60    const CBOR_LD_MAX_SIZE: usize = 512;
61
62    /// Default DNSSEC cache TTL in seconds (5 minutes)
63    const DNSSEC_CACHE_TTL_SECONDS: u64 = 300;
64
65    /// Default peer endpoint port when DNSSEC resolution cannot determine one
66    const DEFAULT_PEER_PORT: u16 = 51820;
67
68    #[cfg(target_arch = "x86_64")]
69    #[target_feature(enable = "avx2,fma")]
70    unsafe fn tensor_contraction_avx2_fma(
71        matrix_a: &[f32],
72        matrix_b: &[f32],
73        result: &mut [f32],
74        size: usize,
75    ) {
76        use core::arch::x86_64::*;
77
78        for i in 0..size {
79            for k in 0..size {
80                let a_ik = _mm256_broadcast_ss(&matrix_a[i * size + k]);
81                let mut j = 0;
82                while j + 8 <= size {
83                    let b_kj = _mm256_loadu_ps(matrix_b.as_ptr().add(k * size + j));
84                    let mut r_ij = _mm256_loadu_ps(result.as_ptr().add(i * size + j));
85                    r_ij = _mm256_fmadd_ps(a_ik, b_kj, r_ij);
86                    _mm256_storeu_ps(result.as_mut_ptr().add(i * size + j), r_ij);
87                    j += 8;
88                }
89                while j < size {
90                    result[i * size + j] += matrix_a[i * size + k] * matrix_b[k * size + j];
91                    j += 1;
92                }
93            }
94        }
95    }
96
97    /// Error type for daemon swarm DNSSEC bootstrap operations.
98    #[derive(Debug, Clone, PartialEq, Eq)]
99    pub enum DaemonError {
100        /// DNSSEC resolver has not been initialized on the worker cell
101        ResolverNotInitialized,
102        /// The `dig` command was unavailable or returned a failure
103        DigUnavailable,
104        /// DNSSEC lookup completed but no valid CBOR-LD payload was found
105        DnssecLookupFailed,
106        /// CBOR-LD payload could not be parsed into Quin pointers
107        CborLdParsingFailed,
108        /// The supplied domain was not parseable into an endpoint
109        InvalidDomain,
110        /// The requested peer id is unknown to the worker cell
111        PeerNotFound,
112    }
113
114    impl From<&'static str> for DaemonError {
115        fn from(msg: &'static str) -> Self {
116            match msg {
117                "DNSSEC resolver not initialized" => DaemonError::ResolverNotInitialized,
118                "DNSSEC lookup failed" | "DNSSEC query failed" => DaemonError::DigUnavailable,
119                "CBOR-LD payload not found in DNSSEC response" => DaemonError::DnssecLookupFailed,
120                "CBOR-LD payload too large" | "CBOR-LD parsing failed" => {
121                    DaemonError::CborLdParsingFailed
122                }
123                _ => DaemonError::DnssecLookupFailed,
124            }
125        }
126    }
127
128    /// A resolved peer endpoint with DNSSEC verification metadata.
129    #[derive(Debug, Clone, PartialEq, Eq)]
130    pub struct PeerEndpoint {
131        /// Resolved IP address of the peer
132        pub address: IpAddr,
133        /// Port the peer is reachable on
134        pub port: u16,
135        /// Whether the DNSSEC chain-of-trust validated the record
136        pub verified: bool,
137        /// UNIX timestamp (seconds) at which the endpoint was resolved
138        pub timestamp: u64,
139    }
140
141    /// A cached DNSSEC peer resolution result with a TTL.
142    #[derive(Debug, Clone)]
143    pub struct CachedPeer {
144        pub endpoint: PeerEndpoint,
145        pub cached_at: u64,
146        pub ttl_seconds: u64,
147    }
148
149    impl CachedPeer {
150        /// Returns `true` if the cached entry is still within its TTL window.
151        pub fn is_fresh(&self, now: u64) -> bool {
152            now.saturating_sub(self.cached_at) < self.ttl_seconds
153        }
154    }
155
156    /// Current UNIX timestamp in seconds (zero on overflow).
157    fn unix_now() -> u64 {
158        SystemTime::now()
159            .duration_since(UNIX_EPOCH)
160            .map(|d| d.as_secs())
161            .unwrap_or(0)
162    }
163
164    /// Deterministically map a domain name (plus an optional 64-bit salt) to an IPv4 address.
165    ///
166    /// Used as the offline fallback when `dig` is unavailable so that the same domain always
167    /// resolves to the same address within the RFC 1918 private range (10.x.x.x). A full
168    /// avalanche mixer is applied so any change in the domain or salt redistributes across all
169    /// output bits (no collision on the 24-bit address window for distinct inputs).
170    fn domain_to_ip(domain: &str, salt: u64) -> IpAddr {
171        // Splitmix-style finaliser: combines the domain hash with the salt and avalanches
172        // so every output bit depends on every input bit.
173        let mut h = crate::q_hash(domain).wrapping_add(salt);
174        h = h.wrapping_mul(0x9E3779B97F4A7C15);
175        h ^= h >> 32;
176        h = h.wrapping_mul(0x9E3779B97F4A7C15);
177        h ^= h >> 32;
178        IpAddr::V4(std::net::Ipv4Addr::new(
179            10,
180            ((h >> 40) & 0xff) as u8,
181            ((h >> 32) & 0xff) as u8,
182            ((h >> 24) & 0xff) as u8,
183        ))
184    }
185
186    /// Derive a peer port from a parsed semantic payload, falling back to the default.
187    fn port_from_payload(payload: &DnssecSemanticPayload) -> u16 {
188        let raw = payload.did_q42 ^ payload.routing_mask;
189        let port = (raw & 0xffff) as u16;
190        if port == 0 {
191            DEFAULT_PEER_PORT
192        } else {
193            port
194        }
195    }
196
197    /// DNSSEC CBOR-LD semantic payload structure
198    #[derive(Debug, Clone)]
199    pub struct DnssecSemanticPayload {
200        pub wireguard_pubkey: [u8; WG_PUBKEY_LEN],
201        pub did_q42: u64,
202        pub routing_mask: u64, // 5th Vector Metadata 64-bit hardware mask
203        pub semantic_handshake: String,
204        pub peer_capabilities: u16,
205        pub semantic_context: u64,
206    }
207
208    /// SocialWebNet peer configuration
209    #[derive(Debug, Clone)]
210    pub struct SocialWebNetPeer {
211        pub peer_id: u64,
212        pub endpoint: IpAddr,
213        pub port: u16,
214        pub pubkey: [u8; WG_PUBKEY_LEN],
215        pub allowed_ips: Vec<String>,
216        pub routing_mask: u64,
217    }
218
219    /// DNSSEC resolver for CBOR-LD semantic payloads
220    pub struct DnssecResolver {
221        pub trusted_anchors: HashMap<String, [u8; 32]>,
222        pub cache: HashMap<String, DnssecSemanticPayload>,
223        pub validation_enabled: bool,
224    }
225
226    /// SocialWebNet interface manager
227    pub struct SocialWebNetInterface {
228        pub interface_name: String,
229        pub local_port: u16,
230        pub active_peers: HashMap<u64, SocialWebNetPeer>,
231        pub routing_table: HashMap<String, u64>,
232    }
233
234    /// A 512MB structural floor bounded worker cell (Fractal Sharding).
235    /// Each cell runs isolated logic evaluation or physics engines.
236    pub struct WorkerCell {
237        pub cell_id: usize,
238        pub memory_boundary: usize, // Strictly 512MB
239        pub attached_blocks: Vec<QualiaSuperBlock>,
240        pub dnssec_resolver: Option<DnssecResolver>,
241        pub wireguard_interface: Option<SocialWebNetInterface>,
242        #[cfg(not(target_arch = "wasm32"))]
243        pub q42_context: Option<Arc<Q42Context>>,
244        #[cfg(not(target_arch = "wasm32"))]
245        pub cbor_ld_parser: Option<Arc<Q42CborLdParser>>,
246        /// DNSSEC peer-resolution cache keyed by domain (TTL-bounded)
247        pub dnssec_cache: HashMap<String, CachedPeer>,
248        /// Per-peer capabilities bitmask keyed by peer id string
249        pub peer_capabilities: HashMap<String, u64>,
250        /// Per-peer semantic context keyed by peer id string
251        pub semantic_contexts: HashMap<String, u64>,
252        /// Local permission policy for peer routing constraints
253        pub local_permission: crate::webizen_server::CompiledPermission,
254    }
255
256    impl WorkerCell {
257        /// Creates `?` with the given state.
258        pub fn new(cell_id: usize) -> Self {
259            Self {
260                cell_id,
261                memory_boundary: 512 * 1024 * 1024,
262                attached_blocks: Vec::new(),
263                dnssec_resolver: None,
264                wireguard_interface: None,
265                #[cfg(not(target_arch = "wasm32"))]
266                q42_context: None,
267                #[cfg(not(target_arch = "wasm32"))]
268                cbor_ld_parser: None,
269                dnssec_cache: HashMap::new(),
270                peer_capabilities: HashMap::new(),
271                semantic_contexts: HashMap::new(),
272                local_permission: crate::webizen_server::CompiledPermission {
273                    routing_mask: 0x01 << 61, // EnforcePermissiveCommons
274                    semantic_handshake: "qualia:handshake:v1".to_string(),
275                    is_permissive_commons: true,
276                },
277            }
278        }
279
280        /// Initialize DNSSEC resolver with trusted anchors
281        pub fn init_dnssec_resolver(&mut self, trusted_anchors: HashMap<String, [u8; 32]>) {
282            self.dnssec_resolver = Some(DnssecResolver {
283                trusted_anchors,
284                cache: HashMap::new(),
285                validation_enabled: true,
286            });
287        }
288
289        /// Initialize SocialWebNet interface
290        pub fn init_wireguard_interface(&mut self, interface_name: String, local_port: u16) {
291            self.wireguard_interface = Some(SocialWebNetInterface {
292                interface_name,
293                local_port,
294                active_peers: HashMap::new(),
295                routing_table: HashMap::new(),
296            });
297        }
298
299        /// Initialize Q42 lexicon for CBOR-LD semantic processing
300        #[cfg(not(target_arch = "wasm32"))]
301        pub fn init_q42_lexicon(&mut self, volume: &Q42Volume) -> Result<(), CborLdError> {
302            let context =
303                Arc::new(Q42Context::from_volume(volume).map_err(|_| CborLdError::InvalidOffset)?);
304            let parser = Arc::new(
305                Q42CborLdParser::from_volume(volume).map_err(|_| CborLdError::InvalidOffset)?,
306            );
307
308            self.q42_context = Some(context);
309            self.cbor_ld_parser = Some(parser);
310            Ok(())
311        }
312
313        /// Resolve CBOR-LD DNSSEC record for peer domain, returning the full semantic payload.
314        ///
315        /// This is the internal semantic-payload resolver used by the WireGuard bootstrap
316        /// pipeline. The public [`resolve_peer_dnssec`](Self::resolve_peer_dnssec) returns a
317        /// lightweight [`PeerEndpoint`] with TTL caching.
318        pub fn resolve_peer_dnssec_payload(
319            &mut self,
320            domain: &str,
321        ) -> Result<DnssecSemanticPayload, &'static str> {
322            // Ensure the resolver is initialised (fail fast with the canonical error).
323            if self.dnssec_resolver.is_none() {
324                return Err("DNSSEC resolver not initialized");
325            }
326
327            // Check cache first (short-lived immutable borrow)
328            if let Some(cached_payload) = self
329                .dnssec_resolver
330                .as_ref()
331                .and_then(|r| r.cache.get(domain))
332            {
333                return Ok(cached_payload.clone());
334            }
335
336            // Perform DNSSEC lookup (immutable borrow of self)
337            let cbor_ld_payload = self.perform_dnssec_lookup(domain)?;
338
339            // Parse CBOR-LD payload directly into Super-Quin structure (immutable borrow)
340            let semantic_payload = self.parse_cbor_ld_to_payload(&cbor_ld_payload)?;
341
342            // Cache the resolved semantic payload for subsequent lookups (fresh mutable borrow)
343            if let Some(ref mut resolver) = self.dnssec_resolver {
344                resolver
345                    .cache
346                    .insert(domain.to_string(), semantic_payload.clone());
347            }
348
349            Ok(semantic_payload)
350        }
351
352        fn dnssec_rrtype_name(rrtype: u16) -> Option<&'static str> {
353            match rrtype {
354                DNSSEC_TXT_RECORD => Some("TXT"),
355                DNSSEC_CERT_RECORD => Some("CERT"),
356                _ => None,
357            }
358        }
359
360        /// Perform DNSSEC lookup for CBOR-LD semantic payload (TXT, then CERT fallback).
361        fn perform_dnssec_lookup(&self, domain: &str) -> Result<Vec<u8>, &'static str> {
362            for rrtype in [DNSSEC_TXT_RECORD, DNSSEC_CERT_RECORD] {
363                if let Ok(cbor_bytes) = self.dig_dnssec_record(domain, rrtype) {
364                    return Ok(cbor_bytes);
365                }
366            }
367            Err("DNSSEC query failed")
368        }
369
370        fn dig_dnssec_record(&self, domain: &str, rrtype: u16) -> Result<Vec<u8>, &'static str> {
371            let rrtype_name = Self::dnssec_rrtype_name(rrtype).ok_or("DNSSEC query failed")?;
372            let qname = format!("_qualia._dnssec.{}", domain);
373
374            let output = Command::new("dig")
375                .args([
376                    "+dnssec",
377                    "+short",
378                    "+yaml",
379                    &format!("+rrtype={rrtype_name}"),
380                    qname.as_str(),
381                ])
382                .output()
383                .map_err(|_| "DNSSEC lookup failed")?;
384
385            if !output.status.success() {
386                return Err("DNSSEC query failed");
387            }
388
389            let response = String::from_utf8_lossy(&output.stdout);
390            let cbor_hex = self.extract_cbor_from_dnssec_response(&response, rrtype)?;
391            hex::decode(&cbor_hex).map_err(|_| "Invalid CBOR hex encoding")
392        }
393
394        /// Extract CBOR-LD payload from DNSSEC response for a validated record type.
395        fn extract_cbor_from_dnssec_response(
396            &self,
397            response: &str,
398            rrtype: u16,
399        ) -> Result<String, &'static str> {
400            let marker = match rrtype {
401                DNSSEC_TXT_RECORD => "cbor-ld:",
402                DNSSEC_CERT_RECORD => "cbor-cert:",
403                _ => return Err("CBOR-LD payload not found in DNSSEC response"),
404            };
405
406            for line in response.lines() {
407                if !line.contains(marker) {
408                    continue;
409                }
410                let parts: Vec<&str> = line.split(':').collect();
411                if parts.len() >= 2 {
412                    return Ok(parts[1].trim().to_string());
413                }
414            }
415            Err("CBOR-LD payload not found in DNSSEC response")
416        }
417
418        /// Parse CBOR-LD payload using Q42 lexicon (zero-allocation)
419        #[cfg(not(target_arch = "wasm32"))]
420        fn parse_cbor_ld_to_payload(
421            &self,
422            cbor_bytes: &[u8],
423        ) -> Result<DnssecSemanticPayload, &'static str> {
424            if cbor_bytes.len() > CBOR_LD_MAX_SIZE {
425                return Err("CBOR-LD payload too large");
426            }
427
428            // Use Q42 lexicon-based CBOR-LD parser if available
429            if let Some(ref parser) = self.cbor_ld_parser {
430                let semantic_payload = parser
431                    .parse_semantic_payload(cbor_bytes)
432                    .map_err(|_| "CBOR-LD parsing failed")?;
433
434                // Convert SemanticPayload to DnssecSemanticPayload
435                // Note: This is a simplified conversion - production code would need proper parsing
436                let wireguard_pubkey = match semantic_payload.wireguard_pubkey {
437                    Some(k) => {
438                        let mut key = [0u8; 32];
439                        if k.len() >= 32 {
440                            key.copy_from_slice(&k.as_bytes()[0..32]);
441                        }
442                        key
443                    }
444                    None => [0u8; 32],
445                };
446
447                let did_q42 = match semantic_payload.did_q42 {
448                    Some(d) => crate::q_hash(&d),
449                    None => 0,
450                };
451
452                let routing_mask = if !semantic_payload.routing_constraints.is_empty() {
453                    0x02 << 61 // Default to Bilateral
454                } else {
455                    0x01 << 61 // Default to Commons
456                };
457
458                return Ok(DnssecSemanticPayload {
459                    wireguard_pubkey,
460                    did_q42,
461                    routing_mask,
462                    semantic_handshake: "Semantic Cryptographic Proof Template".to_string(),
463                    peer_capabilities: 0, // populated via set_peer_capabilities()
464                    semantic_context: 0,  // populated via set_semantic_context()
465                });
466            }
467
468            // Fallback to legacy parsing method
469            self.parse_cbor_ld_to_quin_legacy(cbor_bytes)
470        }
471
472        /// Public CBOR-LD → Quin-pointer parser.
473        ///
474        /// Uses the Q42 lexicon-based CBOR-LD parser when available, deriving a vector of
475        /// 64-bit Quin pointers (one per 8-byte chunk of the parsed semantic payload). If
476        /// the parser is not initialised or the payload is invalid, an error is returned.
477        #[cfg(not(target_arch = "wasm32"))]
478        pub fn parse_cbor_ld_to_quin(&self, cbor_data: &[u8]) -> Result<Vec<u64>, DaemonError> {
479            if cbor_data.is_empty() {
480                return Err(DaemonError::CborLdParsingFailed);
481            }
482            if cbor_data.len() > CBOR_LD_MAX_SIZE {
483                return Err(DaemonError::CborLdParsingFailed);
484            }
485
486            let parser = self
487                .cbor_ld_parser
488                .as_ref()
489                .ok_or(DaemonError::CborLdParsingFailed)?;
490
491            let semantic_payload = parser
492                .parse_semantic_payload(cbor_data)
493                .map_err(|_| DaemonError::CborLdParsingFailed)?;
494
495            // Derive Quin pointers from the parsed semantic payload data: each 8-byte
496            // chunk becomes one little-endian u64 Quin pointer. A trailing partial chunk
497            // is zero-padded so no data is lost.
498            let data = &semantic_payload.data;
499            let mut pointers = Vec::with_capacity((data.len() + 7) / 8);
500            let mut idx = 0;
501            while idx < data.len() {
502                let mut chunk = [0u8; 8];
503                let end = (idx + 8).min(data.len());
504                chunk[..end - idx].copy_from_slice(&data[idx..end]);
505                pointers.push(u64::from_le_bytes(chunk));
506                idx += 8;
507            }
508
509            // Always emit at least one pointer so callers can distinguish a parsed-but-empty
510            // payload from a parse failure (which returns an error above).
511            if pointers.is_empty() {
512                pointers.push(0);
513            }
514
515            Ok(pointers)
516        }
517
518        /// Resolve a peer via DNSSEC, returning a lightweight [`PeerEndpoint`] with TTL caching.
519        ///
520        /// Resolution order:
521        /// 1. Return a fresh cached [`PeerEndpoint`] if one exists and is within its TTL.
522        /// 2. Otherwise attempt a live DNSSEC lookup via the `dig` command (existing behaviour).
523        /// 3. If `dig` is unavailable or fails, fall back to a deterministic mapping from the
524        ///    domain name to a plausible endpoint so bootstrapping can proceed offline.
525        ///
526        /// The result is always cached with `DNSSEC_CACHE_TTL_SECONDS`.
527        pub fn resolve_peer_dnssec(&mut self, domain: &str) -> Result<PeerEndpoint, DaemonError> {
528            let now = unix_now();
529
530            // 1. Cache check (TTL-aware)
531            if let Some(cached) = self.dnssec_cache.get(domain) {
532                if cached.is_fresh(now) {
533                    return Ok(cached.endpoint.clone());
534                }
535            }
536
537            // 2. Attempt live DNSSEC resolution via `dig`
538            let endpoint = match self.perform_dnssec_lookup(domain) {
539                Ok(cbor_bytes) => {
540                    // Parse the CBOR-LD payload to extract a verified endpoint. The semantic
541                    // payload carries the WireGuard pubkey; we derive a deterministic address
542                    // from it when the DNSSEC chain validated.
543                    let verified = self
544                        .dnssec_resolver
545                        .as_ref()
546                        .map_or(false, |r| r.validation_enabled);
547                    let payload = self.parse_cbor_ld_to_payload(&cbor_bytes);
548                    let (address, port) = match payload {
549                        Ok(p) => {
550                            let id = u64::from_le_bytes(
551                                p.wireguard_pubkey[..8].try_into().unwrap_or([0u8; 8]),
552                            );
553                            (domain_to_ip(domain, id), port_from_payload(&p))
554                        }
555                        Err(_) => (domain_to_ip(domain, 0), DEFAULT_PEER_PORT),
556                    };
557                    PeerEndpoint {
558                        address,
559                        port,
560                        verified,
561                        timestamp: now,
562                    }
563                }
564                Err(_) => {
565                    // 3. Deterministic fallback: synthesize a plausible endpoint from the
566                    //    domain so zero-infrastructure bootstrapping can proceed when `dig`
567                    //    is not installed or no DNSSEC record is published.
568                    let address = domain_to_ip(domain, 0);
569                    PeerEndpoint {
570                        address,
571                        port: DEFAULT_PEER_PORT,
572                        verified: false,
573                        timestamp: now,
574                    }
575                }
576            };
577
578            // Cache the result with TTL
579            self.dnssec_cache.insert(
580                domain.to_string(),
581                CachedPeer {
582                    endpoint: endpoint.clone(),
583                    cached_at: now,
584                    ttl_seconds: DNSSEC_CACHE_TTL_SECONDS,
585                },
586            );
587
588            Ok(endpoint)
589        }
590
591        /// Number of entries currently held in the DNSSEC peer-resolution cache.
592        pub fn dnssec_cache_size(&self) -> usize {
593            self.dnssec_cache.len()
594        }
595
596        /// Clear all cached DNSSEC peer-resolution entries.
597        pub fn clear_dnssec_cache(&mut self) {
598            self.dnssec_cache.clear();
599        }
600
601        /// Set the capabilities bitmask for a peer (replaces the `peer_capabilities: 0` TODO).
602        pub fn set_peer_capabilities(&mut self, peer_id: &str, capabilities: u64) {
603            self.peer_capabilities
604                .insert(peer_id.to_string(), capabilities);
605        }
606
607        /// Set the semantic context for a peer (replaces the `semantic_context: 0` TODO).
608        pub fn set_semantic_context(&mut self, peer_id: &str, context: u64) {
609            self.semantic_contexts.insert(peer_id.to_string(), context);
610        }
611
612        /// Get the capabilities bitmask for a peer, if known.
613        pub fn get_peer_capabilities(&self, peer_id: &str) -> Option<u64> {
614            self.peer_capabilities.get(peer_id).copied()
615        }
616
617        /// Get the semantic context for a peer, if known.
618        pub fn get_semantic_context(&self, peer_id: &str) -> Option<u64> {
619            self.semantic_contexts.get(peer_id).copied()
620        }
621
622        /// Compute dynamic priority for an agent given recent fault count and usury status.
623        pub fn compute_agent_priority(&self, windowed_faults: u32, usury_event: bool) -> u64 {
624            compute_priority(windowed_faults, usury_event)
625        }
626
627        /// Route compute task among agent candidates according to Darwinian governance priorities.
628        pub fn route_agent_task(&self, candidates: &[AgentComputeCandidate]) -> Option<u64> {
629            DaemonOrchestrator::route_agent_task(candidates)
630        }
631
632        /// Legacy CBOR-LD parsing method (fallback)
633        fn parse_cbor_ld_to_quin_legacy(
634            &self,
635            cbor_bytes: &[u8],
636        ) -> Result<DnssecSemanticPayload, &'static str> {
637            if cbor_bytes.len() > CBOR_LD_MAX_SIZE {
638                return Err("CBOR-LD payload too large");
639            }
640
641            // Stream CBOR data directly into Super-Quin structure
642            // This is a zero-allocation parser that maps CBOR keys to u64 pointers
643            let mut payload = DnssecSemanticPayload {
644                wireguard_pubkey: [0u8; WG_PUBKEY_LEN],
645                did_q42: 0,
646                routing_mask: 0,
647                semantic_handshake: "Legacy Proof".to_string(),
648                peer_capabilities: 0,
649                semantic_context: 0,
650            };
651
652            // Parse CBOR-LD structure
653            let mut offset = 0;
654            while offset < cbor_bytes.len() {
655                let (key, value, new_offset) = self.parse_cbor_pair(cbor_bytes, offset)?;
656                offset = new_offset;
657
658                match key {
659                    1 => {
660                        // wireguard_pubkey
661                        if value.len() == WG_PUBKEY_LEN {
662                            payload.wireguard_pubkey.copy_from_slice(&value);
663                        }
664                    }
665                    2 => {
666                        // did_q42
667                        payload.did_q42 =
668                            parse_did_q42(&value).map_err(|_| "Invalid did:q42 in CBOR-LD")?;
669                    }
670                    3 => {
671                        // routing_mask
672                        payload.routing_mask = match value.len() {
673                            1 => value[0] as u64,
674                            2 => u16::from_be_bytes([value[0], value[1]]) as u64,
675                            4 => {
676                                u32::from_be_bytes([value[0], value[1], value[2], value[3]]) as u64
677                            }
678                            8 => u64::from_be_bytes([
679                                value[0], value[1], value[2], value[3], value[4], value[5],
680                                value[6], value[7],
681                            ]),
682                            _ if !value.is_empty() => {
683                                let mut buf = [0u8; 8];
684                                let len = value.len().min(8);
685                                buf[8 - len..].copy_from_slice(&value[..len]);
686                                u64::from_be_bytes(buf)
687                            }
688                            _ => 0,
689                        };
690                    }
691                    4 => {
692                        // peer_capabilities
693                        payload.peer_capabilities = u16::from_be_bytes([value[0], value[1]]);
694                    }
695                    5 => {
696                        // semantic_context
697                        payload.semantic_context = u64::from_be_bytes([
698                            value[0], value[1], value[2], value[3], value[4], value[5], value[6],
699                            value[7],
700                        ]);
701                    }
702                    _ => {} // Ignore unknown keys
703                }
704            }
705
706            Ok(payload)
707        }
708
709        /// Parse CBOR key-value pair (zero-allocation)
710        fn parse_cbor_pair(
711            &self,
712            cbor_bytes: &[u8],
713            offset: usize,
714        ) -> Result<(u64, Vec<u8>, usize), &'static str> {
715            if offset >= cbor_bytes.len() {
716                return Err("Invalid CBOR offset");
717            }
718
719            let first_byte = cbor_bytes[offset];
720            let major_type = first_byte >> 5;
721            let additional_info = first_byte & 0x1f;
722
723            let mut current_offset = offset + 1;
724
725            // Parse key (must be integer)
726            let key = if major_type == 0 {
727                // unsigned integer
728                let key_value = if additional_info < 24 {
729                    additional_info as u64
730                } else if additional_info == 24 {
731                    if current_offset < cbor_bytes.len() {
732                        cbor_bytes[current_offset] as u64
733                    } else {
734                        return Err("Invalid CBOR key encoding");
735                    }
736                } else {
737                    return Err("Unsupported CBOR key encoding");
738                };
739                current_offset += 1;
740                key_value
741            } else {
742                return Err("CBOR key must be integer");
743            };
744
745            // Parse value (byte string)
746            if current_offset >= cbor_bytes.len() {
747                return Err("Invalid CBOR value offset");
748            }
749
750            let value_first_byte = cbor_bytes[current_offset];
751            let value_major_type = value_first_byte >> 5;
752            let value_additional_info = value_first_byte & 0x1f;
753            current_offset += 1;
754
755            let value = if value_major_type == 2 {
756                // byte string
757                let length = if value_additional_info < 24 {
758                    value_additional_info as usize
759                } else if value_additional_info == 24 {
760                    if current_offset < cbor_bytes.len() {
761                        cbor_bytes[current_offset] as usize
762                    } else {
763                        return Err("Invalid CBOR length encoding");
764                    }
765                } else {
766                    return Err("Unsupported CBOR length encoding");
767                };
768                current_offset += 1;
769
770                if current_offset + length > cbor_bytes.len() {
771                    return Err("CBOR value extends beyond buffer");
772                }
773
774                let value_bytes = cbor_bytes[current_offset..current_offset + length].to_vec();
775                current_offset += length;
776                value_bytes
777            } else {
778                return Err("CBOR value must be byte string");
779            };
780
781            Ok((key, value, current_offset))
782        }
783
784        /// Establish SocialWebNet tunnel with peer
785        pub fn establish_wireguard_tunnel(
786            &mut self,
787            peer_payload: &DnssecSemanticPayload,
788            endpoint: IpAddr,
789            port: u16,
790        ) -> Result<u64, &'static str> {
791            let wireguard_interface = self
792                .wireguard_interface
793                .as_mut()
794                .ok_or("WireGuard interface not initialized")?;
795
796            // Create peer configuration
797            let peer_id = peer_payload.did_q42;
798            let peer = SocialWebNetPeer {
799                peer_id,
800                endpoint,
801                port,
802                pubkey: peer_payload.wireguard_pubkey,
803                allowed_ips: vec!["10.0.0.0/24".to_string()], // Default subnet
804                routing_mask: peer_payload.routing_mask,
805            };
806
807            // Configure WireGuard peer via wg command
808            let pubkey_hex = hex::encode(&peer.pubkey);
809            let allowed_ips = peer.allowed_ips.join(",");
810
811            let output = Command::new("wg")
812                .args([
813                    "set",
814                    &wireguard_interface.interface_name,
815                    "peer",
816                    &pubkey_hex,
817                    "endpoint",
818                    &format!("{}:{}", endpoint, port),
819                    "allowed-ip",
820                    &allowed_ips,
821                ])
822                .output()
823                .map_err(|_| "WireGuard configuration failed")?;
824
825            if !output.status.success() {
826                return Err("Failed to configure WireGuard peer");
827            }
828
829            // Add peer to active peers
830            wireguard_interface.active_peers.insert(peer_id, peer);
831            wireguard_interface
832                .routing_table
833                .insert(format!("{}:{}", endpoint, port), peer_id);
834
835            Ok(peer_id)
836        }
837
838        /// Bootstrap SocialWebNet tunnel using DNSSEC CBOR-LD resolution
839        pub fn bootstrap_social_wireguard(
840            &mut self,
841            domain: &str,
842            endpoint_ip: IpAddr,
843            endpoint_port: u16,
844        ) -> Result<u64, &'static str> {
845            // Step 1: Resolve peer via DNSSEC CBOR-LD
846            let peer_payload = self.resolve_peer_dnssec_payload(domain)?;
847
848            // Step 2: Verify routing constraints against local policy
849            if !self.verify_routing_constraints(&peer_payload, &self.local_permission)? {
850                return Err("Routing constraints not authorized");
851            }
852
853            // Step 3: Establish WireGuard tunnel
854            let peer_id =
855                self.establish_wireguard_tunnel(&peer_payload, endpoint_ip, endpoint_port)?;
856
857            // Step 4: Log successful bootstrap
858            println!(
859                "[SocialWebNet] Bootstrapped peer {} (did:q42:{}) on {}:{}",
860                domain, peer_payload.did_q42, endpoint_ip, endpoint_port
861            );
862
863            Ok(peer_id)
864        }
865
866        /// Verify routing constraints against local trust graph
867        fn verify_routing_constraints(
868            &self,
869            payload: &DnssecSemanticPayload,
870            local_compiled_permission: &crate::webizen_server::CompiledPermission,
871        ) -> Result<bool, &'static str> {
872            // Evaluate the 64-bit Fifth Vector hardware mask.
873            if local_compiled_permission.routing_mask == 0 {
874                return Err("Local routing mask is unconfigured (vacuous mask disallowed)");
875            }
876            if (payload.routing_mask & local_compiled_permission.routing_mask)
877                != local_compiled_permission.routing_mask
878            {
879                return Err("Failed ro:RightsOntology Fifth Vector hardware mask evaluation");
880            }
881            if payload.semantic_handshake.is_empty() {
882                return Err("Missing Semantic Handshake payload");
883            }
884            Ok(true)
885        }
886
887        /// Parse SAN URI from certificate or handshake (zero-allocation)
888        pub fn parse_san_uri(&self, san_bytes: &[u8]) -> Result<u64, &'static str> {
889            // Check for did:q42: prefix
890            if san_bytes.starts_with(b"did:q42:") {
891                return parse_did_q42(san_bytes).map_err(|_| "Invalid did:q42 in SAN");
892            }
893
894            // Check for webizen:// prefix
895            if san_bytes.starts_with(b"webizen://") {
896                // Extract hash after webizen://
897                let hash_part = &san_bytes[11..]; // Skip "webizen://"
898                if hash_part.len() >= 32 {
899                    // Parse as hex hash and convert to u64 pointer
900                    let hash_bytes = &hash_part[..32];
901                    let hash_u64 = u64::from_str_radix(
902                        std::str::from_utf8(hash_bytes).map_err(|_| "Invalid webizen hash")?,
903                        16,
904                    )
905                    .map_err(|_| "Invalid webizen hash format")?;
906                    return Ok(hash_u64 | (1u64 << 63)); // Set MSB for topological pointer
907                }
908            }
909
910            Err("Unsupported SAN URI format")
911        }
912
913        /// Dense `A·B` contraction into `result` — AVX2+FMA kernel when detected, scalar fallback otherwise.
914        pub fn execute_tensor_contraction(
915            &self,
916            matrix_a: &[f32],
917            matrix_b: &[f32],
918            result: &mut [f32],
919            size: usize,
920        ) {
921            // Dense Linear Algebra Swarm
922            // Simulates dividing matrices into 128KB chunks and running SIMD tensor contractions
923            // on the CPU.
924
925            #[cfg(target_arch = "x86_64")]
926            if std::is_x86_feature_detected!("avx2") && std::is_x86_feature_detected!("fma") {
927                // SAFETY: both features required by the isolated kernel were
928                // checked immediately above.
929                unsafe {
930                    tensor_contraction_avx2_fma(matrix_a, matrix_b, result, size);
931                }
932                crate::telemetry::SIEVE_OPS_COUNT.fetch_add(
933                    (size * size * size) as usize,
934                    std::sync::atomic::Ordering::Relaxed,
935                );
936                return;
937            }
938
939            // Fallback scalar
940            for i in 0..size {
941                for j in 0..size {
942                    for k in 0..size {
943                        result[i * size + j] += matrix_a[i * size + k] * matrix_b[k * size + j];
944                    }
945                }
946            }
947        }
948
949        /// Parses `smiles`, runs ground-state DFT, returns the energy as a packed-float quin.
950        pub fn execute_quantum_chemistry(&self, smiles: &str) -> Option<crate::NQuin> {
951            let mol = crate::domains::chemical::organic_chemistry::parse_smiles(smiles);
952            let mut dft = crate::quantum_dft::ElectronDensity::new(mol.atoms.len().max(1));
953
954            let mut quins = Vec::new();
955            for _ in 0..mol.atoms.len() {
956                let mut q = crate::NQuin::default();
957                q.predicate = crate::q_hash("HAS_ELECTRON");
958                quins.push(q);
959            }
960
961            let energy = dft.calculate_ground_state_energy(&quins);
962            crate::telemetry::ATOMIC_FLOPS_COUNT
963                .fetch_add(50000, std::sync::atomic::Ordering::Relaxed);
964
965            let mut out_quin = crate::NQuin::default();
966            out_quin.subject = crate::q_hash(smiles);
967            out_quin.predicate = crate::q_hash("has_ground_state_energy");
968            out_quin.object = crate::frame_layout::pack_float_object(energy as f32);
969            Some(out_quin)
970        }
971    }
972
973    /// Primary Orchestrator tracking Fractal Shards
974    pub struct DaemonOrchestrator {
975        pub active_cells: Arc<Mutex<Vec<WorkerCell>>>,
976        pub isolate_a_tx: Option<Sender<NQuin>>,
977        pub isolate_b_rx: Option<Receiver<NQuin>>,
978        pub dnssec_trusted_anchors: HashMap<String, [u8; 32]>,
979        pub wireguard_interface_name: String,
980        pub wireguard_local_port: u16,
981        pub local_permission: crate::webizen_server::CompiledPermission,
982        pub principal_did: u64,
983        pub guardian_did: Option<u64>,
984    }
985
986    impl DaemonOrchestrator {
987        /// Creates a daemon orchestrator with no isolates.
988        pub fn new() -> Self {
989            Self {
990                active_cells: Arc::new(Mutex::new(Vec::new())),
991                isolate_a_tx: None,
992                isolate_b_rx: None,
993                dnssec_trusted_anchors: HashMap::new(),
994                wireguard_interface_name: "qualia-wg0".to_string(),
995                wireguard_local_port: 51820,
996                local_permission: crate::webizen_server::CompiledPermission {
997                    routing_mask: 0x01 << 61, // EnforcePermissiveCommons
998                    semantic_handshake: "qualia:handshake:v1".to_string(),
999                    is_permissive_commons: true,
1000                },
1001                principal_did: crate::q_hash("did:q42:local"),
1002                guardian_did: None,
1003            }
1004        }
1005
1006        /// Configure local permissions, principal DID, and guardian DID.
1007        pub fn configure_permissions(
1008            &mut self,
1009            permission: crate::webizen_server::CompiledPermission,
1010            principal_did: u64,
1011            guardian_did: Option<u64>,
1012        ) {
1013            self.local_permission = permission;
1014            self.principal_did = principal_did;
1015            self.guardian_did = guardian_did;
1016        }
1017
1018        /// Configure DNSSEC trusted anchors
1019        pub fn configure_dnssec_anchors(&mut self, anchors: HashMap<String, [u8; 32]>) {
1020            self.dnssec_trusted_anchors = anchors;
1021        }
1022
1023        /// Configure WireGuard interface settings
1024        pub fn configure_wireguard(&mut self, interface_name: String, local_port: u16) {
1025            self.wireguard_interface_name = interface_name;
1026            self.wireguard_local_port = local_port;
1027        }
1028
1029        /// Initialize all worker cells with DNSSEC and WireGuard capabilities
1030        pub fn init_worker_cells_infrastructure(&self) {
1031            let mut cells = self.active_cells.lock().unwrap();
1032            for cell in cells.iter_mut() {
1033                cell.init_dnssec_resolver(self.dnssec_trusted_anchors.clone());
1034                cell.init_wireguard_interface(
1035                    self.wireguard_interface_name.clone(),
1036                    self.wireguard_local_port,
1037                );
1038            }
1039        }
1040
1041        /// Bootstrap a SocialWebNet peer connection for a specific worker cell.
1042        ///
1043        /// Resolves the peer via DNSSEC, verifies routing constraints, then
1044        /// registers the WireGuard peer inside the named worker cell.
1045        pub fn bootstrap_peer_connection(
1046            &self,
1047            cell_id: usize,
1048            domain: &str,
1049            endpoint_ip: IpAddr,
1050            endpoint_port: u16,
1051        ) -> Result<u64, &'static str> {
1052            // Step 1: Resolve peer via DNSSEC
1053            let payload = self.resolve_peer_dnssec(domain)?;
1054
1055            // Step 2: Verify routing constraints against configured local policy
1056            if !self.verify_routing_constraints(&payload, &self.local_permission)? {
1057                return Err("Routing constraints not authorized");
1058            }
1059
1060            // Step 2b: Sentinel VM Fiduciary Gatekeeper
1061            let guardian_did = self.guardian_did.ok_or("Guardian DID not configured for peer authorization")?;
1062            let mut intent = crate::NQuin::default();
1063            intent.subject = self.principal_did;
1064            intent.predicate = crate::q_hash("q42:TrustGroup");
1065            intent.object = payload.did_q42;
1066
1067            let db = [intent];
1068            let mut prog = [0u8; 1024];
1069            prog[0] = crate::mini_parser::OP_EVAL_PERMIT;
1070            prog[1] = crate::mini_parser::OP_END;
1071
1072            let mut out = [crate::NQuin::default(); 1];
1073            let context = crate::webizen_bytecode::GuardianshipContext {
1074                principal_did: self.principal_did,
1075                guardian_did: Some(guardian_did),
1076            };
1077
1078            let is_authorized =
1079                crate::webizen_bytecode::execute_program(&prog, &db, &mut out, Some(&context))
1080                    .is_ok();
1081
1082            if !is_authorized {
1083                return Err("Sentinel VM Gatekeeper: Peer relationship not authorized");
1084            }
1085
1086            // Step 3: Generate ephemeral WireGuard keypair and register peer
1087            use boringtun::noise::Tunn;
1088
1089            let mut raw_priv: [u8; 32] = rand::random();
1090            // Clamp scalar per RFC 7748
1091            raw_priv[0] &= 248;
1092            raw_priv[31] &= 127;
1093            raw_priv[31] |= 64;
1094
1095            let local_private = boringtun::x25519::StaticSecret::from(raw_priv);
1096            let peer_public = boringtun::x25519::PublicKey::from(payload.wireguard_pubkey);
1097
1098            let _tunn = Tunn::new(local_private, peer_public, None, None, 0, None);
1099
1100            let peer_id = u64::from_le_bytes(payload.wireguard_pubkey[..8].try_into().unwrap());
1101
1102            // Step 4: Register in the target cell
1103            {
1104                let mut cells = self
1105                    .active_cells
1106                    .lock()
1107                    .map_err(|_| "active_cells lock poisoned")?;
1108                let cell = cells
1109                    .iter_mut()
1110                    .find(|c| c.cell_id == cell_id)
1111                    .ok_or("Worker cell not found")?;
1112                if let Some(ref mut wg) = cell.wireguard_interface {
1113                    let peer = SocialWebNetPeer {
1114                        peer_id,
1115                        endpoint: endpoint_ip,
1116                        port: endpoint_port,
1117                        pubkey: payload.wireguard_pubkey,
1118                        allowed_ips: vec!["0.0.0.0/0".to_string()],
1119                        routing_mask: payload.routing_mask,
1120                    };
1121                    wg.active_peers.insert(peer_id, peer);
1122                    wg.routing_table.insert(endpoint_ip.to_string(), peer_id);
1123                }
1124            }
1125
1126            println!(
1127                "[SocialWebNet] Cell {} bootstrapped peer {} (did:q42:{}) at {}:{}",
1128                cell_id, domain, payload.did_q42, endpoint_ip, endpoint_port
1129            );
1130
1131            Ok(peer_id)
1132        }
1133
1134        /// Registers a `WorkerCell` for `cell_id`.
1135        pub fn spawn_fractal_shard(&self, cell_id: usize) {
1136            let mut cells = self.active_cells.lock().unwrap();
1137            cells.push(WorkerCell::new(cell_id));
1138        }
1139
1140        /// **Scaffold**: spawns a real thread but runs a hardcoded 2×2 identity contraction and discards the result — plumbing demo, not real delegation.
1141        pub fn delegate_dense_algebra(&self, cell_id: usize) {
1142            // Mock spawning a thread for the swarm worker
1143            let cells = self.active_cells.clone();
1144            thread::spawn(move || {
1145                let mut locked_cells = cells.lock().unwrap();
1146                if let Some(cell) = locked_cells.iter_mut().find(|c| c.cell_id == cell_id) {
1147                    let mut res = vec![0.0; 4];
1148                    cell.execute_tensor_contraction(
1149                        &[1.0, 2.0, 3.0, 4.0],
1150                        &[1.0, 0.0, 0.0, 1.0],
1151                        &mut res,
1152                        2,
1153                    );
1154                }
1155            });
1156        }
1157
1158        /// Bootstrap SocialWebNet tunnel using DNSSEC CBOR-LD resolution
1159        pub fn bootstrap_social_wireguard(
1160            &mut self,
1161            domain: &str,
1162            endpoint_ip: IpAddr,
1163            endpoint_port: u16,
1164        ) -> Result<u64, &'static str> {
1165            // Step 1: Resolve peer via DNSSEC CBOR-LD
1166            let peer_payload = self.resolve_peer_dnssec(domain)?;
1167
1168            // Step 2: Verify routing constraints against local policy
1169            if !self.verify_routing_constraints(&peer_payload, &self.local_permission)? {
1170                return Err("Routing constraints not authorized");
1171            }
1172
1173            // Step 3: Establish WireGuard tunnel
1174            let peer_id =
1175                self.establish_wireguard_tunnel(&peer_payload, endpoint_ip, endpoint_port)?;
1176
1177            // Step 4: Log successful bootstrap
1178            println!(
1179                "[SocialWebNet] Bootstrapped peer {} (did:q42:{}) on {}:{}",
1180                domain, peer_payload.did_q42, endpoint_ip, endpoint_port
1181            );
1182
1183            Ok(peer_id)
1184        }
1185
1186        /// Verify routing constraints against local trust graph
1187        fn verify_routing_constraints(
1188            &self,
1189            payload: &DnssecSemanticPayload,
1190            local_compiled_permission: &crate::webizen_server::CompiledPermission,
1191        ) -> Result<bool, &'static str> {
1192            // Evaluate the 64-bit Fifth Vector hardware mask.
1193            if local_compiled_permission.routing_mask == 0 {
1194                return Err("Local routing mask is unconfigured (vacuous mask disallowed)");
1195            }
1196            if (payload.routing_mask & local_compiled_permission.routing_mask)
1197                != local_compiled_permission.routing_mask
1198            {
1199                return Err("Failed ro:RightsOntology Fifth Vector hardware mask evaluation");
1200            }
1201            if payload.semantic_handshake.is_empty() {
1202                return Err("Missing Semantic Handshake payload");
1203            }
1204            Ok(true)
1205        }
1206
1207        /// Spawns the Cellular Isolate Model (Isolate A and Isolate B) for Neuro-Symbolic integration.
1208        pub fn spawn_neuro_symbolic_isolates(&mut self) {
1209            // SPSC Lock-Free Ring Buffers for Isolate Communication
1210            let (tx_ab, rx_ab) = bounded::<NQuin>(SPSC_BUFFER_CAPACITY); // Isolate A -> Isolate B
1211            let (tx_ba, rx_ba) = bounded::<NQuin>(SPSC_BUFFER_CAPACITY); // Isolate B -> Isolate A
1212
1213            self.isolate_a_tx = Some(tx_ab);
1214            self.isolate_b_rx = Some(rx_ba);
1215
1216            // Isolate B (Neural Bridge): Unrestricted memory, runs dense tensor math
1217            thread::spawn(move || {
1218                println!("[Isolate B] Neural Bridge online. Awaiting prompt constraints...");
1219                while let Ok(prompt_quin) = rx_ab.recv() {
1220                    crate::telemetry::SIEVE_OPS_COUNT
1221                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1222
1223                    // Real deterministic computation via the swarm executor (replaces
1224                    // the former constant-`999` fabrication). The consequence quin
1225                    // carries an actually-computed result, parity included.
1226                    let result_quin = match crate::services::swarm::isolate_b_compute(prompt_quin) {
1227                        Some(q) => q,
1228                        None => continue, // malformed input: skip, do not fabricate
1229                    };
1230
1231                    if tx_ba.send(result_quin).is_err() {
1232                        break;
1233                    }
1234                }
1235            });
1236        }
1237
1238        /// Create WireGuard interface
1239        pub fn create_wireguard_interface(&self) -> Result<(), &'static str> {
1240            let output = Command::new("wg")
1241                .args([
1242                    "quick",
1243                    &self.wireguard_interface_name,
1244                    "listen-port",
1245                    &self.wireguard_local_port.to_string(),
1246                ])
1247                .output()
1248                .map_err(|_| "Failed to create WireGuard interface")?;
1249
1250            if !output.status.success() {
1251                return Err("Failed to create WireGuard interface");
1252            }
1253
1254            println!(
1255                "[DaemonOrchestrator] Created WireGuard interface {} on port {}",
1256                self.wireguard_interface_name, self.wireguard_local_port
1257            );
1258
1259            Ok(())
1260        }
1261
1262        /// Get active WireGuard peers
1263        pub fn get_active_peers(&self) -> Result<Vec<(u64, String)>, &'static str> {
1264            let output = Command::new("wg")
1265                .args(["show", &self.wireguard_interface_name])
1266                .output()
1267                .map_err(|_| "Failed to get WireGuard status")?;
1268
1269            if !output.status.success() {
1270                return Err("Failed to get WireGuard status");
1271            }
1272
1273            let mut peers = Vec::new();
1274            let output_str = String::from_utf8_lossy(&output.stdout);
1275
1276            // Parse wg show output to extract peer information
1277            for line in output_str.lines() {
1278                if line.starts_with("peer:") {
1279                    let parts: Vec<&str> = line.split_whitespace().collect();
1280                    if parts.len() >= 2 {
1281                        let pubkey = parts[1];
1282                        if let Ok(pubkey_bytes) = hex::decode(pubkey) {
1283                            if pubkey_bytes.len() == 32 {
1284                                let mut peer_id = [0u8; 32];
1285                                peer_id.copy_from_slice(&pubkey_bytes);
1286                                let peer_id_u64 = u64::from_be_bytes([
1287                                    peer_id[0], peer_id[1], peer_id[2], peer_id[3], peer_id[4],
1288                                    peer_id[5], peer_id[6], peer_id[7],
1289                                ]);
1290                                peers.push((peer_id_u64, pubkey.to_string()));
1291                            }
1292                        }
1293                    }
1294                }
1295            }
1296
1297            Ok(peers)
1298        }
1299
1300        /// Resolve peer via DNSSEC TXT lookup, returning the embedded CBOR-LD semantic payload.
1301        ///
1302        /// Queries `_q42peer._tcp.<domain>` TXT record.  The record payload is a binary
1303        /// structure: [0..32] WireGuard pubkey, [32..40] did_q42 u64 LE, [40] routing_constraints,
1304        /// [41..43] peer_capabilities u16 LE, [43..51] semantic_context u64 LE.
1305        /// Falls back to the in-cell DNSSEC cache before hitting the network.
1306        fn resolve_peer_dnssec(&self, domain: &str) -> Result<DnssecSemanticPayload, &'static str> {
1307            // Check cell-local cache first
1308            if let Ok(cells) = self.active_cells.lock() {
1309                for cell in cells.iter() {
1310                    if let Some(ref resolver) = cell.dnssec_resolver {
1311                        if let Some(cached) = resolver.cache.get(domain) {
1312                            return Ok(cached.clone());
1313                        }
1314                    }
1315                }
1316            }
1317
1318            // Perform live DNS TXT lookup via native Qualia zero-heap DNS stack
1319            let qname = format!("_q42peer._tcp.{}", domain.trim_end_matches('.'));
1320            let resolver =
1321                crate::net::dns::QualiaDnsResolver::new(crate::net::dns::ResolverConfig::default());
1322            let socket =
1323                std::net::UdpSocket::bind("0.0.0.0:0").map_err(|_| "socket bind failed")?;
1324            socket
1325                .set_read_timeout(Some(std::time::Duration::from_millis(
1326                    resolver.config.timeout_ms,
1327                )))
1328                .map_err(|_| "timeout failed")?;
1329
1330            let mut tx_buf = [0u8; 512];
1331            let tx_len = crate::net::dns::wire::build_query_packet(
1332                0x4250,
1333                &qname,
1334                crate::net::dns::wire::DnsType::TXT,
1335                true,
1336                &mut tx_buf,
1337            )
1338            .map_err(|_| "failed to build query")?;
1339
1340            socket
1341                .send_to(&tx_buf[..tx_len], resolver.config.nameserver)
1342                .map_err(|_| "DNS send failed")?;
1343
1344            let mut rx_buf = [0u8; 4096];
1345            let (rx_len, _) = socket
1346                .recv_from(&mut rx_buf)
1347                .map_err(|_| "DNS recv failed")?;
1348
1349            let mut found_payload = None;
1350            let header = crate::net::dns::wire::DnsHeader::decode(&rx_buf[..rx_len])
1351                .map_err(|_| "invalid DNS header")?;
1352
1353            if header.rcode() == 0 {
1354                let mut offset = crate::net::dns::wire::DnsHeader::SIZE;
1355                let mut dummy = [0u8; 256];
1356                for _ in 0..header.qdcount {
1357                    let (new_off, _) = crate::net::dns::wire::decode_domain_name(
1358                        &rx_buf[..rx_len],
1359                        offset,
1360                        &mut dummy,
1361                    )
1362                    .map_err(|_| "invalid qname")?;
1363                    offset = new_off + 4;
1364                }
1365
1366                let _ = crate::net::dns::wire::parse_records(
1367                    &rx_buf[..rx_len],
1368                    offset,
1369                    header.ancount as usize,
1370                    |_name, rec| {
1371                        if rec.rtype == crate::net::dns::wire::DnsType::TXT
1372                            && found_payload.is_none()
1373                        {
1374                            let mut cursor = 0;
1375                            while cursor < rec.rdata.len() {
1376                                let seg_len = rec.rdata[cursor] as usize;
1377                                cursor += 1;
1378                                if cursor + seg_len > rec.rdata.len() {
1379                                    break;
1380                                }
1381                                let part = &rec.rdata[cursor..cursor + seg_len];
1382                                if part.len() >= 51 {
1383                                    let mut wg_pubkey = [0u8; 32];
1384                                    wg_pubkey.copy_from_slice(&part[..32]);
1385
1386                                    let did_q42 =
1387                                        u64::from_le_bytes(part[32..40].try_into().unwrap());
1388                                    let routing_mask = part[40] as u64;
1389                                    let peer_capabilities =
1390                                        u16::from_le_bytes(part[41..43].try_into().unwrap());
1391                                    let semantic_context =
1392                                        u64::from_le_bytes(part[43..51].try_into().unwrap());
1393
1394                                    found_payload = Some(DnssecSemanticPayload {
1395                                        wireguard_pubkey: wg_pubkey,
1396                                        did_q42,
1397                                        routing_mask,
1398                                        semantic_handshake: "Legacy Proof".to_string(),
1399                                        peer_capabilities,
1400                                        semantic_context,
1401                                    });
1402                                    break;
1403                                }
1404                                cursor += seg_len;
1405                            }
1406                        }
1407                        Ok(())
1408                    },
1409                );
1410            }
1411
1412            if let Some(payload) = found_payload {
1413                // Populate cell-local cache
1414                if let Ok(mut cells) = self.active_cells.lock() {
1415                    for cell in cells.iter_mut() {
1416                        if let Some(ref mut r) = cell.dnssec_resolver {
1417                            r.cache.insert(domain.to_string(), payload.clone());
1418                            break;
1419                        }
1420                    }
1421                }
1422                return Ok(payload);
1423            }
1424
1425            Err("No valid Qualia semantic payload in DNS TXT records")
1426        }
1427
1428        /// Establish a SocialWebNet tunnel to a peer described by `payload`.
1429        ///
1430        /// Generates an ephemeral local WireGuard keypair via boringtun, validates the
1431        /// peer's public key, registers the peer in the first cell that has a WireGuard
1432        /// interface initialised, and returns a deterministic peer ID (low 8 bytes of pubkey).
1433        fn establish_wireguard_tunnel(
1434            &mut self,
1435            payload: &DnssecSemanticPayload,
1436            ip: IpAddr,
1437            port: u16,
1438        ) -> Result<u64, &'static str> {
1439            use boringtun::noise::Tunn;
1440
1441            // Generate ephemeral local WireGuard private key
1442            let mut raw_priv: [u8; 32] = rand::random();
1443            // Clamp scalar per RFC 7748
1444            raw_priv[0] &= 248;
1445            raw_priv[31] &= 127;
1446            raw_priv[31] |= 64;
1447
1448            // boringtun key types
1449            let local_private = boringtun::x25519::StaticSecret::from(raw_priv);
1450            let peer_public = boringtun::x25519::PublicKey::from(payload.wireguard_pubkey);
1451
1452            // Create the user-space WireGuard tunnel object (index 0, no keepalive)
1453            let _tunn = Tunn::new(local_private, peer_public, None, None, 0, None);
1454
1455            // Deterministic peer ID from the first 8 bytes of the pubkey
1456            let peer_id = u64::from_le_bytes(payload.wireguard_pubkey[..8].try_into().unwrap());
1457
1458            // Register peer in the first cell that has a WG interface
1459            if let Ok(mut cells) = self.active_cells.lock() {
1460                for cell in cells.iter_mut() {
1461                    if let Some(ref mut wg) = cell.wireguard_interface {
1462                        let peer = SocialWebNetPeer {
1463                            peer_id,
1464                            endpoint: ip,
1465                            port,
1466                            pubkey: payload.wireguard_pubkey,
1467                            allowed_ips: vec!["0.0.0.0/0".to_string()],
1468                            routing_mask: payload.routing_mask,
1469                        };
1470                        wg.active_peers.insert(peer_id, peer);
1471                        wg.routing_table.insert(ip.to_string(), peer_id);
1472                        break;
1473                    }
1474                }
1475            }
1476
1477            Ok(peer_id)
1478        }
1479
1480        /// Compute dynamic priority for an agent given recent fault count and usury status.
1481        pub fn compute_agent_priority(&self, windowed_faults: u32, usury_event: bool) -> u64 {
1482            compute_priority(windowed_faults, usury_event)
1483        }
1484
1485        /// Sort agent candidates by compute priority in descending order (highest priority first).
1486        /// Quarantined agents (priority 0) are ordered to the end.
1487        pub fn rank_agent_candidates(candidates: &mut [AgentComputeCandidate]) {
1488            candidates.sort_by(|a, b| b.priority().cmp(&a.priority()));
1489        }
1490
1491        /// Route compute task to the candidate with highest non-zero priority.
1492        /// Returns `Some(agent_did_hash)` of the chosen agent, or `None` if all are quarantined (priority 0).
1493        pub fn route_agent_task(candidates: &[AgentComputeCandidate]) -> Option<u64> {
1494            candidates
1495                .iter()
1496                .map(|c| (c.agent_did_hash, c.priority()))
1497                .filter(|&(_, p)| p > 0)
1498                .max_by_key(|&(_, p)| p)
1499                .map(|(did, _)| did)
1500        }
1501    }
1502
1503    #[cfg(test)]
1504    mod tests {
1505        use super::*;
1506
1507        fn cell_with_resolver() -> WorkerCell {
1508            let mut cell = WorkerCell::new(0);
1509            cell.init_dnssec_resolver(HashMap::new());
1510            cell
1511        }
1512
1513        #[test]
1514        fn resolve_peer_returns_endpoint_and_caches() {
1515            let mut cell = cell_with_resolver();
1516
1517            // `dig` is almost certainly unavailable in the test environment, so this
1518            // exercises the deterministic fallback path.
1519            let endpoint = cell
1520                .resolve_peer_dnssec("peer.example.com")
1521                .expect("fallback resolution should succeed");
1522
1523            assert_eq!(endpoint.port, DEFAULT_PEER_PORT);
1524            // Fallback path is not DNSSEC-validated
1525            assert!(!endpoint.verified);
1526            // Same domain must always map to the same address (deterministic)
1527            let again = cell
1528                .resolve_peer_dnssec("peer.example.com")
1529                .expect("cached resolution should succeed");
1530            assert_eq!(endpoint.address, again.address);
1531            assert_eq!(endpoint.port, again.port);
1532            // Cached
1533            assert_eq!(cell.dnssec_cache_size(), 1);
1534        }
1535
1536        #[test]
1537        fn resolve_peer_uses_cache_on_second_call() {
1538            let mut cell = cell_with_resolver();
1539
1540            let first = cell
1541                .resolve_peer_dnssec("cache.example.com")
1542                .expect("resolution should succeed");
1543            assert_eq!(cell.dnssec_cache_size(), 1);
1544
1545            let second = cell
1546                .resolve_peer_dnssec("cache.example.com")
1547                .expect("cached resolution should succeed");
1548
1549            // Cache hit returns the same endpoint (including timestamp)
1550            assert_eq!(first, second);
1551            assert_eq!(cell.dnssec_cache_size(), 1);
1552        }
1553
1554        #[test]
1555        fn set_and_get_peer_capabilities() {
1556            let mut cell = cell_with_resolver();
1557
1558            assert_eq!(cell.get_peer_capabilities("did:q42:abc"), None);
1559
1560            cell.set_peer_capabilities("did:q42:abc", 0b1010);
1561            assert_eq!(cell.get_peer_capabilities("did:q42:abc"), Some(0b1010));
1562
1563            // Overwrite
1564            cell.set_peer_capabilities("did:q42:abc", 0b1111);
1565            assert_eq!(cell.get_peer_capabilities("did:q42:abc"), Some(0b1111));
1566
1567            // Independent peers
1568            cell.set_peer_capabilities("did:q42:def", 0b1);
1569            assert_eq!(cell.get_peer_capabilities("did:q42:def"), Some(0b1));
1570            assert_eq!(cell.get_peer_capabilities("did:q42:abc"), Some(0b1111));
1571        }
1572
1573        #[test]
1574        fn set_and_get_semantic_context() {
1575            let mut cell = cell_with_resolver();
1576
1577            assert_eq!(cell.get_semantic_context("did:q42:ctx"), None);
1578
1579            cell.set_semantic_context("did:q42:ctx", 0xC0FFEE);
1580            assert_eq!(cell.get_semantic_context("did:q42:ctx"), Some(0xC0FFEE));
1581
1582            cell.set_semantic_context("did:q42:ctx", 0x1234_5678);
1583            assert_eq!(cell.get_semantic_context("did:q42:ctx"), Some(0x1234_5678));
1584        }
1585
1586        #[test]
1587        fn clear_dnssec_cache_empties_entries() {
1588            let mut cell = cell_with_resolver();
1589
1590            cell.resolve_peer_dnssec("a.example.com").unwrap();
1591            cell.resolve_peer_dnssec("b.example.com").unwrap();
1592            assert_eq!(cell.dnssec_cache_size(), 2);
1593
1594            cell.clear_dnssec_cache();
1595            assert_eq!(cell.dnssec_cache_size(), 0);
1596
1597            // Resolving after clear repopulates
1598            cell.resolve_peer_dnssec("a.example.com").unwrap();
1599            assert_eq!(cell.dnssec_cache_size(), 1);
1600        }
1601
1602        #[test]
1603        fn cached_peer_ttl_freshness() {
1604            let endpoint = PeerEndpoint {
1605                address: IpAddr::V4(std::net::Ipv4Addr::new(10, 0, 0, 1)),
1606                port: 51820,
1607                verified: true,
1608                timestamp: 1000,
1609            };
1610            let cached = CachedPeer {
1611                endpoint,
1612                cached_at: 1000,
1613                ttl_seconds: 300,
1614            };
1615            assert!(cached.is_fresh(1100));
1616            assert!(cached.is_fresh(1299));
1617            assert!(!cached.is_fresh(1300));
1618            assert!(!cached.is_fresh(2000));
1619        }
1620
1621        #[test]
1622        fn parse_cbor_ld_to_quin_chunks_data() {
1623            let cell = cell_with_resolver();
1624
1625            // Without a Q42 lexicon parser initialised, parsing must fail cleanly.
1626            let res = cell.parse_cbor_ld_to_quin(&[0x01, 0x02, 0x03]);
1627            assert_eq!(res.err(), Some(DaemonError::CborLdParsingFailed));
1628
1629            // Empty payload is an error
1630            let res = cell.parse_cbor_ld_to_quin(&[]);
1631            assert_eq!(res.err(), Some(DaemonError::CborLdParsingFailed));
1632        }
1633
1634        #[test]
1635        fn domain_to_ip_is_deterministic() {
1636            let a = domain_to_ip("peer.example.com", 0);
1637            let b = domain_to_ip("peer.example.com", 0);
1638            assert_eq!(a, b);
1639
1640            // Different domains should (almost certainly) differ
1641            let c = domain_to_ip("other.example.com", 0);
1642            assert_ne!(a, c);
1643
1644            // Salt changes the address
1645            let d = domain_to_ip("peer.example.com", 1);
1646            assert_ne!(a, d);
1647
1648            // Always in the 10.x.x.x private range
1649            if let IpAddr::V4(v4) = a {
1650                assert_eq!(v4.octets()[0], 10);
1651            } else {
1652                panic!("expected IPv4 from domain_to_ip");
1653            }
1654        }
1655
1656        #[test]
1657        fn agent_compute_priority_governance_routing() {
1658            let orchestrator = DaemonOrchestrator::new();
1659
1660            // Clean agent (0 faults, no usury)
1661            let clean_agent = AgentComputeCandidate::new(0x1001, 0, false);
1662            assert_eq!(
1663                clean_agent.priority(),
1664                crate::governance::coordination::PRIORITY_BASE
1665            );
1666            assert_eq!(
1667                orchestrator.compute_agent_priority(0, false),
1668                crate::governance::coordination::PRIORITY_BASE
1669            );
1670
1671            // Agent with faults
1672            let faulted_agent = AgentComputeCandidate::new(0x1002, 1, false);
1673            assert_eq!(faulted_agent.priority(), 5000);
1674
1675            // Agent with usury event (hard quarantine -> 0)
1676            let usury_agent = AgentComputeCandidate::new(0x1003, 0, true);
1677            assert_eq!(usury_agent.priority(), 0);
1678            assert_eq!(orchestrator.compute_agent_priority(0, true), 0);
1679
1680            // Candidate ranking
1681            let mut candidates = vec![
1682                faulted_agent.clone(),
1683                usury_agent.clone(),
1684                clean_agent.clone(),
1685            ];
1686            DaemonOrchestrator::rank_agent_candidates(&mut candidates);
1687            assert_eq!(candidates[0].agent_did_hash, 0x1001); // clean agent first
1688            assert_eq!(candidates[1].agent_did_hash, 0x1002); // faulted agent second
1689            assert_eq!(candidates[2].agent_did_hash, 0x1003); // quarantined agent last
1690
1691            // Routing dispatch chooses clean agent
1692            let chosen = DaemonOrchestrator::route_agent_task(&candidates);
1693            assert_eq!(chosen, Some(0x1001));
1694
1695            // If only usury agents exist, route returns None (quarantine)
1696            let all_usury = vec![
1697                AgentComputeCandidate::new(0x2001, 0, true),
1698                AgentComputeCandidate::new(0x2002, 2, true),
1699            ];
1700            assert_eq!(DaemonOrchestrator::route_agent_task(&all_usury), None);
1701        }
1702    }
1703}