clm-kernel 0.0.5

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
//! Central content-hash module — upgradable hash function abstraction (INV-02).
//!
//! All content hashing in CLM must route through this module. The current default
//! algorithm is SHA-256, but the `HashProvider` trait allows any conforming
//! implementation to be substituted without changing call sites. Stored hash
//! values carry an algorithm prefix (e.g. `sha256:<hex>`) so multiple algorithms
//! can coexist in the same namespace.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────┐
//! │                    HashConfig                            │
//! │  active_algorithm: "sha256:"                             │
//! │  collision_threshold: 2                                  │
//! │  fallback_order: ["sha256:", "sha3-256:"]               │
//! └──────────────────────┬──────────────────────────────────┘
//!                        │
//!                        ▼
//! ┌─────────────────────────────────────────────────────────┐
//! │               ProviderRegistry                           │
//! │  "sha256:"    → Sha256Provider                           │
//! │  "sha3-256:"  → Sha3_256Provider (future)               │
//! └──────────────────────┬──────────────────────────────────┘
//!                        │
//!         ┌──────────────┼──────────────┐
//!         ▼              ▼              ▼
//!    raw_hash_*    prefixed_hash_*   verify_hash
//!    (compute)     (compute+prefix)  (dispatch by prefix)
//! ```
//!
//! Common function signature (matches Python `clm_hash_string`):
//!   `fn(content: &[u8]) -> String`  →  raw hex digest, no prefix
//!
//! To get a prefixed hash (for storage), use `prefixed_hash_bytes` / `prefixed_hash_string`.

use md5::Md5;
use sha1::Sha1;
use sha2::{Digest, Sha256, Sha512};
use sha3::{Shake256, digest::{ExtendableOutput, XofReader}};
use std::sync::{Mutex, OnceLock};

// ── Constants ─────────────────────────────────────────────────────────────

/// Algorithm prefix for BLAKE3 hash provider (INV-02).
pub const BLAKE3_HASH_PREFIX: &str = "blake3:";

/// Algorithm prefix for legacy SHA-256 hash provider.
pub const SHA256_HASH_PREFIX: &str = "sha256:";

/// Algorithm prefix for the default hash provider (BLAKE3 is default).
pub const DEFAULT_HASH_PREFIX: &str = BLAKE3_HASH_PREFIX;

/// Default collision threshold before triggering an algorithm upgrade.
pub const DEFAULT_COLLISION_THRESHOLD: u32 = 2;

// ── HashProvider trait ────────────────────────────────────────────────────

/// Trait for pluggable content-hash algorithms.
///
/// Any type implementing this trait can serve as CLM's content hash function.
/// The trait is intentionally minimal: `hash` returns the raw hex digest,
/// and `prefix` returns the algorithm tag used in prefixed storage format.
pub trait HashProvider: Send + Sync {
    /// Compute the raw hex digest of `content`.
    fn hash(&self, content: &[u8]) -> String;

    /// Algorithm prefix (e.g. `"blake3:"`, `"sha256:"`).
    fn prefix(&self) -> &'static str;

    /// Compute the raw digest as a fixed-size byte array (for Merkle trees, etc.).
    /// Default implementation parses the hex digest; providers may override
    /// for efficiency.
    fn hash_bytes(&self, content: &[u8]) -> [u8; 32] {
        let hex = self.hash(content);
        let mut out = [0u8; 32];
        let bytes = hex.as_bytes();
        for i in 0..32 {
            out[i] = u8::from_str_radix(
                std::str::from_utf8(&bytes[i * 2..i * 2 + 2]).unwrap_or("00"),
                16,
            )
            .unwrap_or(0);
        }
        out
    }
}

// ── Built-in providers ────────────────────────────────────────────────────

/// Default BLAKE3 hash provider (INV-02: high-performance, tree-hashable 256-bit).
pub struct Blake3Provider;

impl HashProvider for Blake3Provider {
    fn hash(&self, content: &[u8]) -> String {
        blake3::hash(content).to_hex().to_string()
    }

    fn prefix(&self) -> &'static str {
        BLAKE3_HASH_PREFIX
    }

    fn hash_bytes(&self, content: &[u8]) -> [u8; 32] {
        *blake3::hash(content).as_bytes()
    }
}

