clm-kernel 0.0.23

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Federated Service Catalog (`service.pkc.*`) & Dynamic Capability Routing
//! Canonical Path: kernel/clm_rust_core/src/mesh/service.rs
//!
//! Implements:
//! - DEL-258-01: Federated Service Catalog & Manifest Registry
//! - DEL-258-02: Multi-Subnet Peer Routing Matrix & Trace Vectors
//! - INV-258-01: Schema Conformance Witness
//! - INV-258-02: Deterministic Routing Fallback
//! - DOD-258-01: Capability Determinism (BLAKE3-hashed MCard manifest)

use std::collections::{BTreeMap, HashMap};
use serde::{Deserialize, Serialize};
use crate::mesh::noise::{blake3_digest, SovereignNodeIdentity};

pub const PKC_SERVICE_PREFIX: &str = "service.pkc.";
pub const PKC_SERVICE_MDNS_TYPE: &str = "_pkc-service._tcp.local.";
pub const PKC_CAPABILITY_MIME_TYPE: &str = crate::layer0::vocabulary_types::MIME_APPLICATION_X_CLM_CAPABILITY_JSON;

// ── Types & Specifications ──────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PropertySchema {
    #[serde(rename = "type")]
    pub prop_type: String,
    #[serde(default)]
    pub required: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SchemaSpec {
    #[serde(rename = "type")]
    pub schema_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<BTreeMap<String, PropertySchema>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub polynomial_order: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SlaWitness {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_window: Option<u32>,
    pub compute_type: String,
    pub p95_latency_ms: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub throughput_tps: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reliability_score: Option<f64>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PricingSpec {
    pub base_cost: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cost_per_token: Option<f64>,
    pub currency: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceEndpoint {
    pub protocol: String,
    pub address: String,
    pub port: u16,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub noise_pubkey_hex: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServiceCapabilityManifest {
    pub service_id: String,
    pub version: String,
    pub provider_did: String,
    pub description: String,
    pub input_schema: SchemaSpec,
    pub output_schema: SchemaSpec,
    pub sla: SlaWitness,
    pub pricing: PricingSpec,
    pub endpoints: Vec<ServiceEndpoint>,
    pub registered_at: u64,
    pub ttl_seconds: u64,
    pub content_hash: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

// ── Validation & Canonicalization ───────────────────────────────────────────

pub fn is_valid_service_id(service_id: &str) -> bool {
    if !service_id.starts_with(PKC_SERVICE_PREFIX) {
        return false;
    }
    let parts: Vec<&str> = service_id[PKC_SERVICE_PREFIX.len()..].split('.').collect();
    parts.len() >= 2 && parts.iter().all(|p| !p.is_empty() && p.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-'))
}

#[derive(Serialize)]
struct CanonicalManifest<'a> {
    description: &'a str,
    endpoints: &'a [ServiceEndpoint],
    input_schema: &'a SchemaSpec,
    output_schema: &'a SchemaSpec,
    pricing: &'a PricingSpec,
    provider_did: &'a str,
    registered_at: u64,
    service_id: &'a str,
    sla: &'a SlaWitness,
    ttl_seconds: u64,
    version: &'a str,
}

pub fn canonicalize_manifest(manifest: &ServiceCapabilityManifest) -> String {
    let canonical = CanonicalManifest {
        description: &manifest.description,
        endpoints: &manifest.endpoints,
        input_schema: &manifest.input_schema,
        output_schema: &manifest.output_schema,
        pricing: &manifest.pricing,
        provider_did: &manifest.provider_did,
        registered_at: manifest.registered_at,
        service_id: &manifest.service_id,
        sla: &manifest.sla,
        ttl_seconds: manifest.ttl_seconds,
        version: &manifest.version,
    };
    serde_json::to_string(&canonical).unwrap_or_default()
}

pub fn compute_manifest_hash(manifest: &ServiceCapabilityManifest) -> String {
    let canonical = canonicalize_manifest(manifest);
    let digest = blake3_digest(canonical.as_bytes());
    hex::encode(digest)
}

pub fn sign_capability_manifest(
    mut manifest: ServiceCapabilityManifest,
    identity: &SovereignNodeIdentity,
) -> Result<ServiceCapabilityManifest, String> {
    if !is_valid_service_id(&manifest.service_id) {
        return Err(format!("Invalid service identifier '{}'", manifest.service_id));
    }
    manifest.provider_did = identity.did.clone();
    let content_hash = compute_manifest_hash(&manifest);
    let hash_bytes = hex::decode(&content_hash).map_err(|e| e.to_string())?;
    let sig_bytes = identity.sign(&hash_bytes);
    let signature = bs58::encode(sig_bytes).into_string();

    manifest.content_hash = content_hash;
    manifest.signature = Some(signature);
    Ok(manifest)
}

pub fn verify_capability_manifest(manifest: &ServiceCapabilityManifest) -> bool {
    if !is_valid_service_id(&manifest.service_id) {
        return false;
    }
    let expected_hash = compute_manifest_hash(manifest);
    if expected_hash != manifest.content_hash {
        return false;
    }

    if let Some(ref sig_b58) = manifest.signature {
        let pubkey_bytes = match SovereignNodeIdentity::did_to_public_key(&manifest.provider_did) {
            Ok(pk) => pk,
            Err(_) => return false,
        };
        let hash_bytes = match hex::decode(&manifest.content_hash) {
            Ok(hb) => hb,
            Err(_) => return false,
        };
        let sig_vec = match bs58::decode(sig_b58).into_vec() {
            Ok(v) => v,
            Err(_) => return false,
        };
        if sig_vec.len() != 64 {
            return false;
        }
        let mut sig_arr = [0u8; 64];
        sig_arr.copy_from_slice(&sig_vec);
        return SovereignNodeIdentity::verify_signature(&pubkey_bytes, &hash_bytes, &sig_arr);
    }
    true
}

// ── Routing Matrix & Merkle Trace Vector ─────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouteTier {
    Local,
    Lan,
    Overlay,
}

#[derive(Debug, Clone)]
pub struct RoutingCandidate {
    pub manifest: ServiceCapabilityManifest,
    pub tier: RouteTier,
    pub composite_score: f64,
    pub effective_latency_ms: u32,
    pub reliability: f64,
    pub cost: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingTraceHop {
    pub node_did: String,
    pub timestamp: u64,
    pub hop_hash: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingTraceVector {
    pub trace_id: String,
    pub origin_did: String,
    pub hops: Vec<RoutingTraceHop>,
}

pub fn create_trace_vector(origin_did: &str, trace_id: Option<String>) -> RoutingTraceVector {
    let id = trace_id.unwrap_or_else(|| format!("trace_{}", uuid::Uuid::new_v4()));
    let initial_data = format!("{}:{}", id, origin_did);
    let initial_hash = hex::encode(blake3_digest(initial_data.as_bytes()));

    RoutingTraceVector {
        trace_id: id,
        origin_did: origin_did.to_string(),
        hops: vec![RoutingTraceHop {
            node_did: origin_did.to_string(),
            timestamp: 0,
            hop_hash: initial_hash,
        }],
    }
}

pub fn append_trace_hop(vector: &mut RoutingTraceVector, node_did: &str, timestamp: u64) {
    let prev_hash = vector.hops.last().map(|h| h.hop_hash.as_str()).unwrap_or("0");
    let hop_data = format!("{}:{}:{}", node_did, prev_hash, timestamp);
    let hop_hash = hex::encode(blake3_digest(hop_data.as_bytes()));

    vector.hops.push(RoutingTraceHop {
        node_did: node_did.to_string(),
        timestamp,
        hop_hash,
    });
}

pub fn detect_routing_loop(vector: &RoutingTraceVector, target_node_did: &str) -> bool {
    vector.hops.iter().any(|h| h.node_did == target_node_did)
}

// ── Service Telemetry & Catalog ─────────────────────────────────────────────

#[derive(Debug, Clone)]
pub struct ServiceTelemetry {
    pub last_seen: u64,
    pub latency_ms: u32,
    pub success_count: u32,
    pub error_count: u32,
    pub reliability: f64,
}

pub struct ServiceCatalog {
    pub node_did: String,
    local_services: HashMap<String, ServiceCapabilityManifest>,
    remote_services: HashMap<String, HashMap<String, ServiceCapabilityManifest>>,
    telemetry: HashMap<String, ServiceTelemetry>,
}

impl ServiceCatalog {
    pub fn new(node_did: &str) -> Self {
        Self {
            node_did: node_did.to_string(),
            local_services: HashMap::new(),
            remote_services: HashMap::new(),
            telemetry: HashMap::new(),
        }
    }

    pub fn register_local_service(&mut self, manifest: ServiceCapabilityManifest) -> Result<(), String> {
        if !verify_capability_manifest(&manifest) {
            return Err(format!("Manifest for '{}' failed verification", manifest.service_id));
        }
        self.local_services.insert(manifest.service_id.clone(), manifest);
        Ok(())
    }

    pub fn register_remote_service(&mut self, manifest: ServiceCapabilityManifest) -> bool {
        if !verify_capability_manifest(&manifest) {
            return false;
        }
        let service_id = manifest.service_id.clone();
        let provider_did = manifest.provider_did.clone();

        self.telemetry.entry(provider_did.clone()).or_insert_with(|| ServiceTelemetry {
            last_seen: manifest.registered_at,
            latency_ms: manifest.sla.p95_latency_ms,
            success_count: 1,
            error_count: 0,
            reliability: manifest.sla.reliability_score.unwrap_or(1.0),
        });

        self.remote_services
            .entry(service_id)
            .or_default()
            .insert(provider_did, manifest);
        true
    }

    pub fn find_providers(&self, service_id: &str) -> Vec<ServiceCapabilityManifest> {
        let mut results = Vec::new();
        if let Some(local) = self.local_services.get(service_id) {
            results.push(local.clone());
        }
        if let Some(remotes) = self.remote_services.get(service_id) {
            for manifest in remotes.values() {
                results.push(manifest.clone());
            }
        }
        results
    }

    pub fn update_telemetry(&mut self, provider_did: &str, observed_latency_ms: u32, success: bool) {
        let cur = self.telemetry.entry(provider_did.to_string()).or_insert_with(|| ServiceTelemetry {
            last_seen: 0,
            latency_ms: observed_latency_ms,
            success_count: 0,
            error_count: 0,
            reliability: 1.0,
        });

        if success {
            cur.success_count += 1;
        } else {
            cur.error_count += 1;
        }
        let total = cur.success_count + cur.error_count;
        cur.reliability = if total > 0 { cur.success_count as f64 / total as f64 } else { 1.0 };
        cur.latency_ms = ((cur.latency_ms as f64 * 0.7) + (observed_latency_ms as f64 * 0.3)) as u32;
    }

    pub fn get_telemetry(&self, provider_did: &str) -> Option<&ServiceTelemetry> {
        self.telemetry.get(provider_did)
    }

    pub fn sweep_expired(&mut self, now: u64) -> Vec<String> {
        let mut evicted = Vec::new();
        for (service_id, providers) in self.remote_services.iter_mut() {
            providers.retain(|did, manifest| {
                let last_active = manifest.registered_at;
                let ttl_ms = manifest.ttl_seconds * 1000;
                if now.saturating_sub(last_active) > ttl_ms {
                    evicted.push(format!("{}@{}", service_id, did));
                    false
                } else {
                    true
                }
            });
        }
        self.remote_services.retain(|_, providers| !providers.is_empty());
        evicted
    }
}

// ── Service Router ──────────────────────────────────────────────────────────

pub struct ServiceRouter<'a> {
    pub catalog: &'a ServiceCatalog,
    pub this_node_did: String,
    pub weight_latency: f64,
    pub weight_cost: f64,
    pub weight_reliability: f64,
}

impl<'a> ServiceRouter<'a> {
    pub fn new(catalog: &'a ServiceCatalog) -> Self {
        Self {
            catalog,
            this_node_did: catalog.node_did.clone(),
            weight_latency: 0.5,
            weight_cost: 0.3,
            weight_reliability: 0.2,
        }
    }

    pub fn classify_tier(&self, manifest: &ServiceCapabilityManifest) -> RouteTier {
        if manifest.provider_did == self.this_node_did {
            return RouteTier::Local;
        }
        if let Some(ep) = manifest.endpoints.first() {
            let addr = ep.address.to_lowercase();
            if addr == "127.0.0.1" || addr == "localhost" || addr.ends_with(".local") || addr.starts_with("192.168.") || addr.starts_with("10.") {
                return RouteTier::Lan;
            }
        }
        RouteTier::Overlay
    }

    pub fn rank_candidates(&self, service_id: &str, trace: Option<&RoutingTraceVector>) -> Vec<RoutingCandidate> {
        let manifests = self.catalog.find_providers(service_id);
        let mut candidates = Vec::new();

        for manifest in manifests {
            if let Some(tr) = trace
                && detect_routing_loop(tr, &manifest.provider_did) {
                    continue;
                }

            let tier = self.classify_tier(&manifest);
            let tele = self.catalog.get_telemetry(&manifest.provider_did);
            let effective_latency = tele.map(|t| t.latency_ms).unwrap_or(manifest.sla.p95_latency_ms);
            let reliability = tele.map(|t| t.reliability).unwrap_or(manifest.sla.reliability_score.unwrap_or(1.0));
            let cost = manifest.pricing.base_cost;

            let tier_multiplier = match tier {
                RouteTier::Local => 0.4,
                RouteTier::Lan => 1.0,
                RouteTier::Overlay => 1.6,
            };

            let normalized_lat = effective_latency as f64 / 100.0;
            let score = tier_multiplier * (self.weight_latency * normalized_lat + self.weight_cost * cost)
                - self.weight_reliability * (reliability * 10.0);

            candidates.push(RoutingCandidate {
                manifest,
                tier,
                composite_score: score,
                effective_latency_ms: effective_latency,
                reliability,
                cost,
            });
        }

        candidates.sort_by(|a, b| a.composite_score.partial_cmp(&b.composite_score).unwrap_or(std::cmp::Ordering::Equal));
        candidates
    }

    pub fn select_best_route(&self, service_id: &str, trace: Option<&RoutingTraceVector>) -> Option<RoutingCandidate> {
        self.rank_candidates(service_id, trace).into_iter().next()
    }
}

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

#[cfg(test)]
#[path = "service_tests.rs"]
mod tests;