clm-kernel 0.0.2

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
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use rand::RngCore;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ObservabilityConfigRecord {
    pub tempo_endpoint: String,
    pub loki_endpoint: String,
    pub mimir_endpoint: String,
    pub sampling_rate: f64,
    pub handle: String,
    pub content_hash: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TraceSpanRecord {
    pub trace_id: String,
    pub span_id: String,
    pub parent_span_id: Option<String>,
    pub pcard_handle: String,
    pub vcard_hash: String,
    pub duration_ms: u64,
    pub timestamp: String,
    pub handle: String,
    pub content_hash: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MetricRecord {
    pub metric_name: String,
    pub value: f64,
    pub labels: serde_json::Value,
    pub timestamp: String,
    pub handle: String,
    pub content_hash: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct StructuredLogRecord {
    pub log_id: String,
    pub trace_id: String,
    pub level: String,
    pub vcard_hash: String,
    pub eoa_did: String,
    pub message: String,
    pub timestamp: String,
    pub handle: String,
    pub content_hash: String,
}

fn resolve_db_path(db_name_or_path: &str, clm_root: Option<&str>) -> PathBuf {
    if db_name_or_path.contains('/') || db_name_or_path.contains('\\') {
        PathBuf::from(db_name_or_path)
    } else {
        let root = clm_root.map(PathBuf::from).unwrap_or_else(|| {
            std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
        });
        root.join("data").join("execution_logs").join(db_name_or_path)
    }
}

fn init_db_tables(conn: &Connection) -> Result<(), String> {
    conn.execute(
        "CREATE TABLE IF NOT EXISTS card (
            hash TEXT PRIMARY KEY,
            content TEXT NOT NULL,
            g_time TEXT
        );",
        [],
    ).map_err(|e| e.to_string())?;

    conn.execute(
        "CREATE TABLE IF NOT EXISTS handle_registry (
            handle TEXT PRIMARY KEY,
            hash TEXT NOT NULL
        );",
        [],
    ).map_err(|e| e.to_string())?;

    Ok(())
}

fn generate_sha256(content: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(content.as_bytes());
    hex::encode(hasher.finalize())
}

/// Configures observability telemetry endpoints and stores configuration MCard (`mcard:observability/config`).
pub fn configure_observability(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    tempo_endpoint: &str,
    loki_endpoint: &str,
    mimir_endpoint: &str,
    sampling_rate: Option<f64>,
) -> Result<ObservabilityConfigRecord, String> {
    let db_path = resolve_db_path(db_name_or_path, clm_root);
    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    init_db_tables(&conn)?;

    let rate = sampling_rate.unwrap_or(1.0);
    let handle = "mcard:observability/config".to_string();

    let json_val = serde_json::json!({
        "type": "observability_config",
        "tempo_endpoint": tempo_endpoint,
        "loki_endpoint": loki_endpoint,
        "mimir_endpoint": mimir_endpoint,
        "sampling_rate": rate
    });

    let content_json = json_val.to_string();
    let content_hash = generate_sha256(&content_json);

    conn.execute(
        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
        rusqlite::params![content_hash, content_json],
    ).map_err(|e| e.to_string())?;

    conn.execute(
        "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
        rusqlite::params![handle, content_hash],
    ).map_err(|e| e.to_string())?;

    Ok(ObservabilityConfigRecord {
        tempo_endpoint: tempo_endpoint.to_string(),
        loki_endpoint: loki_endpoint.to_string(),
        mimir_endpoint: mimir_endpoint.to_string(),
        sampling_rate: rate,
        handle,
        content_hash,
    })
}

/// Emits an OpenTelemetry trace span and stores MCard (`mcard:observability/trace/{trace_id}`).
pub fn emit_trace_span(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    trace_id: &str,
    span_id: &str,
    parent_span_id: Option<&str>,
    pcard_handle: &str,
    vcard_hash: &str,
    duration_ms: u64,
) -> Result<TraceSpanRecord, String> {
    let db_path = resolve_db_path(db_name_or_path, clm_root);
    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    init_db_tables(&conn)?;

    let timestamp = chrono::Utc::now().to_rfc3339();
    let handle = format!("mcard:observability/trace/{}", trace_id);

    let json_val = serde_json::json!({
        "type": "trace_span",
        "trace_id": trace_id,
        "span_id": span_id,
        "parent_span_id": parent_span_id,
        "pcard_handle": pcard_handle,
        "vcard_hash": vcard_hash,
        "duration_ms": duration_ms,
        "timestamp": timestamp
    });

    let content_json = json_val.to_string();
    let content_hash = generate_sha256(&content_json);

    conn.execute(
        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
        rusqlite::params![content_hash, content_json],
    ).map_err(|e| e.to_string())?;

    conn.execute(
        "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
        rusqlite::params![handle, content_hash],
    ).map_err(|e| e.to_string())?;

    Ok(TraceSpanRecord {
        trace_id: trace_id.to_string(),
        span_id: span_id.to_string(),
        parent_span_id: parent_span_id.map(|s| s.to_string()),
        pcard_handle: pcard_handle.to_string(),
        vcard_hash: vcard_hash.to_string(),
        duration_ms,
        timestamp,
        handle,
        content_hash,
    })
}

/// Records a metric event and stores MCard (`mcard:observability/metric/{metric_name}`).
pub fn record_metric(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    metric_name: &str,
    value: f64,
    labels_json: Option<&str>,
) -> Result<MetricRecord, String> {
    let db_path = resolve_db_path(db_name_or_path, clm_root);
    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    init_db_tables(&conn)?;

    let timestamp = chrono::Utc::now().to_rfc3339();
    let handle = format!("mcard:observability/metric/{}", metric_name);
    let labels: serde_json::Value = match labels_json {
        Some(s) => serde_json::from_str(s).unwrap_or_else(|_| serde_json::json!({})),
        None => serde_json::json!({}),
    };

    let json_val = serde_json::json!({
        "type": "metric_event",
        "metric_name": metric_name,
        "value": value,
        "labels": labels,
        "timestamp": timestamp
    });

    let content_json = json_val.to_string();
    let content_hash = generate_sha256(&content_json);

    conn.execute(
        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
        rusqlite::params![content_hash, content_json],
    ).map_err(|e| e.to_string())?;

    conn.execute(
        "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
        rusqlite::params![handle, content_hash],
    ).map_err(|e| e.to_string())?;

    Ok(MetricRecord {
        metric_name: metric_name.to_string(),
        value,
        labels,
        timestamp,
        handle,
        content_hash,
    })
}

/// Emits a Loki-compatible structured log entry and stores MCard (`mcard:observability/log/{log_id}`).
pub fn emit_structured_log(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    trace_id: &str,
    level: &str,
    vcard_hash: &str,
    eoa_did: &str,
    message: &str,
) -> Result<StructuredLogRecord, String> {
    let db_path = resolve_db_path(db_name_or_path, clm_root);
    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    init_db_tables(&conn)?;

    let mut log_bytes = [0u8; 8];
    rand::thread_rng().fill_bytes(&mut log_bytes);
    let log_id = format!("log_{}", hex::encode(log_bytes));
    let handle = format!("mcard:observability/log/{}", log_id);
    let timestamp = chrono::Utc::now().to_rfc3339();

    let json_val = serde_json::json!({
        "type": "structured_log",
        "log_id": log_id,
        "trace_id": trace_id,
        "level": level,
        "vcard_hash": vcard_hash,
        "eoa_did": eoa_did,
        "message": message,
        "timestamp": timestamp
    });

    let content_json = json_val.to_string();
    let content_hash = generate_sha256(&content_json);

    conn.execute(
        "INSERT INTO card (hash, content) VALUES (?1, ?2) ON CONFLICT(hash) DO UPDATE SET content=excluded.content;",
        rusqlite::params![content_hash, content_json],
    ).map_err(|e| e.to_string())?;

    conn.execute(
        "INSERT INTO handle_registry (handle, hash) VALUES (?1, ?2) ON CONFLICT(handle) DO UPDATE SET hash=excluded.hash;",
        rusqlite::params![handle, content_hash],
    ).map_err(|e| e.to_string())?;

    Ok(StructuredLogRecord {
        log_id,
        trace_id: trace_id.to_string(),
        level: level.to_string(),
        vcard_hash: vcard_hash.to_string(),
        eoa_did: eoa_did.to_string(),
        message: message.to_string(),
        timestamp,
        handle,
        content_hash,
    })
}

/// Retrieves trace span MCard content by `trace_id`.
pub fn get_trace(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    trace_id: &str,
) -> Result<TraceSpanRecord, String> {
    let db_path = resolve_db_path(db_name_or_path, clm_root);
    if !db_path.exists() {
        return Err(format!("Database not found for trace {}", trace_id));
    }
    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    let handle = format!("mcard:observability/trace/{}", trace_id);

    let (content, content_hash): (String, String) = conn.query_row(
        "SELECT c.content, c.hash FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;",
        rusqlite::params![handle],
        |row| {
            let c: String = row.get(0)?;
            let h: String = row.get(1)?;
            Ok((c, h))
        },
    ).map_err(|_| format!("Trace span {} not found", trace_id))?;

    let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
    Ok(TraceSpanRecord {
        trace_id: v.get("trace_id").and_then(|x| x.as_str()).unwrap_or(trace_id).to_string(),
        span_id: v.get("span_id").and_then(|x| x.as_str()).unwrap_or("").to_string(),
        parent_span_id: v.get("parent_span_id").and_then(|x| x.as_str()).map(|x| x.to_string()),
        pcard_handle: v.get("pcard_handle").and_then(|x| x.as_str()).unwrap_or("").to_string(),
        vcard_hash: v.get("vcard_hash").and_then(|x| x.as_str()).unwrap_or("").to_string(),
        duration_ms: v.get("duration_ms").and_then(|x| x.as_u64()).unwrap_or(0),
        timestamp: v.get("timestamp").and_then(|x| x.as_str()).unwrap_or("").to_string(),
        handle,
        content_hash,
    })
}

/// Retrieves metric MCard content by `metric_name`.
pub fn get_metric(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    metric_name: &str,
) -> Result<MetricRecord, String> {
    let db_path = resolve_db_path(db_name_or_path, clm_root);
    if !db_path.exists() {
        return Err(format!("Database not found for metric {}", metric_name));
    }
    let conn = Connection::open(&db_path).map_err(|e| e.to_string())?;
    let handle = format!("mcard:observability/metric/{}", metric_name);

    let (content, content_hash): (String, String) = conn.query_row(
        "SELECT c.content, c.hash FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;",
        rusqlite::params![handle],
        |row| {
            let c: String = row.get(0)?;
            let h: String = row.get(1)?;
            Ok((c, h))
        },
    ).map_err(|_| format!("Metric {} not found", metric_name))?;

    let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
    Ok(MetricRecord {
        metric_name: v.get("metric_name").and_then(|x| x.as_str()).unwrap_or(metric_name).to_string(),
        value: v.get("value").and_then(|x| x.as_f64()).unwrap_or(0.0),
        labels: v.get("labels").cloned().unwrap_or_else(|| serde_json::json!({})),
        timestamp: v.get("timestamp").and_then(|x| x.as_str()).unwrap_or("").to_string(),
        handle,
        content_hash,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_observability_pipeline() {
        let db_path = "/tmp/test_observability.db";
        let _ = std::fs::remove_file(db_path);

        // 1. Configure observability
        let cfg = configure_observability(db_path, None, "http://localhost:4317", "http://localhost:3100", "http://localhost:9009", Some(1.0)).unwrap();
        assert_eq!(cfg.tempo_endpoint, "http://localhost:4317");

        // 2. Emit trace span
        let trace = emit_trace_span(db_path, None, "tr_001", "sp_001", None, "pcard:auth/verify", "0xhash123", 42).unwrap();
        assert_eq!(trace.trace_id, "tr_001");

        // 3. Query trace span
        let fetched_trace = get_trace(db_path, None, "tr_001").unwrap();
        assert_eq!(fetched_trace.duration_ms, 42);
        assert_eq!(fetched_trace.vcard_hash, "0xhash123");

        // 4. Record metric
        let metric = record_metric(db_path, None, "pkc_auth_success_total", 1.0, Some(r#"{"provider":"zitadel"}"#)).unwrap();
        assert_eq!(metric.metric_name, "pkc_auth_success_total");

        // 5. Query metric
        let fetched_metric = get_metric(db_path, None, "pkc_auth_success_total").unwrap();
        assert_eq!(fetched_metric.value, 1.0);

        // 6. Emit structured log
        let log_rec = emit_structured_log(db_path, None, "tr_001", "INFO", "0xhash123", "did:key:z6MkAgent", "Auth challenge verified").unwrap();
        assert_eq!(log_rec.level, "INFO");

        let _ = std::fs::remove_file(db_path);
    }
}