clm-kernel 0.0.12

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
#![allow(unused_imports)]
use super::*;

pub fn handle_register_batch(
    pillar: &str,
    clm_root: &str,
    handle: &str,
    hash_val: &str,
    content: &str,
) -> Result<()> {
    let now = crate::utils::now_iso8601();

    #[cfg(any(feature = "native", feature = "db"))]
    let created_at_opt = {
        if let Ok(writer_arc) = get_writer_connection(pillar, clm_root) {
            let mut conn = writer_arc
                .lock()
                .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
            let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
            {
                let mut stmt_card = tx.prepare_cached(
                    "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
                )?;
                stmt_card.execute(params![hash_val, content, now])?;

                let mut stmt_hist = tx.prepare_cached(
                    "INSERT INTO handle_history (handle, previous_hash, changed_at) \
                     SELECT hr.handle, hr.current_hash, ?1 FROM handle_registry hr \
                     JOIN card c ON c.hash = hr.current_hash \
                     WHERE hr.handle = ?2 AND hr.current_hash != ?3",
                )?;
                stmt_hist.execute(params![now, handle, hash_val])?;

                // ORC-23/27: `created_at` IS NOT A COLUMN. It is the FIRST history row for the
                // handle — which is exactly why the schema removed it. This function SELECTed
                // it and wrote it back, so it failed with "no such column: created_at" the
                // moment the column went. The kind of a fact does not decide where it lives;
                // the architecture does, and this one lives in the history.
                let mut stmt_reg = tx.prepare_cached(
                    "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) \
                     VALUES (?1, ?2, ?3)",
                )?;
                stmt_reg.execute(params![handle, hash_val, now])?;
            }
            // DERIVED, not stored — the same value the column used to hold.
            let created_at: String = tx
                .query_row(
                    "SELECT MIN(changed_at) FROM handle_history WHERE handle = ?1",
                    params![handle],
                    |row| row.get(0),
                )
                .unwrap_or_else(|_| now.clone());
            tx.commit()?;
            Some(created_at)
        } else {
            None
        }
    };

    #[cfg(not(any(feature = "native", feature = "db")))]
    let created_at_opt: Option<String> = None;

    let _created_at = if let Some(ca) = created_at_opt {
        ca
    } else {
        let mut conn = get_connection(pillar, clm_root)?;
        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
        {
            let mut stmt_card = tx.prepare_cached(
                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
            )?;
            stmt_card.execute(params![hash_val, content, now])?;

            let mut stmt_hist = tx.prepare_cached(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) \
                 SELECT hr.handle, hr.current_hash, ?1 FROM handle_registry hr \
                 JOIN card c ON c.hash = hr.current_hash \
                 WHERE hr.handle = ?2 AND hr.current_hash != ?3",
            )?;
            stmt_hist.execute(params![now, handle, hash_val])?;

            // ORC-23/27: three columns. `created_at` is the FIRST history row, not a column.
            let mut stmt_reg = tx.prepare_cached(
                "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) \
                 VALUES (?1, ?2, ?3)",
            )?;
            stmt_reg.execute(params![handle, hash_val, now])?;
        }
        // DERIVED, not stored — the same value the column used to hold.
        let created_at: String = tx
            .query_row(
                "SELECT MIN(changed_at) FROM handle_history WHERE handle = ?1",
                params![handle],
                |row| row.get(0),
            )
            .unwrap_or_else(|_| now.clone());
        tx.commit()?;
        created_at
    };

    // Sync to membroker if active
    if is_membroker_backend() {
        let esc_hash = hash_val.replace('\'', "''");
        let esc_content = content.replace('\'', "''");
        let esc_handle = handle.replace('\'', "''");
        let esc_now = now.replace('\'', "''");
        membroker_sync(pillar, &format!(
            "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES ('{}', '{}', '{}')",
            esc_hash, esc_content, esc_now
        ));
        membroker_sync(pillar, &format!(
            "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES ('{}', '{}', '{}')",
            esc_handle, esc_hash, esc_now
        ));
    }

    Ok(())
}

