clm-kernel 0.0.6

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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
use std::env;
use std::fs;
use std::io::{Read, Write};
use std::net::{TcpStream, Shutdown};
use std::path::{Path, PathBuf};
use std::time::Duration;
use rusqlite::{params, Connection};
use std::cell::RefCell;
use std::collections::HashMap;
use crate::error::{ClmError, StorageErrorCode, Result};

thread_local! {
    pub static TEST_SANDBOX_ACTIVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    pub static TEST_SANDBOX_DB_ID: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
    pub static TEST_SANDBOX_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    static IN_MEMORY_CONNS: RefCell<HashMap<String, Connection>> = RefCell::new(HashMap::new());
}

pub fn clear_in_memory_connections() {
    IN_MEMORY_CONNS.with(|conns| conns.borrow_mut().clear());
}

/// Canonical MCard schema (v3.0.3) embedded at compile-time as single source of truth (SSOT).
pub const CANONICAL_SCHEMA: &str = include_str!("../types/schemas/mcard_schema.sql");

#[cfg(any(feature = "native", feature = "db"))]
use std::sync::{Arc, Mutex, OnceLock};
#[cfg(any(feature = "native", feature = "db"))]
use r2d2::Pool;
#[cfg(any(feature = "native", feature = "db"))]
use r2d2_sqlite::SqliteConnectionManager;

#[cfg(any(feature = "native", feature = "db"))]
pub mod migrations;

#[cfg(any(feature = "native", feature = "db"))]
pub mod compaction;

/// High-Concurrency Dual-Pool SQLite Manager.
///
/// Provides a dedicated single writer connection alongside an `r2d2` multi-reader
/// connection pool configured with WAL mode, normal synchronous mode, and busy timeouts.
#[cfg(any(feature = "native", feature = "db"))]
#[derive(Clone)]
pub struct DbPillarPool {
    writer: Arc<Mutex<Connection>>,
    reader_pool: Pool<SqliteConnectionManager>,
    db_path: PathBuf,
}

#[cfg(any(feature = "native", feature = "db"))]
impl DbPillarPool {
    /// Initializes a dual-pool manager for the given pillar database path.
    pub fn new(pillar: &str, clm_root: &str) -> Result<Self> {
        let normalized = get_pillar_filename(pillar);
        let db_path = get_db_path(&normalized, clm_root);
        let db_path_str = db_path.to_string_lossy();

        if !db_path_str.starts_with("file:")
            && let Some(parent) = db_path.parent() {
                let _ = fs::create_dir_all(parent);
            }

        #[cfg(unix)]
        if !db_path_str.starts_with("file:") {
            use std::os::unix::fs::PermissionsExt;
            if let Ok(meta) = fs::metadata(&db_path) {
                let current_mode = meta.permissions().mode();
                if current_mode & 0o200 == 0 {
                    let mut perms = meta.permissions();
                    perms.set_mode(current_mode | 0o664);
                    let _ = fs::set_permissions(&db_path, perms);
                }
            }
            for ext in &["-shm", "-wal"] {
                let aux_path = format!("{}{}", db_path.display(), ext);
                if let Ok(meta) = fs::metadata(&aux_path) {
                    let current_mode = meta.permissions().mode();
                    if current_mode & 0o200 == 0 {
                        let mut perms = meta.permissions();
                        perms.set_mode(current_mode | 0o664);
                        let _ = fs::set_permissions(&aux_path, perms);
                    }
                }
            }
        }

        // 1. Initialize Writer Connection with WAL pragma & run migrations
        let mut writer_conn = Connection::open_with_flags(
            &db_path,
            rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE
                | rusqlite::OpenFlags::SQLITE_OPEN_CREATE
                | rusqlite::OpenFlags::SQLITE_OPEN_URI,
        )?;
        writer_conn.busy_timeout(std::time::Duration::from_millis(5000))?;
        let _ = writer_conn.pragma_update(None, "journal_mode", "WAL");
        let _ = writer_conn.pragma_update(None, "synchronous", "NORMAL");
        let _ = writer_conn.pragma_update(None, "foreign_keys", "ON");

        // Apply versioned schema migrations on the writer connection
        let _ = migrations::apply_migrations(&mut writer_conn, &normalized);

        // 2. Initialize Reader Pool
        let manager = SqliteConnectionManager::file(&db_path)
            .with_flags(
                rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE
                    | rusqlite::OpenFlags::SQLITE_OPEN_CREATE
                    | rusqlite::OpenFlags::SQLITE_OPEN_URI,
            )
            .with_init(|conn| {
                let _ = conn.busy_timeout(std::time::Duration::from_millis(5000));
                let _ = conn.pragma_update(None, "journal_mode", "WAL");
                let _ = conn.pragma_update(None, "synchronous", "NORMAL");
                let _ = conn.pragma_update(None, "query_only", true);
                Ok(())
            });

        let reader_pool = Pool::builder()
            .max_size(16)
            .min_idle(Some(2))
            .connection_timeout(std::time::Duration::from_millis(5000))
            .build(manager)
            .map_err(|e| {
                ClmError::storage(
                    StorageErrorCode::DatabaseUnavailable,
                    format!("Failed to build SQLite reader connection pool for {}: {}", normalized, e),
                )
            })?;

        Ok(Self {
            writer: Arc::new(Mutex::new(writer_conn)),
            reader_pool,
            db_path,
        })
    }