/// Legacy SHA-256 hash provider.
pub struct Sha256Provider;

impl HashProvider for Sha256Provider {
    fn hash(&self, content: &[u8]) -> String {
        let mut hasher = Sha256::new();
        hasher.update(content);
        format!("{:x}", hasher.finalize())
    }

    fn prefix(&self) -> &'static str {
        SHA256_HASH_PREFIX
    }

    fn hash_bytes(&self, content: &[u8]) -> [u8; 32] {
        let mut hasher = Sha256::new();
        hasher.update(content);
        hasher.finalize().into()
    }
}

/// MD5 hash provider (weakest in the hierarchy, for legacy compatibility).
pub struct Md5Provider;

impl HashProvider for Md5Provider {
    fn hash(&self, content: &[u8]) -> String {
        let mut hasher = Md5::new();
        hasher.update(content);
        format!("{:x}", hasher.finalize())
    }

    fn prefix(&self) -> &'static str {
        "md5:"
    }
}

/// SHA-1 hash provider (legacy, for migration path compatibility).
pub struct Sha1Provider;

impl HashProvider for Sha1Provider {
    fn hash(&self, content: &[u8]) -> String {
        let mut hasher = Sha1::new();
        hasher.update(content);
        format!("{:x}", hasher.finalize())
    }

    fn prefix(&self) -> &'static str {
        "sha1:"
    }
}

/// SHA-512 hash provider (stronger than SHA-256).
pub struct Sha512Provider;

impl HashProvider for Sha512Provider {
    fn hash(&self, content: &[u8]) -> String {
        let mut hasher = Sha512::new();
        hasher.update(content);
        format!("{:x}", hasher.finalize())
    }

    fn prefix(&self) -> &'static str {
        "sha512:"
    }
}

/// Keccak SHAKE-256 provider with configurable output bit-length (`custom-N`).
///
/// Uses the SHAKE-256 extendable-output function (XOF) to produce a digest
/// of `N` bits. The prefix is `custom-N:` (e.g. `custom-1024:`).
/// This provides future-proofing: if `custom-N` is exhausted, upgrade to
/// `custom-2N` by registering a new provider with doubled bit-length.
pub struct Shake256Provider {
    bits: usize,
    prefix_str: &'static str,
}

impl Shake256Provider {
    /// Create a new `custom-N` provider for the given bit-length.
    ///
    /// `bits` must be > 0. The byte-length of the digest is `(bits + 7) / 8`.
    pub fn new(bits: usize) -> Self {
        let prefix_str: &'static str = Box::leak(
            format!("custom-{}:", bits).into_boxed_str(),
        );
        Self { bits, prefix_str }
    }

    fn byte_len(&self) -> usize {
        self.bits.div_ceil(8)
    }
}

impl HashProvider for Shake256Provider {
    fn hash(&self, content: &[u8]) -> String {
        let mut hasher = Shake256::default();
        sha3::digest::Update::update(&mut hasher, content);
        let mut reader = hasher.finalize_xof();
        let byte_len = self.byte_len();
        let mut buf = vec![0u8; byte_len];
        reader.read(&mut buf);
        hex::encode(&buf)
    }

    fn prefix(&self) -> &'static str {
        self.prefix_str
    }
}

// ── Provider registry (Step 2) ────────────────────────────────────────────

/// Registry of available hash providers, keyed by algorithm prefix.
///
/// The registry allows multiple algorithms to coexist. New providers can be
/// registered at startup or at runtime. The active algorithm (used for new
/// content) is determined by `HashConfig.active_algorithm`.
pub struct ProviderRegistry {
    providers: Vec<(&'static str, Box<dyn HashProvider>)>,
}

impl ProviderRegistry {
    fn new() -> Self {
        Self {
            providers: Vec::new(),
        }
    }

    /// Register a new hash provider under its algorithm prefix.
    pub fn register(&mut self, provider: Box<dyn HashProvider>) {
        let prefix = provider.prefix();
        self.providers.push((prefix, provider));
    }

    /// Look up a provider by algorithm prefix.
    pub fn get(&self, prefix: &str) -> Option<&dyn HashProvider> {
        self.providers
            .iter()
            .find(|(p, _)| *p == prefix)
            .map(|(_, provider)| provider.as_ref())
    }