pub fn handle_delete_batch(pillar: &str, clm_root: &str, handle: &str) -> Result<()> {
    let now = crate::utils::now_iso8601();

    #[cfg(any(feature = "native", feature = "db"))]
    {
        if let Ok(writer_arc) = get_writer_connection(pillar, clm_root) {
            let mut conn = writer_arc
                .lock()
                .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
            let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
            {
                let mut stmt_hist = tx.prepare_cached(
                    "INSERT INTO handle_history (handle, previous_hash, changed_at) \
                     SELECT hr.handle, hr.current_hash, ?1 FROM handle_registry hr \
                     JOIN card c ON c.hash = hr.current_hash \
                     WHERE hr.handle = ?2",
                )?;
                stmt_hist.execute(params![now, handle])?;

                let mut stmt_del_hist = tx.prepare_cached("DELETE FROM handle_history WHERE handle = ?1")?;
                stmt_del_hist.execute(params![handle])?;

                let mut stmt_del = tx.prepare_cached("DELETE FROM handle_registry WHERE handle = ?1")?;
                stmt_del.execute(params![handle])?;
            }
            tx.commit()?;
            return Ok(());
        }
    }

    let mut conn = get_connection(pillar, clm_root)?;
    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
    {
        let mut stmt_hist = tx.prepare_cached(
            "INSERT INTO handle_history (handle, previous_hash, changed_at) \
             SELECT hr.handle, hr.current_hash, ?1 FROM handle_registry hr \
             JOIN card c ON c.hash = hr.current_hash \
             WHERE hr.handle = ?2",
        )?;
        stmt_hist.execute(params![now, handle])?;

        let mut stmt_del_hist = tx.prepare_cached("DELETE FROM handle_history WHERE handle = ?1")?;
        stmt_del_hist.execute(params![handle])?;

        let mut stmt_del = tx.prepare_cached("DELETE FROM handle_registry WHERE handle = ?1")?;
        stmt_del.execute(params![handle])?;
    }
    tx.commit()?;
    Ok(())
}

pub fn resolve_handle_hash(pillar: &str, clm_root: &str, handle: &str) -> Result<Option<String>> {
    #[cfg(any(feature = "native", feature = "db"))]
    {
        if let Ok(reader) = get_reader_connection(pillar, clm_root) {
            return resolve_handle_hash_cached(&reader, handle);
        }
    }
    let conn = get_connection(pillar, clm_root)?;
    resolve_handle_hash_cached(&conn, handle)
}

pub fn resolve_handle_content(
    pillar: &str,
    clm_root: &str,
    handle: &str,
) -> Result<Option<String>> {
    #[cfg(any(feature = "native", feature = "db"))]
    {
        if let Ok(reader) = get_reader_connection(pillar, clm_root) {
            return resolve_handle_content_cached(&reader, handle);
        }
    }
    let conn = get_connection(pillar, clm_root)?;
    resolve_handle_content_cached(&conn, handle)
}

pub fn card_exists(pillar: &str, clm_root: &str, hash: &str) -> Result<bool> {
    #[cfg(any(feature = "native", feature = "db"))]
    {
        if let Ok(reader) = get_reader_connection(pillar, clm_root) {
            return card_exists_cached(&reader, hash);
        }
    }
    let conn = get_connection(pillar, clm_root)?;
    card_exists_cached(&conn, hash)
}

pub fn setter_card_batch(
    pillar: &str,
    clm_root: &str,
    hash: &str,
    content: &str,
    g_time: &str,
) -> Result<()> {
    #[cfg(any(feature = "native", feature = "db"))]
    {
        if let Ok(writer_arc) = get_writer_connection(pillar, clm_root) {
            let conn = writer_arc
                .lock()
                .map_err(|e| ClmError::storage(StorageErrorCode::TransactionFailed, e.to_string()))?;
            let mut stmt = conn.prepare_cached(
                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
            )?;
            stmt.execute(params![hash, content, g_time])?;
            return Ok(());
        }
    }
    let conn = get_connection(pillar, clm_root)?;
    let mut stmt = conn.prepare_cached(
        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
    )?;
    stmt.execute(params![hash, content, g_time])?;
    Ok(())
}