    /// Returns an `Arc<Mutex<Connection>>` handle to the dedicated writer connection.
    pub fn writer(&self) -> Arc<Mutex<Connection>> {
        self.writer.clone()
    }

    /// Acquires a connection from the multi-reader pool without locking the writer.
    pub fn reader(&self) -> Result<r2d2::PooledConnection<SqliteConnectionManager>> {
        self.reader_pool.get().map_err(|e| {
            ClmError::storage(
                StorageErrorCode::DatabaseUnavailable,
                format!("Failed to acquire connection from reader pool: {}", e),
            )
        })
    }

    /// Returns the underlying database path or URI.
    pub fn db_path(&self) -> &Path {
        &self.db_path
    }
}

#[cfg(any(feature = "native", feature = "db"))]
static SHARED_POOLS: OnceLock<dashmap::DashMap<String, Arc<DbPillarPool>>> = OnceLock::new();

#[cfg(any(feature = "native", feature = "db"))]
static SHARED_CONNECTIONS: OnceLock<dashmap::DashMap<String, Arc<Mutex<Connection>>>> = OnceLock::new();

#[cfg(any(feature = "native", feature = "db"))]
pub fn get_pillar_pool(pillar: &str, clm_root: &str) -> Result<Arc<DbPillarPool>> {
    let normalized = get_pillar_filename(pillar);
    let db_path = get_db_path(&normalized, clm_root);
    let key = format!("{}:{}", normalized, db_path.to_string_lossy());
    let map = SHARED_POOLS.get_or_init(dashmap::DashMap::new);
    if let Some(entry) = map.get(&key) {
        return Ok(entry.clone());
    }
    let pool = Arc::new(DbPillarPool::new(&normalized, clm_root)?);
    map.insert(key, pool.clone());
    Ok(pool)
}

#[cfg(any(feature = "native", feature = "db"))]
pub fn get_writer_connection(pillar: &str, clm_root: &str) -> Result<Arc<Mutex<Connection>>> {
    let pool = get_pillar_pool(pillar, clm_root)?;
    Ok(pool.writer())
}

#[cfg(any(feature = "native", feature = "db"))]
pub fn get_reader_connection(pillar: &str, clm_root: &str) -> Result<r2d2::PooledConnection<SqliteConnectionManager>> {
    let pool = get_pillar_pool(pillar, clm_root)?;
    pool.reader()
}

#[cfg(any(feature = "native", feature = "db"))]
pub fn get_shared_connection(pillar: &str, clm_root: &str) -> std::result::Result<Arc<Mutex<Connection>>, String> {
    get_writer_connection(pillar, clm_root).map_err(|e| e.to_string())
}