    /// Get the active provider (determined by `HashConfig`).
    pub fn active(&self, active_prefix: &str) -> &dyn HashProvider {
        self.get(active_prefix)
            .unwrap_or_else(|| self.get(DEFAULT_HASH_PREFIX).expect("default provider must be registered"))
    }

    /// List all registered algorithm prefixes.
    pub fn algorithms(&self) -> Vec<&'static str> {
        self.providers.iter().map(|(p, _)| *p).collect()
    }
}

pub fn global_registry() -> &'static Mutex<ProviderRegistry> {
    static REGISTRY: OnceLock<Mutex<ProviderRegistry>> = OnceLock::new();
    REGISTRY.get_or_init(|| {
        let mut reg = ProviderRegistry::new();
        reg.register(Box::new(Blake3Provider));
        reg.register(Box::new(Sha256Provider));
        reg.register(Box::new(Md5Provider));
        reg.register(Box::new(Sha1Provider));
        reg.register(Box::new(Sha512Provider));
        Mutex::new(reg)
    })
}

/// Register an additional hash provider at runtime.
pub fn register_provider(provider: Box<dyn HashProvider>) {
    let mut reg = global_registry().lock().unwrap();
    reg.register(provider);
}

/// Register a `custom-N` (SHAKE-256) provider with the given bit-length.
///
/// Convenience wrapper around `register_provider` for the `custom-N` family.
/// Example: `register_custom_provider(1024)` registers a `custom-1024:` provider.
pub fn register_custom_provider(bits: usize) {
    register_provider(Box::new(Shake256Provider::new(bits)));
}

/// Algorithm strength hierarchy (weakest → strongest).
///
/// Used by the collision remediation system to determine the next algorithm
/// when the current one exceeds its collision threshold. For `custom-N`,
/// the upgrade path is `custom-2N` (recursive doubling).
pub const STRENGTH_HIERARCHY: &[&str] = &[
    "md5:",
    "sha1:",
    "sha256:",
    "blake3:",
    "sha512:",
    "custom-1024:",
];

/// Recommend the next stronger algorithm in the hierarchy.
///
/// If the current algorithm is `custom-N`, returns `custom-2N` (recursive doubling).
/// If the current algorithm is not in the hierarchy, returns `blake3:` as a safe default.
pub fn next_stronger_algorithm(current: &str) -> &'static str {
    // Handle custom-N recursive doubling
    if let Some(rest) = current.strip_prefix("custom-")
        && let Some(num_str) = rest.strip_suffix(':')
            && let Ok(n) = num_str.parse::<usize>() {
                let doubled = n * 2;
                return Box::leak(format!("custom-{}:", doubled).into_boxed_str());
            }
    // Find current in the standard hierarchy
    let pos = STRENGTH_HIERARCHY.iter().position(|&algo| algo == current);
    match pos {
        Some(i) if i + 1 < STRENGTH_HIERARCHY.len() => STRENGTH_HIERARCHY[i + 1],
        _ => DEFAULT_HASH_PREFIX,
    }
}

/// List all registered algorithm prefixes.
pub fn list_algorithms() -> Vec<&'static str> {
    let reg = global_registry().lock().unwrap();
    reg.algorithms()
}

// ── Hash configuration policy (Step 4) ────────────────────────────────────

/// Configuration policy for hash algorithm selection and collision handling.
///
/// This struct governs:
/// - Which algorithm is used for **new** content (`active_algorithm`)
/// - How many collisions trigger an automatic upgrade (`collision_threshold`)
/// - The order of fallback algorithms if the active one is compromised
///
/// The config is stored in a global `OnceLock` and can be loaded from a
/// configuration file or environment variable at startup.
#[derive(Debug, Clone)]
pub struct HashConfig {
    /// Algorithm prefix for new content (e.g. `"blake3:"`, `"sha256:"`).
    pub active_algorithm: &'static str,
    /// Number of collisions before triggering an upgrade.
    pub collision_threshold: u32,
    /// Ordered list of fallback algorithm prefixes.
    /// If the active algorithm is compromised, the first available fallback
    /// becomes the new active algorithm.
    pub fallback_order: Vec<&'static str>,
}

