clm-kernel 0.0.24

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
use super::*;
#[cfg(feature = "native")]
use crate::layer2::collision_migration::{content_equivalent, migrate_handle_hash};

    #[test]
    fn test_raw_hash_bytes() {
        // Default active algorithm is blake3:
        assert_eq!(
            raw_hash_bytes(b"hello"),
            "ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
        );
    }

    #[test]
    fn test_sha256_provider() {
        let provider = Sha256Provider;
        assert_eq!(
            provider.hash(b"hello"),
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        );
    }

    #[test]
    fn test_raw_hash_string() {
        assert_eq!(
            raw_hash_string("hello"),
            "ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
        );
    }

    #[test]
    fn test_raw_hash_bytes_32() {
        let expected = [
            0xea, 0x8f, 0x16, 0x3d, 0xb3, 0x86, 0x82, 0x92, 0x5e, 0x44, 0x91, 0xc5, 0xe5, 0x8d,
            0x4b, 0xb3, 0x50, 0x6e, 0xf8, 0xc1, 0x4e, 0xb7, 0x8a, 0x86, 0xe9, 0x08, 0xc5, 0x62,
            0x4a, 0x67, 0x20, 0x0f,
        ];
        assert_eq!(raw_hash_bytes_32(b"hello"), expected);
    }

    #[test]
    fn test_prefixed_hash_string() {
        let h = prefixed_hash_string("hello");
        assert!(h.starts_with("blake3:"));
        assert_eq!(
            h,
            "blake3:ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
        );
    }

    #[test]
    fn test_strip_prefix() {
        assert_eq!(strip_prefix("sha256:abcdef"), "abcdef");
        assert_eq!(strip_prefix("sha3-256:abcdef"), "abcdef");
        assert_eq!(strip_prefix("noprefix"), "noprefix");
    }

    #[test]
    fn test_extract_prefix() {
        assert_eq!(extract_prefix("sha256:abc"), Some("sha256:"));
        assert_eq!(extract_prefix("sha3-256:abc"), Some("sha3-256:"));
        assert_eq!(extract_prefix("noprefix"), None);
    }

    #[test]
    fn test_verify_hash_match() {
        let content = b"hello";
        let stored = prefixed_hash_bytes(content);
        assert!(verify_hash(&stored, content).is_ok());
    }

    #[test]
    fn test_verify_hash_mismatch() {
        let stored = prefixed_hash_bytes(b"hello");
        assert!(verify_hash(&stored, b"world").is_err());
    }

    #[test]
    fn test_verify_hash_unknown_prefix() {
        assert!(verify_hash("unknown:abc", b"hello").is_err());
    }

    #[test]
    fn test_provider_registry() {
        let algorithms = list_algorithms();
        assert!(algorithms.contains(&"sha256:"));
    }

    #[test]
    fn test_collision_no_collision() {
        let result = check_collision("abc", b"hello", None, 0);
        assert_eq!(result, CollisionCheckResult::NoCollision);
    }

    #[test]
    fn test_collision_same_content() {
        let result = check_collision("abc", b"hello", Some(b"hello"), 0);
        assert_eq!(result, CollisionCheckResult::NoCollision);
    }

    #[test]
    fn test_collision_detected() {
        let result = check_collision("abc", b"hello", Some(b"world"), 0);
        assert_eq!(
            result,
            CollisionCheckResult::Collision {
                hash: "abc".to_string(),
                collision_count: 1
            }
        );
    }

    #[test]
    fn test_collision_threshold_exceeded() {
        let result = check_collision("abc", b"hello", Some(b"world"), 1);
        match result {
            CollisionCheckResult::ThresholdExceeded {
                recommended_algorithm,
                ..
            } => {
                // With default config, fallback order is ["blake3:", "sha256:"], so recommended == sha256:
                assert_eq!(recommended_algorithm, "sha256:");
            }
            other => panic!("Expected ThresholdExceeded, got {:?}", other),
        }
    }

    #[test]
    fn test_hash_config_default() {
        let cfg = HashConfig::default();
        assert_eq!(cfg.active_algorithm, DEFAULT_HASH_PREFIX);
        assert_eq!(cfg.collision_threshold, DEFAULT_COLLISION_THRESHOLD);
    }

    #[test]
    fn test_hash_config_parse() {
        let cfg = HashConfig::parse_config("sha256:|3|sha256:,sha3-256:");
        assert_eq!(cfg.active_algorithm, "sha256:");
        assert_eq!(cfg.collision_threshold, 3);
        assert_eq!(cfg.fallback_order, vec!["sha256:", "sha3-256:"]);
    }

    #[test]
    fn test_shake256_provider() {
        let provider = Shake256Provider::new(256);
        let h = provider.hash(b"hello");
        // 256 bits = 32 bytes = 64 hex chars
        assert_eq!(h.len(), 64);
        assert_eq!(provider.prefix(), "custom-256:");
    }

    #[test]
    fn test_shake256_provider_1024() {
        let provider = Shake256Provider::new(1024);
        let h = provider.hash(b"hello");
        // 1024 bits = 128 bytes = 256 hex chars
        assert_eq!(h.len(), 256);
        assert_eq!(provider.prefix(), "custom-1024:");
    }

    #[test]
    fn test_register_custom_provider() {
        register_custom_provider(512);
        let algorithms = list_algorithms();
        assert!(algorithms.contains(&"custom-512:"));
    }

    #[test]
    fn test_next_stronger_algorithm() {
        assert_eq!(next_stronger_algorithm("md5:"), "sha1:");
        assert_eq!(next_stronger_algorithm("sha1:"), "sha256:");
        assert_eq!(next_stronger_algorithm("sha256:"), "blake3:");
        assert_eq!(next_stronger_algorithm("blake3:"), "sha512:");
        assert_eq!(next_stronger_algorithm("sha512:"), "custom-1024:");
    }

    #[test]
    fn test_next_stronger_custom_doubling() {
        assert_eq!(next_stronger_algorithm("custom-1024:"), "custom-2048:");
        assert_eq!(next_stronger_algorithm("custom-2048:"), "custom-4096:");
    }

    #[test]
    fn test_verify_hash_custom_n() {
        register_custom_provider(256);
        let provider = Shake256Provider::new(256);
        let content = b"hello";
        let raw = provider.hash(content);
        let prefixed = format!("custom-256:{}", raw);
        assert!(verify_hash(&prefixed, content).is_ok());
        assert!(verify_hash(&prefixed, b"world").is_err());
    }

    #[test]
    fn test_md5_provider() {
        let provider = Md5Provider;
        let h = provider.hash(b"hello");
        assert_eq!(h.len(), 32); // 128 bits = 16 bytes = 32 hex chars
        assert_eq!(h, "5d41402abc4b2a76b9719d911017c592");
        assert_eq!(provider.prefix(), "md5:");
    }

    #[test]
    fn test_sha1_provider() {
        let provider = Sha1Provider;
        let h = provider.hash(b"hello");
        assert_eq!(h.len(), 40); // 160 bits = 20 bytes = 40 hex chars
        assert_eq!(h, "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d");
        assert_eq!(provider.prefix(), "sha1:");
    }

    #[test]
    fn test_sha512_provider() {
        let provider = Sha512Provider;
        let h = provider.hash(b"hello");
        assert_eq!(h.len(), 128); // 512 bits = 64 bytes = 128 hex chars
        assert_eq!(
            h,
            "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043"
        );
        assert_eq!(provider.prefix(), "sha512:");
    }

    #[test]
    fn test_blake3_provider() {
        let provider = Blake3Provider;
        let h = provider.hash(b"hello");
        // 256 bits = 32 bytes = 64 hex chars
        assert_eq!(h.len(), 64);
        assert_eq!(
            h,
            "ea8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200f"
        );
        assert_eq!(provider.prefix(), "blake3:");
    }

    #[test]
    fn test_all_providers_registered() {
        let algorithms = list_algorithms();
        assert!(algorithms.contains(&"blake3:"));
        assert!(algorithms.contains(&"sha256:"));
        assert!(algorithms.contains(&"md5:"));
        assert!(algorithms.contains(&"sha1:"));
        assert!(algorithms.contains(&"sha512:"));
    }

    #[test]
    fn test_verify_hash_blake3() {
        let provider = Blake3Provider;
        let content = b"hello";
        let prefixed = format!("blake3:{}", provider.hash(content));
        assert!(verify_hash(&prefixed, content).is_ok());
        assert!(verify_hash(&prefixed, b"world").is_err());
    }

    #[test]
    fn test_verify_hash_md5() {
        let provider = Md5Provider;
        let content = b"hello";
        let prefixed = format!("md5:{}", provider.hash(content));
        assert!(verify_hash(&prefixed, content).is_ok());
        assert!(verify_hash(&prefixed, b"world").is_err());
    }

    #[test]
    fn test_verify_hash_sha512() {
        let provider = Sha512Provider;
        let content = b"hello";
        let prefixed = format!("sha512:{}", provider.hash(content));
        assert!(verify_hash(&prefixed, content).is_ok());
        assert!(verify_hash(&prefixed, b"world").is_err());
    }

    #[test]
    #[cfg(feature = "native")]
    fn test_migrate_through_hierarchy() {
        use rusqlite::Connection;
        register_custom_provider(1024);
        let mut conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
             CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
             CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
        ).unwrap();
        let content = b"hierarchy_test_payload";
        let h = prefixed_hash_bytes(content);
        let g_time = format!("{}|2025-01-01T00:00:00Z|UTC", h.split(':').next().unwrap());
        conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, ?)", rusqlite::params![h, content, g_time]).unwrap();
        conn.execute("INSERT INTO handle_registry (handle, current_hash, created_at, updated_at) VALUES (?, ?, '2025-01-01', '2025-01-01')", rusqlite::params!["test:hier_handle", h]).unwrap();
        // Migrate sha256 -> sha512
        let h512 = migrate_handle_hash(&mut conn, "test:hier_handle", "sha512:").unwrap();
        assert!(h512.starts_with("sha512:"));
        assert!(content_equivalent(&conn, &h, &h512).unwrap());
        // Migrate sha512 -> custom-1024
        let h_custom = migrate_handle_hash(&mut conn, "test:hier_handle", "custom-1024:").unwrap();
        assert!(h_custom.starts_with("custom-1024:"));
        assert!(content_equivalent(&conn, &h, &h_custom).unwrap());
        // Verify 3 cards coexist. A migration writes the new digest in the canonical bare form
        // (DEC-12) while the pre-migration row keeps whatever form it was stored under, so the
        // coexistence check counts rows by content rather than by reference form.
        let count: i64 = conn.query_row("SELECT count(*) FROM card WHERE content = ?", rusqlite::params![content], |r| r.get(0)).unwrap();
        assert_eq!(count, 3);
        // Verify 2 history entries
        let hist: i64 = conn.query_row("SELECT count(*) FROM handle_history WHERE handle = 'test:hier_handle'", [], |r| r.get(0)).unwrap();
        assert_eq!(hist, 2);
    }

    #[test]
    #[cfg(feature = "native")]
    fn test_content_equivalent() {
        use rusqlite::Connection;
        let conn = Connection::open_in_memory().unwrap();
        conn.execute(
            "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL)",
            [],
        )
        .unwrap();
        let a = crate::layer0::mcard_record::MCardRecord::create(b"hello world", Some("sha256")).unwrap();
        let b = crate::layer0::mcard_record::MCardRecord::create(b"hello world", Some("sha512")).unwrap();
        let c = crate::layer0::mcard_record::MCardRecord::create(b"different", Some("sha256")).unwrap();
        for record in [&a, &b, &c] { crate::layer2::record_store::insert_record(&conn, record).unwrap(); }
        assert!(content_equivalent(&conn, &a.hash, &b.hash).unwrap());
        assert!(content_equivalent(&conn, &a.hash, &a.hash).unwrap());
        assert!(!content_equivalent(&conn, &a.hash, &c.hash).unwrap());
        assert!(!content_equivalent(&conn, &a.hash, "missing").unwrap());
        conn.execute("UPDATE card SET content = 'corrupt' WHERE hash = ?", [&a.hash]).unwrap();
        assert!(content_equivalent(&conn, &a.hash, &a.hash).is_err());
    }

    #[test]
    #[cfg(feature = "native")]
    fn test_migrate_handle_hash() {
        use rusqlite::Connection;
        register_custom_provider(256);
        let mut conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
             CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
             CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
        ).unwrap();
        let content = b"migration_test_payload";
        let h = prefixed_hash_bytes(content);
        let g_time = format!("{}|2025-01-01T00:00:00Z|UTC", h.split(':').next().unwrap());
        conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, ?)", rusqlite::params![h, content, g_time]).unwrap();
        conn.execute("INSERT INTO handle_registry (handle, current_hash, created_at, updated_at) VALUES (?, ?, '2025-01-01', '2025-01-01')", rusqlite::params!["test:handle", h]).unwrap();
        let new_h = migrate_handle_hash(&mut conn, "test:handle", "custom-256:").unwrap();
        assert!(new_h.starts_with("custom-256:"));
        let updated: String = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = 'test:handle'", [], |r| r.get(0)).unwrap();
        assert_eq!(updated, new_h);
        let hist: i64 = conn.query_row("SELECT count(*) FROM handle_history WHERE handle = 'test:handle'", [], |r| r.get(0)).unwrap();
        assert_eq!(hist, 1);
        assert!(content_equivalent(&conn, &h, &new_h).unwrap());
    }

    #[test]
    #[cfg(feature = "native")]
    fn migration_rejects_algorithm_less_source_without_mutation() {
        use rusqlite::Connection;
        let mut conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
             CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
             CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
        ).unwrap();
        let content = b"legacy_data";
        let hash = prefixed_hash_bytes(content);
        conn.execute("INSERT INTO card VALUES (?, ?, ?)", rusqlite::params![hash, content, "2025-01-01T00:00:00Z"]).unwrap();
        conn.execute("INSERT INTO handle_registry VALUES (?, ?, ?, ?)", rusqlite::params!["legacy", hash, "2025-01-01", "2025-01-01"]).unwrap();
        assert!(migrate_handle_hash(&mut conn, "legacy", "sha512:").is_err());
        let (stored_hash, stored_time): (String, String) = conn.query_row("SELECT hash, g_time FROM card", [], |row| Ok((row.get(0)?, row.get(1)?))).unwrap();
        assert_eq!((stored_hash, stored_time), (hash.clone(), "2025-01-01T00:00:00Z".to_string()));
        let head: String = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = 'legacy'", [], |row| row.get(0)).unwrap();
        assert_eq!(head, hash);
        assert_eq!(conn.query_row("SELECT count(*) FROM handle_history", [], |row| row.get::<_, i64>(0)).unwrap(), 0);
    }

    #[test]
    fn registered_provider_requires_valid_declared_metadata() {
        use crate::layer0::mcard_record::{MCardRecord, RecordVerification, verify_record};
        register_custom_provider(2048);
        let record = MCardRecord::create_at(b"custom", Some("custom-2048"), Some("2025-01-01T00:00:00Z"), "UTC").unwrap();
        assert!(matches!(verify_record(&record), RecordVerification::DeclaredOk { .. }));
        let mut malformed = record.clone();
        malformed.g_time.push_str("|not-an-extension");
        assert!(matches!(verify_record(&malformed), RecordVerification::Malformed { .. }));
        malformed.g_time = "custom-2049|2025-01-01T00:00:00Z|UTC".to_string();
        assert!(matches!(verify_record(&malformed), RecordVerification::Malformed { .. }));
    }

    #[test]
    #[cfg(feature = "native")]
    fn migration_rejects_corrupt_existing_target_without_changing_head() {
        use rusqlite::Connection;
        let mut conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
             CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
             CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
        ).unwrap();
        let content = b"migration content";
        let source = crate::layer0::mcard_record::MCardRecord::create_at(content, Some("blake3"), Some("2025-01-01T00:00:00Z"), "UTC").unwrap();
        let target = crate::hash::raw_hash_bytes_for("sha512", content).unwrap();
        conn.execute("INSERT INTO card VALUES (?, ?, ?)", rusqlite::params![source.hash, source.content, source.g_time]).unwrap();
        conn.execute("INSERT INTO card VALUES (?, ?, ?)", rusqlite::params![target, b"corrupt", "sha512|2025-01-01T00:00:00Z|UTC"]).unwrap();
        conn.execute("INSERT INTO handle_registry VALUES (?, ?, ?, ?)", rusqlite::params!["test", source.hash, "2025", "2025"]).unwrap();
        assert!(migrate_handle_hash(&mut conn, "test", "sha512:").is_err());
        let head: String = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = 'test'", [], |row| row.get(0)).unwrap();
        assert_eq!(head, source.hash);
        let stored: Vec<u8> = conn.query_row("SELECT content FROM card WHERE hash = ?", [&target], |row| row.get(0)).unwrap();
        assert_eq!(stored, b"corrupt");
        assert_eq!(conn.query_row("SELECT count(*) FROM handle_history", [], |row| row.get::<_, i64>(0)).unwrap(), 0);
    }

    #[test]
    #[cfg(feature = "native")]
    fn migration_rejects_conflicting_source_reference() {
        use rusqlite::Connection;
        let mut conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
             CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
             CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
        ).unwrap();
        let source = crate::layer0::mcard_record::MCardRecord::create_at(b"content", Some("blake3"), Some("2025-01-01T00:00:00Z"), "UTC").unwrap();
        conn.execute("INSERT INTO card VALUES (?, ?, ?)", rusqlite::params![source.hash, source.content, source.g_time]).unwrap();
        let conflicting = format!("sha256:{}", source.hash);
        conn.execute("INSERT INTO handle_registry VALUES (?, ?, ?, ?)", rusqlite::params!["test", conflicting, "2025", "2025"]).unwrap();
        assert!(migrate_handle_hash(&mut conn, "test", "sha512:").is_err());
        let head: String = conn.query_row("SELECT current_hash FROM handle_registry WHERE handle = 'test'", [], |row| row.get(0)).unwrap();
        assert_eq!(head, conflicting);
        assert_eq!(conn.query_row("SELECT count(*) FROM card", [], |row| row.get::<_, i64>(0)).unwrap(), 1);
        assert_eq!(conn.query_row("SELECT count(*) FROM handle_history", [], |row| row.get::<_, i64>(0)).unwrap(), 0);
    }