#[cfg(any(feature = "native", feature = "db"))]
pub fn clear_shared_connections() {
    if let Some(map) = SHARED_CONNECTIONS.get() {
        map.clear();
    }
    if let Some(pools) = SHARED_POOLS.get() {
        pools.clear();
    }
}

pub fn set_sandbox_depth(depth: usize) {
    TEST_SANDBOX_DEPTH.with(|d| d.set(depth));
}

pub fn thread_local_depth_get() -> usize {
    TEST_SANDBOX_DEPTH.with(|d| d.get())
}

pub fn thread_local_depth_increment() -> usize {
    TEST_SANDBOX_DEPTH.with(|d| {
        let c = d.get() + 1;
        d.set(c);
        c
    })
}

pub fn thread_local_depth_decrement() {
    TEST_SANDBOX_DEPTH.with(|d| {
        let c = d.get();
        if c > 0 {
            d.set(c - 1);
        }
    })
}

pub struct DatabaseSandboxGuard {
    prev_active: bool,
    prev_db_id: Option<String>,
}

impl DatabaseSandboxGuard {
    pub fn activate(db_id: &str) -> Self {
        let prev_active = TEST_SANDBOX_ACTIVE.with(|active| active.get());
        let prev_db_id = TEST_SANDBOX_DB_ID.with(|id| id.borrow().clone());
        
        TEST_SANDBOX_ACTIVE.with(|active| active.set(true));
        TEST_SANDBOX_DB_ID.with(|id| {
            *id.borrow_mut() = Some(db_id.to_string());
        });
        
        DatabaseSandboxGuard {
            prev_active,
            prev_db_id,
        }
    }
}

impl Drop for DatabaseSandboxGuard {
    fn drop(&mut self) {
        TEST_SANDBOX_ACTIVE.with(|active| active.set(self.prev_active));
        TEST_SANDBOX_DB_ID.with(|id| {
            *id.borrow_mut() = self.prev_db_id.clone();
        });
        clear_in_memory_connections();
    }
}


pub fn get_db_path(pillar: &str, clm_root: &str) -> PathBuf {
    if env::var("CLM_MEM_TRIDB").unwrap_or_default() == "1" {
        return PathBuf::from(format!("file:memdb_{}?mode=memory&cache=shared", get_pillar_filename(pillar)));
    }
    let is_sandbox = TEST_SANDBOX_ACTIVE.with(|active| active.get());
    if is_sandbox {
        let db_id = TEST_SANDBOX_DB_ID.with(|id| {
            id.borrow().clone().unwrap_or_else(|| {
                format!("{:?}", std::thread::current().id())
            })
        });
        let depth = TEST_SANDBOX_DEPTH.with(|d| d.get());
        let depth_suffix = if depth > 0 { format!("_depth_{}", depth) } else { "".to_string() };
        PathBuf::from(format!("file:memdb_{}_{}{}?mode=memory&cache=shared", get_pillar_filename(pillar), db_id, depth_suffix))
    } else {
        let zero_fs = crate::utils::is_zero_fs();
        if zero_fs {
            let snap_dir = env::var("CLM_MEMBROKER_SNAP_DIR")
                .unwrap_or_else(|_| "/tmp".to_string());
            let snap_path = if cfg!(windows) && (snap_dir == "/tmp" || snap_dir == "\\tmp") {
                std::env::temp_dir()
            } else {
                PathBuf::from(&snap_dir)
            };
            snap_path.join(format!("{}.db", get_pillar_filename(pillar)))
        } else {
            let fname = get_pillar_filename(pillar);
            let db_dir = Path::new(clm_root).join("db");
            let target_path = db_dir.join(format!("{}.db", fname));
            // Backward-compatibility: if mcard_state requested but content_memory.db exists, fall back
            if fname == "mcard_state" && !target_path.exists() && db_dir.join("content_memory.db").exists() {
                db_dir.join("content_memory.db")
            } else if fname == "sovereign_identity" && !target_path.exists() && db_dir.join("agent_identities.db").exists() {
                db_dir.join("agent_identities.db")
            } else {
                target_path
            }
        }
    }
}