impl Default for HashConfig {
    fn default() -> Self {
        Self {
            active_algorithm: DEFAULT_HASH_PREFIX,
            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
            fallback_order: vec![DEFAULT_HASH_PREFIX, SHA256_HASH_PREFIX],
        }
    }
}

fn normalize_prefix(value: &str) -> &'static str {
    let normalized = value.trim().trim_end_matches(':').to_lowercase();
    Box::leak(format!("{}:", normalized).into_boxed_str())
}

impl HashConfig {
    /// Load hash configuration from environment variables.
    ///
    /// Checks in order:
    /// 1. `CLM_HASH_CONFIG`: `active_algorithm|collision_threshold|fallback1,fallback2,...`
    ///    Example: `blake3:|2|blake3:,sha256:`
    /// 2. `CLM_HASH_ALGO` / `MCARD_HASH_ALGORITHM`: simple string override (e.g. `blake3` or `sha256`)
    ///
    /// If unset, returns the central BLAKE3 default. Unsupported configured names are preserved;
    /// write operations reject them through `raw_hash_bytes_for` instead of silently downgrading.
    pub fn from_env() -> Self {
        let configured = std::env::var("CLM_HASH_CONFIG")
            .ok()
            .filter(|raw| !raw.trim().is_empty())
            .map(|raw| Self::parse_config(&raw))
            .or_else(|| {
                std::env::var("CLM_HASH_ALGO")
                    .or_else(|_| std::env::var("MCARD_HASH_ALGORITHM"))
                    .ok()
                    .filter(|algo| !algo.trim().is_empty())
                    .map(|algo| {
                        let prefix = normalize_prefix(&algo);
                        Self {
                            active_algorithm: prefix,
                            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
                            fallback_order: vec![prefix, SHA256_HASH_PREFIX],
                        }
                    })
            });

        let Some(config) = configured else {
            return Self::default();
        };
        config
    }

    fn parse_config(raw: &str) -> Self {
        let parts: Vec<&str> = raw.splitn(3, '|').collect();
        if parts.len() < 2 {
            return Self::default();
        }
        let active = if parts[0].is_empty() {
            DEFAULT_HASH_PREFIX
        } else {
            normalize_prefix(parts[0])
        };
        let threshold = parts[1].parse::<u32>().unwrap_or(DEFAULT_COLLISION_THRESHOLD);
        let fallbacks: Vec<&'static str> = if parts.len() == 3 && !parts[2].is_empty() {
            parts[2]
                .split(',')
                .map(|s| if s.is_empty() { DEFAULT_HASH_PREFIX } else { normalize_prefix(s) })
                .collect()
        } else {
            vec![active]
        };
        Self {
            active_algorithm: active,
            collision_threshold: threshold,
            fallback_order: fallbacks,
        }
    }
}

fn global_config() -> &'static HashConfig {
    static CONFIG: OnceLock<HashConfig> = OnceLock::new();
    CONFIG.get_or_init(HashConfig::from_env)
}

/// Get the current hash configuration.
pub fn config() -> &'static HashConfig {
    global_config()
}

// ── Prefix-based dispatch (Step 3) ────────────────────────────────────────

/// Extract the algorithm prefix from a stored hash string.
///
/// Returns `Some(prefix)` if the string contains a `:` separator,
/// `None` if there is no prefix (assumed to be the default algorithm).
pub fn extract_prefix(prefixed: &str) -> Option<&str> {
    prefixed.find(':').map(|pos| &prefixed[..=pos])
}

/// Verify a stored hash against content by dispatching to the correct provider.
///
/// This function parses the algorithm prefix from `stored_hash`, looks up
/// the corresponding provider in the registry, and checks whether the
/// content matches.
///
/// Returns `Ok(())` if the hash matches, `Err(message)` if it doesn't
/// or the provider is unknown.
pub fn verify_hash(stored_hash: &str, content: &[u8]) -> Result<(), String> {
    let prefix = extract_prefix(stored_hash).unwrap_or(DEFAULT_HASH_PREFIX);
    let reg = global_registry().lock().unwrap();
    let provider = reg.get(prefix).ok_or_else(|| {
        format!("Unknown hash algorithm prefix: {} (registered: {:?})", prefix, reg.algorithms())
    })?;
    let computed = provider.hash(content);
    let stored_raw = strip_prefix(stored_hash);
    if computed == stored_raw {
        Ok(())
    } else {
        Err(format!(
            "Hash mismatch: expected {}..., got {}...",
            &stored_raw[..stored_raw.len().min(16)],
            &computed[..computed.len().min(16)]
        ))
    }
}