pub fn emit_exec_mcard(
    operation: &str,
    content_hash: &str,
    extra_yaml: &str,
    a_hash: &str,
    c_hash: &str,
    clm_root: &str,
) -> Result<String> {
    let is_sandbox = TEST_SANDBOX_ACTIVE.with(|active| active.get());
    let zero_fs = is_sandbox || env::var("CLM_ZERO_FS").unwrap_or_default() == "true";
    let data_root = Path::new(clm_root).join("data");
    let mcard_dir = if zero_fs {
        let tmp_dir = env::var("TMPDIR").unwrap_or_else(|_| "/tmp".to_string());
        Path::new(&tmp_dir).join("data").join("execution_logs")
    } else {
        data_root.join("execution_logs")
    };

    if !zero_fs {
        let _ = fs::create_dir_all(&mcard_dir);
    }

    let now = chrono::Local::now();
    let g_time = now.format("%Y-%m-%dT%H:%M:%S%z").to_string();
    let unix_ts = now.timestamp();

    let short_hash = if content_hash.len() >= 8 {
        &content_hash[0..8]
    } else {
        content_hash
    };
    let mcard_file = mcard_dir.join(format!("exec_{}_{}.yaml", unix_ts, short_hash));

    // Construct MCard content YAML
    let mut mcard_content = format!(
        "mcard:\n  g_time: \"{}\"\n  content_hash: \"{}\"\n  operation: \"{}\"\n  agent_did: \"{}\"\n",
        g_time, content_hash, operation, env::var("ACTIVE_AGENT_DID").unwrap_or_default()
    );

    if !extra_yaml.is_empty() {
        for line in extra_yaml.lines() {
            mcard_content.push_str(&format!("  {}\n", line));
        }
    }

    if !a_hash.is_empty() || !c_hash.is_empty() {
        mcard_content.push_str("  source:\n");
        if !a_hash.is_empty() {
            mcard_content.push_str(&format!("    a_hash: \"{}\"\n", a_hash));
        }
        if !c_hash.is_empty() {
            mcard_content.push_str(&format!("    c_hash: \"{}\"\n", c_hash));
        }
        mcard_content.push_str(&format!("    operation: \"{}\"\n", operation));
        
        if let Ok(runtime_facts) = env::var("CLM_RUNTIME_FACTS")
            && !runtime_facts.is_empty() {
                mcard_content.push_str("    runtime_facts:\n");
                for line in runtime_facts.lines() {
                    mcard_content.push_str(&format!("      {}\n", line));
                }
            }
    } else {
        if let Ok(runtime_facts) = env::var("CLM_RUNTIME_FACTS")
            && !runtime_facts.is_empty() {
                mcard_content.push_str("  runtime_facts:\n");
                for line in runtime_facts.lines() {
                    mcard_content.push_str(&format!("    {}\n", line));
                }
            }
    }

    if !zero_fs {
        fs::write(&mcard_file, &mcard_content)?;
    }

    // Write to execution_log.db using writer connection or fallback
    #[cfg(any(feature = "native", feature = "db"))]
    let write_done = {
        if let Ok(writer_arc) = get_writer_connection("execution_log", clm_root) {
            if let Ok(conn) = writer_arc.lock() {
                let mut retry_count = 0;
                loop {
                    match conn.prepare_cached(
                        "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
                    ) {
                        Ok(mut stmt) => match stmt.execute(params![content_hash, &mcard_content, &g_time]) {
                            Ok(_) => break true,
                            Err(e) if retry_count < 10 && e.to_string().contains("locked") => {
                                retry_count += 1;
                                std::thread::sleep(std::time::Duration::from_millis(50 * retry_count));
                            }
                            Err(e) => {
                                eprintln!("[DB EMIT_EXEC_MCARD] Writer execute failed: {}", e);
                                break false;
                            }
                        },
                        Err(e) if retry_count < 10 && e.to_string().contains("locked") => {
                            retry_count += 1;
                            std::thread::sleep(std::time::Duration::from_millis(50 * retry_count));
                        }
                        Err(_) => break false,
                    }
                }
            } else {
                false
            }
        } else {
            false
        }
    };
    #[cfg(not(any(feature = "native", feature = "db")))]
    let write_done = false;

    if !write_done {
        let mut retry_count = 0;
        loop {
            match get_connection("execution_log", clm_root) {
                Ok(conn) => match conn.prepare_cached(
                    "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
                ) {
                    Ok(mut stmt) => match stmt.execute(params![content_hash, &mcard_content, &g_time]) {
                        Ok(_) => break,
                        Err(e) if retry_count < 10 && e.to_string().contains("locked") => {
                            retry_count += 1;
                            std::thread::sleep(std::time::Duration::from_millis(50 * retry_count));
                        }
                        Err(e) => return Err(ClmError::from(e)),
                    },
                    Err(e) if retry_count < 10 && e.to_string().contains("locked") => {
                        retry_count += 1;
                        std::thread::sleep(std::time::Duration::from_millis(50 * retry_count));
                    }
                    Err(e) => return Err(ClmError::from(e)),
                },
                Err(e) if retry_count < 10 && e.to_string().contains("locked") => {
                    retry_count += 1;
                    std::thread::sleep(std::time::Duration::from_millis(50 * retry_count));
                }
                Err(e) => return Err(e),
            }
        }
    }

    // Sync execution MCard to membroker (only active in Zero-FS mode)
    let esc_mcard = mcard_content.replace('\'', "''");
    let esc_gtime = g_time.replace('\'', "''");
    membroker_sync("execution_log", &format!(
        "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES ('{}', '{}', '{}')",
        content_hash, esc_mcard, esc_gtime
    ));

    Ok(mcard_file.to_string_lossy().to_string())
}