fn get_pillar_filename(pillar: &str) -> String {
    match pillar {
        "mcard_state" | "mcard_state.db" => "mcard_state".to_string(),
        "sovereign_identity" | "sovereign_identity.db" => "sovereign_identity".to_string(),
        "agent_identity" | "agent_identities" => "agent_identities".to_string(),
        "content_memory" | "content" | "memory" => "content_memory".to_string(),
        "execution_log" | "execution" | "log" => "execution_log".to_string(),
        "evolution" | "evol" => {
            let now = chrono::Local::now();
            let iso_week = chrono::Datelike::iso_week(&now);
            format!("pkc_evol_{:04}_w{:02}", iso_week.year(), iso_week.week())
        }
        _ => "content_memory".to_string(),
    }
}

/// Check if the membroker backend is active (CLM_DB_BACKEND=membroker and CLM_ZERO_FS=true).
pub fn is_membroker_backend() -> bool {
    env::var("CLM_DB_BACKEND").unwrap_or_default() == "membroker"
        && crate::utils::is_zero_fs()
}

/// Send a SQL statement to the Python membroker via TCP (framed CLMQ protocol).
/// Returns the response body on success.
pub fn membroker_send(pillar: &str, sql: &str) -> Result<String> {
    let port: u16 = env::var("CLM_MEMBROKER_PORT")
        .unwrap_or_else(|_| "43740".to_string())
        .parse()
        .unwrap_or(43740);

    let addr = format!("127.0.0.1:{}", port);
    let timeout = Duration::from_secs(5);
    let socket_addr: std::net::SocketAddr = addr
        .parse()
        .map_err(|e| ClmError::Evaluation(format!("Invalid membroker address: {}", e)))?;

    let mut stream = TcpStream::connect_timeout(&socket_addr, timeout)
        .map_err(|e| ClmError::Evaluation(format!("membroker connect failed: {}", e)))?;
    stream.set_read_timeout(Some(timeout))?;
    stream.set_write_timeout(Some(timeout))?;

    let body = sql.as_bytes();
    let header = format!("CLMQ\t{}\t{}\t\n", pillar, body.len());
    stream.write_all(header.as_bytes())?;
    stream.write_all(body)?;
    stream.shutdown(Shutdown::Write)?;

    let mut response = Vec::new();
    stream.read_to_end(&mut response)?;
    let resp_str = String::from_utf8_lossy(&response);

    if resp_str.starts_with("CLMR\tOK\t") {
        if let Some(pos) = resp_str.find('\n') {
            Ok(resp_str[pos + 1..].to_string())
        } else {
            Ok(String::new())
        }
    } else {
        Err(ClmError::Evaluation(format!("membroker error: {}", resp_str)))
    }
}

/// Sync a single INSERT/REPLACE statement to the membroker if the backend is active.
/// Silently skips if membroker is not available or not in use.
pub fn membroker_sync(pillar: &str, sql: &str) {
    if !is_membroker_backend() {
        return;
    }
    let _ = membroker_send(pillar, sql);
}