// ── Collision detection (Step 5) ──────────────────────────────────────────

/// Result of a collision check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CollisionCheckResult {
    /// No collision — the hash is unique.
    NoCollision,
    /// Collision detected — the same hash already exists with different content.
    Collision { hash: String, collision_count: u32 },
    /// Threshold exceeded — the active algorithm should be upgraded.
    ThresholdExceeded {
        hash: String,
        collision_count: u32,
        recommended_algorithm: &'static str,
    },
}

/// Check whether a hash collision has occurred and whether the threshold
/// for algorithm upgrade has been exceeded.
///
/// Callers should invoke this *before* inserting a new card into the database.
/// If `existing_content` is `Some` and differs from `new_content`, a collision
/// is recorded. When the collision count for the active algorithm reaches
/// `config().collision_threshold`, a `ThresholdExceeded` result is returned
/// with the recommended fallback algorithm.
pub fn check_collision(
    hash: &str,
    new_content: &[u8],
    existing_content: Option<&[u8]>,
    collision_count: u32,
) -> CollisionCheckResult {
    match existing_content {
        None => CollisionCheckResult::NoCollision,
        Some(existing) if existing == new_content => CollisionCheckResult::NoCollision,
        Some(_) => {
            let count = collision_count + 1;
            let cfg = config();
            if count >= cfg.collision_threshold {
                // Find the first fallback that isn't the current active algorithm
                let recommended = cfg
                    .fallback_order
                    .iter()
                    .find(|&&algo| algo != cfg.active_algorithm)
                    .copied()
                    .unwrap_or(cfg.active_algorithm);
                CollisionCheckResult::ThresholdExceeded {
                    hash: hash.to_string(),
                    collision_count: count,
                    recommended_algorithm: recommended,
                }
            } else {
                CollisionCheckResult::Collision {
                    hash: hash.to_string(),
                    collision_count: count,
                }
            }
        }
    }
}

// ── Convenience functions (delegate to the active provider) ──────────────

/// Compute the raw hex digest of bytes using the active provider (no prefix).
///
/// This is the canonical "common function signature" shared with Python's
/// `clm_hash_string`: `fn(content: &[u8]) -> String`.
pub fn raw_hash_bytes(content: &[u8]) -> String {
    let reg = global_registry().lock().unwrap();
    reg.active(config().active_algorithm).hash(content)
}

/// Compute a raw digest with an explicit algorithm, failing instead of substituting a default.
pub fn raw_hash_bytes_for(algorithm: &str, content: &[u8]) -> Result<String, String> {
    let normalized = algorithm.trim().trim_end_matches(':').to_lowercase();
    let prefix = format!("{}:", normalized);
    let reg = global_registry().lock().map_err(|e| e.to_string())?;
    let provider = reg.get(&prefix).ok_or_else(|| {
        format!("Unsupported hash algorithm: {} (registered: {:?})", normalized, reg.algorithms())
    })?;
    Ok(provider.hash(content))
}

/// Compute the raw hex digest of a string using the active provider (no prefix).
pub fn raw_hash_string(s: &str) -> String {
    raw_hash_bytes(s.as_bytes())
}

/// Compute the raw digest as a 32-byte array using the active provider.
///
/// Used by Merkle tree and type lattice code that needs the raw bytes
/// rather than a hex string.
pub fn raw_hash_bytes_32(content: &[u8]) -> [u8; 32] {
    let reg = global_registry().lock().unwrap();
    reg.active(config().active_algorithm).hash_bytes(content)
}

/// Compute the prefixed hash of bytes (e.g. `"sha256:<hex>"`).
pub fn prefixed_hash_bytes(content: &[u8]) -> String {
    let reg = global_registry().lock().unwrap();
    let provider = reg.active(config().active_algorithm);
    format!("{}{}", provider.prefix(), provider.hash(content))
}