pub fn get_card_content(pillar: &str, clm_root: &str, hash: &str) -> Result<Option<String>> {
    #[cfg(any(feature = "native", feature = "db"))]
    {
        if let Ok(reader) = get_reader_connection(pillar, clm_root) {
            return get_card_cached(&reader, hash);
        }
    }
    let conn = get_connection(pillar, clm_root)?;
    get_card_cached(&conn, hash)
}

pub fn backup_db(pillar: &str, clm_root: &str) -> Result<Connection> {
    let src = get_connection(pillar, clm_root)?;
    let mut dst = Connection::open_in_memory()?;
    {
        let backup = rusqlite::backup::Backup::new(&src, &mut dst)?;
        backup.run_to_completion(10_000, std::time::Duration::ZERO, None)?;
    }
    Ok(dst)
}

pub fn restore_db(pillar: &str, clm_root: &str, backup_conn: &Connection) -> Result<()> {
    let mut dst = get_connection(pillar, clm_root)?;
    {
        let backup = rusqlite::backup::Backup::new(backup_conn, &mut dst)?;
        backup.run_to_completion(10_000, std::time::Duration::ZERO, None)?;
    }
    Ok(())
}

/// Offloads synchronous blocking database operations from Tokio worker threads
/// to Tokio's dedicated thread pool, protecting the Satori event loop from starvation.
#[cfg(any(feature = "native", all(feature = "db", feature = "async")))]
pub async fn query_db_async<F, R>(f: F) -> Result<R>
where
    F: FnOnce() -> Result<R> + Send + 'static,
    R: Send + 'static,
{
    tokio::task::spawn_blocking(f)
        .await
        .map_err(|join_err| ClmError::Storage(crate::error::StorageErrorCode::QueryFailed, format!("Tokio worker join error: {}", join_err)))?
}