pub fn get_connection(pillar: &str, clm_root: &str) -> Result<Connection> {
    let db_path = get_db_path(pillar, clm_root);
    // Ensure parent dir exists (only if not in-memory URI starting with file:)
    let db_path_str = db_path.to_string_lossy();
    if !db_path_str.starts_with("file:") {
        if let Some(parent) = db_path.parent() {
            let _ = fs::create_dir_all(parent);
        }
    } else {
        // Shared memory database. Cache connection in thread-local to ensure persistence
        let path_str = db_path_str.to_string();
        let already_registered = IN_MEMORY_CONNS.with(|conns| conns.borrow().contains_key(&path_str));
        if !already_registered
            && let Ok(keep_alive_conn) = Connection::open_with_flags(
                &db_path,
                rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE
                    | rusqlite::OpenFlags::SQLITE_OPEN_CREATE
                    | rusqlite::OpenFlags::SQLITE_OPEN_URI,
            ) {
                let _ = keep_alive_conn.busy_timeout(std::time::Duration::from_millis(10000));
                let _ = keep_alive_conn.pragma_update(None, "journal_mode", "WAL");
                let _ = keep_alive_conn.pragma_update(None, "synchronous", "NORMAL");

                let table_exists: bool = keep_alive_conn
                    .query_row(
                        "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='card';",
                        [],
                        |row| row.get(0),
                    )
                    .unwrap_or(0) > 0;
                if !table_exists {
                    let project_path = Path::new(clm_root);
                    let mut schema_file = project_path.join("types").join("schemas").join("mcard_schema.sql");
                    if !schema_file.exists() {
                        schema_file = project_path.join("schema").join("mcard_schema.sql");
                    }
                    if !schema_file.exists() {
                        schema_file = project_path.join("..").join("schema").join("mcard_schema.sql");
                    }
                    if schema_file.exists()
                        && let Ok(schema_sql) = fs::read_to_string(&schema_file) {
                            let sql_to_use = if schema_sql.contains("CREATE TABLE") {
                                &schema_sql
                            } else {
                                CANONICAL_SCHEMA
                            };
                            let _ = keep_alive_conn.execute_batch(sql_to_use);
                        }
                    let _ = keep_alive_conn.execute("ALTER TABLE card ADD COLUMN g_time TEXT;", []);
                }
                IN_MEMORY_CONNS.with(|conns| {
                    conns.borrow_mut().insert(path_str, keep_alive_conn);
                });
            }
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(meta) = fs::metadata(&db_path) {
            let current_mode = meta.permissions().mode();
            if current_mode & 0o200 == 0 {
                let mut perms = meta.permissions();
                perms.set_mode(current_mode | 0o664);
                let _ = fs::set_permissions(&db_path, perms);
            }
        }
        for ext in &["-shm", "-wal"] {
            let aux_path = format!("{}{}", db_path.display(), ext);
            if let Ok(meta) = fs::metadata(&aux_path) {
                let current_mode = meta.permissions().mode();
                if current_mode & 0o200 == 0 {
                    let mut perms = meta.permissions();
                    perms.set_mode(current_mode | 0o664);
                    let _ = fs::set_permissions(&aux_path, perms);
                }
            }
        }
    }

    let conn = Connection::open_with_flags(
        &db_path,
        rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE
            | rusqlite::OpenFlags::SQLITE_OPEN_CREATE
            | rusqlite::OpenFlags::SQLITE_OPEN_URI,
    )?;
    // Enable busy timeout to avoid lock contention
    conn.busy_timeout(std::time::Duration::from_millis(10000))?;

    // Enable WAL mode and normal synchronous mode persistently on the connection
    let _ = conn.pragma_update(None, "journal_mode", "WAL");
    let _ = conn.pragma_update(None, "synchronous", "NORMAL");

    // Check if the card table exists, if not, auto-initialize from schema
    let table_exists: bool = conn
        .query_row(
            "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='card';",
            [],
            |row| row.get(0),
        )
        .unwrap_or(0) > 0;
    if !table_exists {
        let _ = conn.execute_batch(CANONICAL_SCHEMA);
    }

    let _ = conn.execute("ALTER TABLE card ADD COLUMN g_time TEXT;", []);
    Ok(conn)
}