/// Compute the prefixed hash of a string (e.g. `"sha256:<hex>"`).
pub fn prefixed_hash_string(s: &str) -> String {
    prefixed_hash_bytes(s.as_bytes())
}

/// Prepend the active algorithm prefix to an already-computed raw hex digest.
pub fn prefixed(raw_hex: &str) -> String {
    format!("{}{}", config().active_algorithm, raw_hex)
}

/// Strip a known algorithm prefix from a hash string.
///
/// If the hash starts with a known algorithm prefix (or any `<algo>:` pattern),
/// the unprefixed hex is returned. Otherwise the input is returned as-is.
pub fn strip_prefix(prefixed: &str) -> &str {
    // Try the active algorithm prefix first
    let active = config().active_algorithm;
    if let Some(rest) = prefixed.strip_prefix(active) {
        return rest;
    }
    // Try the default prefix
    if let Some(rest) = prefixed.strip_prefix(DEFAULT_HASH_PREFIX) {
        return rest;
    }
    // Generic fallback: strip any `<algo>:` prefix
    if let Some(pos) = prefixed.find(':')
        && pos + 1 < prefixed.len() {
            return &prefixed[pos + 1..];
        }
    prefixed
}

/// Returns the default hash provider (currently `Blake3Provider`).
///
/// Kept for backward compatibility — prefer `raw_hash_bytes` / `raw_hash_string`.
pub fn default_provider() -> impl HashProvider {
    Blake3Provider
}

// ── Content-equivalence operator (Gap 2) ──────────────────────────────────

/// Check whether two hashes point to the same content in the CAS.
///
/// This is the Rust equivalent of the shell `clm_content_equivalent` operator.
/// Two hashes generated by different algorithms (e.g. `sha256:abc` and
/// `sha512:def`) will never match as strings, but they may point to the same
/// underlying content. This function resolves both hashes to their stored
/// content and compares the raw bytes.
///
/// Returns `Ok(true)` if both hashes exist and point to identical content,
/// `Ok(false)` if they differ or one is not found, `Err` on DB error.
#[cfg(feature = "native")]
pub fn content_equivalent(
    conn: &rusqlite::Connection,
    hash_a: &str,
    hash_b: &str,
) -> Result<bool, String> {
    if hash_a == hash_b {
        return Ok(true);
    }
    let content_a = lookup_content(conn, hash_a);
    let content_b = lookup_content(conn, hash_b);
    match (content_a, content_b) {
        (Some(a), Some(b)) => Ok(a == b),
        _ => Ok(false),
    }
}

/// Resolve a stored row by reference, accepting either the bare digest or a qualified form.
///
/// The digest column holds bare hex (DEC-12); references that leave a row are qualified. A
/// lookup therefore tries the reference as given, then its unprefixed form, so both a legacy
/// prefixed row and a canonical bare row resolve.
#[cfg(feature = "native")]
fn lookup_content(conn: &rusqlite::Connection, reference: &str) -> Option<Vec<u8>> {
    let raw = strip_prefix(reference);
    let mut candidates = vec![reference];
    if raw != reference {
        candidates.push(raw);
    }
    for candidate in candidates {
        if let Ok(content) = conn.query_row(
            "SELECT content FROM card WHERE hash = ?",
            rusqlite::params![candidate],
            |row| row.get::<_, Vec<u8>>(0),
        ) {
            return Some(content);
        }
    }
    None
}

// ── Handle migration lifecycle (Gap 3) ────────────────────────────────────