pub fn init_tridb(clm_root: &str) -> Result<()> {
    let project_path = Path::new(clm_root);
    let mut schema_file = project_path.join("types").join("schemas").join("mcard_schema.sql");
    if !schema_file.exists() {
        schema_file = project_path.join("..").join("types").join("schemas").join("mcard_schema.sql");
    }

    let schema_sql = if schema_file.exists() {
        let content = fs::read_to_string(&schema_file).unwrap_or_else(|_| CANONICAL_SCHEMA.to_string());
        if content.contains("CREATE TABLE") {
            content
        } else {
            CANONICAL_SCHEMA.to_string()
        }
    } else {
        CANONICAL_SCHEMA.to_string()
    };

    let mut version = "unknown".to_string();
    for line in schema_sql.lines() {
        if line.contains("Version:") {
            if let Some(pos) = line.find("Version:") {
                let suffix = &line[pos + 8..].trim();
                let parts: Vec<&str> = suffix.split_whitespace().collect();
                if !parts.is_empty() {
                    version = parts[0].trim_matches(|c: char| !c.is_numeric() && c != '.').to_string();
                }
            }
            break;
        }
    }

    eprintln!("[INIT_TRIDB] Canonical Schema: {}", schema_file.display());
    eprintln!("[INIT_TRIDB] Schema version:   {}", version);
    eprintln!();

    let pillars = vec!["agent_identities", "content_memory", "execution_log"];

    for pillar in pillars {
        let conn = get_connection(pillar, clm_root)
            .map_err(|e| ClmError::Evaluation(format!("Failed to open DB for {}: {}", pillar, e)))?;

        // Enable WAL mode
        let _ = conn.pragma_update(None, "journal_mode", "WAL");

        // Split schema into separate statements (SQLite executescript equivalent)
        // Since sqlite3 handles multiple statements, we can run them in a transaction
        conn.execute_batch(&schema_sql)
            .map_err(|e| ClmError::Evaluation(format!("Failed to apply schema for {}: {}", pillar, e)))?;

        // Validate tables exist
        let mut stmt = conn
            .prepare("SELECT name FROM sqlite_master WHERE type='table';")?;
        let table_rows = stmt
            .query_map([], |row| row.get::<_, String>(0))?;

        let mut has_card = false;
        let mut has_registry = false;
        let mut has_history = false;

        for name in table_rows.flatten() {
            match name.as_str() {
                "card" => has_card = true,
                "handle_registry" => has_registry = true,
                "handle_history" => has_history = true,
                _ => {}
            }
        }

        if !has_card || !has_registry || !has_history {
            return Err(ClmError::Evaluation(format!("DB {} is missing required tables", pillar)));
        }
        
        // Optional: Schema registration check for self-evolution
        let schema_handle = format!("db:schema:{}:{}", pillar, version);
        let schema_hash = crate::fs_utils::compute_sha256_hex(schema_sql.as_bytes());
        let _ = handle_register_batch(pillar, clm_root, &schema_handle, &crate::hash::prefixed(&schema_hash), &schema_sql);
    }

    // Load the type lattice eagerly so type validation is always available.
    // This mirrors the Python TypeRegistry which loads on construction.
    // The lattice is stored in a global OnceLock for zero-cost repeated access.
    let mut lattice = crate::type_lattice::TypeLattice::new();
    lattice.load_registry(clm_root);
    eprintln!("[INIT_TRIDB] Type lattice loaded: {} types registered", lattice.registry.len());

    Ok(())
}

pub fn sql_query_parameterized(
    pillar: &str,
    clm_root: &str,
    query: &str,
    params_vec: Vec<String>,
    as_json: bool,
) -> Result<String> {
    let conn = get_connection(pillar, clm_root)?;
    
    // Ensure table structure is present (fallback just in case)
    let _ = conn.execute("SELECT 1 FROM card LIMIT 1;", []);
    
    let query_trimmed = query.trim();
    let is_batch = query_trimmed.contains("BEGIN;") 
        || query_trimmed.contains("begin;")
        || query_trimmed.contains("COMMIT;")
        || query_trimmed.contains("commit;")
        || (query_trimmed.contains(';') && !query_trimmed.ends_with(';'))
        || query_trimmed.matches(';').count() > 1;

    if is_batch {
        conn.execute_batch(query)?;
        if as_json {
            return Ok("[]".to_string());
        } else {
            return Ok(String::new());
        }
    }

    let mut stmt = conn.prepare(query)?;
    let col_count = stmt.column_count();
    let col_names: Vec<String> = stmt
        .column_names()
        .into_iter()
        .map(|s| s.to_string())
        .collect();

    // Convert Vec<String> to rusqlite params
    let params_ref: Vec<&dyn rusqlite::ToSql> = params_vec
        .iter()
        .map(|s| s as &dyn rusqlite::ToSql)
        .collect();

    let mut rows = stmt.query(params_ref.as_slice())?;
    
    if as_json {
        let mut results = Vec::new();
        while let Some(row) = rows.next()? {
            let mut row_map = serde_json::Map::new();
            for i in 0..col_count {
                let name = &col_names[i];
                let value_ref = row.get_ref(i)?;
                let json_val = match value_ref {
                    rusqlite::types::ValueRef::Null => serde_json::Value::Null,
                    rusqlite::types::ValueRef::Integer(n) => serde_json::Value::Number(n.into()),
                    rusqlite::types::ValueRef::Real(f) => {
                        if let Some(num) = serde_json::Number::from_f64(f) {
                            serde_json::Value::Number(num)
                        } else {
                            serde_json::Value::Null
                        }
                    }
                    rusqlite::types::ValueRef::Text(t) => {
                        let text = String::from_utf8_lossy(t).into_owned();
                        serde_json::Value::String(text)
                    }
                    rusqlite::types::ValueRef::Blob(b) => {
                        let text = String::from_utf8_lossy(b).into_owned();
                        serde_json::Value::String(text)
                    }
                };
                row_map.insert(name.clone(), json_val);
            }
            results.push(serde_json::Value::Object(row_map));
        }
        Ok(serde_json::Value::Array(results).to_string())
    } else {
        let mut results = Vec::new();
        while let Some(row) = rows.next()? {
            let mut row_parts = Vec::new();
            for i in 0..col_count {
                let val_ref = row.get_ref(i)?;
                let s = match val_ref {
                    rusqlite::types::ValueRef::Null => "".to_string(),
                    rusqlite::types::ValueRef::Integer(n) => n.to_string(),
                    rusqlite::types::ValueRef::Real(f) => f.to_string(),
                    rusqlite::types::ValueRef::Text(t) => String::from_utf8_lossy(t).into_owned(),
                    rusqlite::types::ValueRef::Blob(b) => String::from_utf8_lossy(b).into_owned(),
                };
                row_parts.push(s);
            }
            results.push(row_parts.join("|"));
        }
        Ok(results.join("\n"))
    }
}

/// Pre-compiled statement query for card content by hash.
pub fn get_card_cached(conn: &Connection, hash: &str) -> Result<Option<String>> {
    let mut stmt = conn.prepare_cached("SELECT content FROM card WHERE hash = ?1")?;
    let mut rows = stmt.query(params![hash])?;
    if let Some(row) = rows.next()? {
        let val: rusqlite::types::Value = row.get(0)?;
        let content = match val {
            rusqlite::types::Value::Text(s) => s,
            rusqlite::types::Value::Blob(b) => {
                String::from_utf8(b).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
            }
            _ => "".to_string(),
        };
        Ok(Some(content))
    } else {
        Ok(None)
    }
}

/// Pre-compiled statement check if a card exists by hash.
pub fn card_exists_cached(conn: &Connection, hash: &str) -> Result<bool> {
    let mut stmt = conn.prepare_cached("SELECT count(*) FROM card WHERE hash = ?1")?;
    let count: i64 = stmt.query_row(params![hash], |row| row.get(0))?;
    Ok(count > 0)
}

/// Pre-compiled statement resolution of handle to current hash.
pub fn resolve_handle_hash_cached(conn: &Connection, handle: &str) -> Result<Option<String>> {
    let mut stmt = conn.prepare_cached("SELECT current_hash FROM handle_registry WHERE handle = ?1")?;
    let res: Option<String> = stmt.query_row(params![handle], |row| row.get(0)).ok();
    Ok(res)
}