/// Migrate a handle to use a different hash algorithm.
///
/// This is the Rust equivalent of the shell `clm_migrate_handle_hash` operator.
/// It resolves the handle to its current hash, retrieves the content from the
/// CAS, computes a new hash under the target algorithm, and transactionally
/// inserts the new card, records handle history, and updates the handle pointer.
///
/// # Arguments
/// * `conn` - SQLite connection to the content_memory database.
/// * `handle` - The handle name to migrate (e.g. `"test:migration_handle"`).
/// * `target_algo` - Target algorithm prefix (e.g. `"sha256:"`, `"custom-1024:"`).
///   Must be a registered provider.
///
/// Returns `Ok(new_hash)` on success, `Err(message)` on failure.
#[cfg(feature = "native")]
pub fn migrate_handle_hash(
    conn: &mut rusqlite::Connection,
    handle: &str,
    target_algo: &str,
) -> Result<String, String> {
    // Validate target algorithm is registered
    {
        let reg = global_registry().lock().unwrap();
        if reg.get(target_algo).is_none() {
            return Err(format!(
                "Unsupported target algorithm: '{}' (registered: {:?})",
                target_algo,
                reg.algorithms()
            ));
        }
    }

    // 1. Resolve the handle to its current, possibly-qualified reference.
    let current_hash: String = conn
        .query_row(
            "SELECT current_hash FROM handle_registry WHERE handle = ?",
            rusqlite::params![handle],
            |row| row.get(0),
        )
        .map_err(|_| format!("Handle '{}' not found in handle_registry", handle))?;

    // 2. Retrieve the exact existing content preimage.
    let content: Vec<u8> = lookup_content(conn, &current_hash)
        .ok_or_else(|| format!("Content not found in CAS for hash '{}'", current_hash))?;

    // 3. Create a fresh self-verifying record under the requested provider.
    let now_utc = chrono::Utc::now().to_rfc3339();
    let record = crate::layer0::mcard_record::MCardRecord::create_at(
        &content,
        Some(target_algo),
        Some(&now_utc),
        "UTC",
    )?;
    if !matches!(
        crate::layer0::mcard_record::verify_record(&record),
        crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
    ) {
        return Err("hash migration produced an invalid self-verifying record".to_string());
    }
    let new_hash = format!("{}{}", target_algo.trim_end_matches(':').to_lowercase() + ":", record.hash);

    // 4. Transactional update with retry for WAL lock contention.

    let max_attempts = 3;
    let mut last_err = String::new();
    for attempt in 0..max_attempts {
        let tx = match conn.transaction() {
            Ok(tx) => tx,
            Err(e) => {
                last_err = e.to_string();
                std::thread::sleep(std::time::Duration::from_millis(200));
                continue;
            }
        };
        let result = (|| {
            tx.execute(
                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
                rusqlite::params![&record.hash, &record.content, &record.g_time],
            )
            .map_err(|e| e.to_string())?;
            tx.execute(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)",
                rusqlite::params![handle, &current_hash, &now_utc],
            )
            .map_err(|e| e.to_string())?;
            tx.execute(
                "UPDATE handle_registry SET current_hash = ?, updated_at = ? WHERE handle = ?",
                rusqlite::params![&new_hash, &now_utc, handle],
            )
            .map_err(|e| e.to_string())?;
            tx.commit().map_err(|e| e.to_string())
        })();

        match result {
            Ok(()) => return Ok(new_hash),
            Err(e) => {
                last_err = e;
                if attempt + 1 < max_attempts {
                    std::thread::sleep(std::time::Duration::from_millis(200));
                }
            }
        }
    }

    Err(format!("Transaction failed after {} attempts: {}", max_attempts, last_err))
}

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

    #[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);
        conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')", rusqlite::params![h, content]).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 content = b"hello world";
        let hash_a = "sha256:aaa";
        let hash_b = "sha512:bbb";
        let hash_c = "sha256:ccc";
        conn.execute(
            "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
            rusqlite::params![hash_a, content],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
            rusqlite::params![hash_b, content],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')",
            rusqlite::params![hash_c, b"different"],
        )
        .unwrap();

        // Same content, different hashes → equivalent
        assert_eq!(content_equivalent(&conn, hash_a, hash_b).unwrap(), true);
        // Same hash → equivalent
        assert_eq!(content_equivalent(&conn, hash_a, hash_a).unwrap(), true);
        // Different content → not equivalent
        assert_eq!(content_equivalent(&conn, hash_a, hash_c).unwrap(), false);
        // Missing hash → not equivalent
        assert_eq!(content_equivalent(&conn, hash_a, "missing").unwrap(), false);
    }

    #[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);
        conn.execute("INSERT INTO card (hash, content, g_time) VALUES (?, ?, '2025-01-01')", rusqlite::params![h, content]).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());
    }
}