/// Pre-compiled statement resolution of handle to card content.
pub fn resolve_handle_content_cached(conn: &Connection, handle: &str) -> Result<Option<String>> {
    if let Some(hash) = resolve_handle_hash_cached(conn, handle)? {
        get_card_cached(conn, &hash)
    } else {
        Ok(None)
    }
}

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)))?
}

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

    #[test]
    fn test_cached_statement_queries() {
        let mut conn = Connection::open_in_memory().unwrap();
        migrations::apply_migrations(&mut conn, "content_memory").unwrap();

        // Insert card via cached statement
        let mut stmt = conn
            .prepare_cached("INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)")
            .unwrap();
        stmt.execute(rusqlite::params!["test_hash_1", "test_content_1", 1000])
            .unwrap();

        // Retrieve card via helper function using prepared cache
        let content = get_card_cached(&conn, "test_hash_1").unwrap();
        assert_eq!(content, Some("test_content_1".to_string()));

        let exists = card_exists_cached(&conn, "test_hash_1").unwrap();
        assert!(exists);

        let not_exists = card_exists_cached(&conn, "nonexistent").unwrap();
        assert!(!not_exists);

        // Insert handle registry
        let now = crate::utils::now_iso8601();
        let mut stmt_h = conn
            // ORC-23/27: three columns. `created_at` is the first history row, not a column —
            // so the fixture writes a history row rather than a column that does not exist.
            .prepare_cached("INSERT OR IGNORE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)")
            .unwrap();
        stmt_h.execute(params!["test_handle_1", "test_hash_1", &now]).unwrap();
        conn.prepare_cached(
            "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
        )
        .unwrap()
        .execute(params!["test_handle_1", "test_hash_1", &now])
        .unwrap();

        let resolved_hash = resolve_handle_hash_cached(&conn, "test_handle_1").unwrap();
        assert_eq!(resolved_hash, Some("test_hash_1".to_string()));

        let resolved_content = resolve_handle_content_cached(&conn, "test_handle_1").unwrap();
        assert_eq!(resolved_content, Some("test_content_1".to_string()));
    }

    #[cfg(any(feature = "native", feature = "db"))]
    #[test]
    fn test_concurrent_readers_in_pool() {
        let temp_dir = tempfile::tempdir().unwrap();
        let clm_root = temp_dir.path().to_str().unwrap();
        let pool = DbPillarPool::new("content_memory", clm_root).unwrap();

        // Pre-populate with 50 cards using the writer
        {
            let writer_arc = pool.writer();
            let mut conn = writer_arc.lock().unwrap();
            let tx = conn.transaction().unwrap();
            for i in 0..50 {
                let hash = format!("hash_{:04}", i);
                let content = format!("content_{:04}", i);
                let mut stmt = tx
                    .prepare_cached("INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)")
                    .unwrap();
                stmt.execute(rusqlite::params![hash, content, i as i64])
                    .unwrap();
            }
            tx.commit().unwrap();
        }

        // Spawn 16 concurrent reader threads querying simultaneously
        let mut handles = Vec::new();
        for thread_idx in 0..16 {
            let pool_clone = pool.clone();
            let h = std::thread::spawn(move || {
                let reader = pool_clone.reader().expect("Acquiring reader connection should succeed");
                for j in 0..50 {
                    let card_idx = (thread_idx * 7 + j) % 50;
                    let target_hash = format!("hash_{:04}", card_idx);
                    let expected_content = format!("content_{:04}", card_idx);

                    let content = get_card_cached(&reader, &target_hash)
                        .expect("Read query should not fail");
                    assert_eq!(content, Some(expected_content));
                }
            });
            handles.push(h);
        }

        for h in handles {
            h.join().expect("Reader thread should complete without panicking");
        }
    }

    #[tokio::test]
    async fn test_query_db_async_isolation() {
        let temp_dir = tempfile::tempdir().unwrap();
        let clm_root = temp_dir.path().to_str().unwrap();
        let pool = DbPillarPool::new("content_memory", clm_root).unwrap();

        // Write via writer connection
        let pool_writer = pool.clone();
        query_db_async(move || {
            let writer_arc = pool_writer.writer();
            let mut conn = writer_arc.lock().unwrap();
            let tx = conn.transaction()?;
            {
                let mut stmt = tx.prepare_cached("INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)")?;
                stmt.execute(rusqlite::params!["async_hash", "async_content", 12345])?;
            }
            tx.commit()?;
            Ok(())
        })
        .await
        .unwrap();

        // Read concurrently via query_db_async
        let pool_reader = pool.clone();
        let res = query_db_async(move || {
            let reader = pool_reader.reader()?;
            let content = get_card_cached(&reader, "async_hash")?;
            Ok(content)
        })
        .await
        .unwrap();

        assert_eq!(res, Some("async_content".to_string()));
    }
}