omega-cognitive-kernel 0.17.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
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
//! Disk persistence for kernel state (S2 product surface).

#[allow(unused_imports)]
use crate::prelude::*;

use crate::error::{OmegaError, Result};
use crate::memory::case::Case;
use crate::memory::strategy::Strategy;
use crate::types::{CognitivePatch, MetaMetrics, RuleEffect};
use alloc::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use std::fs;
#[cfg(feature = "async")]
use std::future::Future;
use std::io::Read;
use std::path::{Path, PathBuf};
#[cfg(feature = "async")]
use std::pin::Pin;

/// Constant defining default state path.
pub const DEFAULT_STATE_PATH: &str = ".omega/state.json";
/// Maximum serialized snapshot accepted by file and string loaders.
pub const MAX_SNAPSHOT_BYTES: u64 = 64 * 1024 * 1024;
/// Maximum number of entries in each persisted collection.
pub const MAX_SNAPSHOT_COLLECTION_ITEMS: usize = 1_000_000;

/// Current on-disk schema. Bump only with a migration path.
pub const CURRENT_SCHEMA_VERSION: u32 = 7;

fn default_schema_version() -> u32 {
    0
}

/// Pre-v2 default for the L1 self-modify master switch was `false` (safe).
fn default_self_modify_enabled() -> bool {
    false
}

/// Pre-v2 the cooldown counter started "warm" so the first patch could fire
/// immediately once self-modify was enabled.
fn default_steps_since_last_patch() -> u64 {
    100
}

fn default_l2_enabled() -> bool {
    // Missing legacy flags must not acquire permission to alter L0 on upgrade.
    false
}

fn default_l2_commit_threshold() -> f64 {
    0.82
}

fn default_l2_commit_cooldown() -> u64 {
    5
}

fn default_l2_negative_reward_required() -> u32 {
    3
}

fn default_l2_detector_window() -> usize {
    4
}

fn default_l2_detector_pred_threshold() -> f64 {
    0.58
}

fn default_l2_detector_self_ref_threshold() -> f64 {
    0.50
}

fn default_l2_detector_cooldown() -> usize {
    5
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Data structure representing external loop state.
pub struct ExternalLoopState {
    #[serde(default)]
    /// Identifier for the last external step.
    pub last_external_step_id: Option<u64>,
    /// Cooldown for this value.
    pub cooldown: crate::orchestrator::CooldownTracker,
    #[serde(default)]
    /// Identifier for the last checkpoint.
    pub last_checkpoint_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Most recent checkpoint UUID.
    pub last_checkpoint_uuid: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional current params.
    pub current_params: Option<std::collections::BTreeMap<String, f64>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Most recent checkpoint params.
    pub last_checkpoint_params: Option<std::collections::BTreeMap<String, f64>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Serializable snapshot of the kernel state.
pub struct KernelSnapshot {
    /// On-disk schema version. Missing / 0 treated as pre-0.5 and migrated up to
    /// [`CURRENT_SCHEMA_VERSION`] (currently 7) on load.
    #[serde(default = "default_schema_version")]
    pub version: u32,
    /// Total number of kernel steps completed.
    pub total_steps: u64,
    /// Mapping of biases.
    pub biases: BTreeMap<String, f64>,
    /// Mapping of constraints.
    pub constraints: BTreeMap<String, f64>,
    /// Number of CAS total.
    pub cas_total_steps: u64,
    /// Cas average prediction error for this value.
    pub cas_avg_prediction_error: f64,
    /// Cas adaptation score for this value.
    pub cas_adaptation_score: f64,
    /// Cognitive effect for this value.
    pub cognitive_effect: RuleEffect,
    /// Collection of cases.
    pub cases: Vec<Case>,
    /// Case capacity for this value.
    pub case_capacity: usize,
    /// Mapping of strategies.
    pub strategies: BTreeMap<String, Strategy>,
    /// Number of active cognitive modules.
    pub active_modules: BTreeMap<String, String>,
    /// Collection of patch history.
    pub patch_history: Vec<(CognitivePatch, String)>,
    #[serde(default = "default_l2_enabled")]
    /// Whether the L2 meta-controller is enabled.
    pub l2_enabled: bool,
    #[serde(default)]
    /// Whether L2 in fixed point is enabled or active.
    pub l2_in_fixed_point: bool,
    #[serde(default)]
    /// Number of L2 dwell.
    pub l2_dwell_steps: u64,
    #[serde(default)]
    /// L2 last alignment score for this value.
    pub l2_last_alignment_score: f64,
    #[serde(default = "default_l2_commit_threshold")]
    /// L2 commit threshold for this value.
    pub l2_commit_threshold: f64,
    #[serde(default = "default_l2_commit_cooldown")]
    /// Number of L2 commit cooldown.
    pub l2_commit_cooldown_steps: u64,
    #[serde(default)]
    /// L2 commit cooldown remaining for this value.
    pub l2_commit_cooldown_remaining: u64,
    #[serde(default)]
    /// L2 last consequence score for this value.
    pub l2_last_consequence_score: f64,
    #[serde(default)]
    /// Whether L2 is operating in defensive mode.
    pub l2_defensive_mode: bool,
    #[serde(default)]
    /// Number of consecutive negative consequences observed by L2.
    pub l2_negative_consequence_streak: u32,
    #[serde(default)]
    /// Number of L2 stable consequence.
    pub l2_stable_consequence_steps: u32,
    #[serde(default)]
    /// L2 reward change score for this value.
    pub l2_reward_change_score: f64,
    #[serde(default)]
    /// L2 error change score for this value.
    pub l2_error_change_score: f64,
    #[serde(default)]
    /// Whether L2 awaiting consequence is enabled or active.
    pub l2_awaiting_consequence: bool,
    #[serde(default)]
    /// L2 negative reward streak for this value.
    pub l2_negative_reward_streak: u32,
    #[serde(default = "default_l2_negative_reward_required")]
    /// L2 negative reward required for this value.
    pub l2_negative_reward_required: u32,
    #[serde(default)]
    /// Collection of L2 detector history.
    pub l2_detector_history: Vec<MetaMetrics>,
    #[serde(default = "default_l2_detector_window")]
    /// L2 detector window for this value.
    pub l2_detector_window: usize,
    #[serde(default = "default_l2_detector_pred_threshold")]
    /// L2 detector pred threshold for this value.
    pub l2_detector_pred_threshold: f64,
    #[serde(default = "default_l2_detector_self_ref_threshold")]
    /// L2 detector self ref threshold for this value.
    pub l2_detector_self_ref_threshold: f64,
    #[serde(default = "default_l2_detector_cooldown")]
    /// Number of L2 detector cooldown.
    pub l2_detector_cooldown_steps: usize,
    #[serde(default)]
    /// L2 detector cooldown remaining for this value.
    pub l2_detector_cooldown_remaining: usize,
    /// L1 self-modify master switch (v2+). Restored so that enabling L1 then
    /// restarting does not silently fall back to the safe default-off.
    #[serde(default = "default_self_modify_enabled")]
    pub self_modify_enabled: bool,
    /// L1 patch cooldown counter (v2+). Restored so a restart cannot reset the
    /// min-steps-between-patches cooldown.
    #[serde(default = "default_steps_since_last_patch")]
    pub steps_since_last_patch: u64,
    /// L2 rollback policy snapshot (v2+). Restored so that after an L2 commit a
    /// restart retains the pre-commit policy needed for negative-feedback rollback.
    #[serde(default)]
    pub l2_rollback_effect: Option<RuleEffect>,
    /// Last UCB-backed L2 decision, available to status and trajectory replay.
    #[serde(default)]
    pub last_l2_decision: Option<crate::types::L2DecisionRecord>,
    /// Complete local bandit state when the kernel uses BanditUcbDecisionMaker.
    #[serde(default)]
    pub bandit_ucb: Option<crate::l0::bandit_decision::BanditUcbSnapshot>,
    #[serde(default)]
    /// Bandit config for this value.
    pub bandit_config: crate::types::BanditConfig,
    #[serde(default)]
    /// Optional L1 previous effect.
    pub l1_previous_effect: Option<RuleEffect>,
    #[serde(default)]
    /// Whether L1 pending rollback is enabled or active.
    pub l1_pending_rollback: bool,
    /// Resident L2 controller and one-step pending policy (v4+). Missing legacy
    /// state is dormant with zero trust, so migration cannot inject a bias.
    #[serde(default)]
    pub l2_controller: crate::l2::control::ResidentController,
    #[serde(default)]
    /// L2 policy proposed but not yet applied.
    pub l2_pending_policy: crate::types::L2Policy,
    #[serde(default)]
    /// L2 policy currently applied at the control boundary.
    pub l2_applied_policy: crate::types::L2Policy,
    #[serde(default)]
    /// Whether L2 pending L1 rollback is enabled or active.
    pub l2_pending_l1_rollback: bool,
    #[serde(default)]
    /// L2 last reward for this value.
    pub l2_last_reward: f64,
    /// Per-instance prioritized-replay cursor (v6+), independent of other kernels.
    #[serde(default)]
    pub case_sample_counter: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional external loop.
    pub external_loop: Option<ExternalLoopState>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional Adaptive Kernel Protocol v1 durable state (introduced in schema v7).
    pub adaptive_state: Option<crate::adaptive::AdaptivePersistedState>,
}

impl Default for KernelSnapshot {
    fn default() -> Self {
        Self {
            version: CURRENT_SCHEMA_VERSION,
            total_steps: 0,
            biases: BTreeMap::new(),
            constraints: BTreeMap::new(),
            cas_total_steps: 0,
            cas_avg_prediction_error: 0.0,
            cas_adaptation_score: 0.0,
            cognitive_effect: RuleEffect::default(),
            cases: Vec::new(),
            case_capacity: 256,
            strategies: BTreeMap::new(),
            active_modules: BTreeMap::new(),
            patch_history: Vec::new(),
            l2_enabled: true,
            l2_in_fixed_point: false,
            l2_dwell_steps: 0,
            l2_last_alignment_score: 0.0,
            l2_commit_threshold: default_l2_commit_threshold(),
            l2_commit_cooldown_steps: default_l2_commit_cooldown(),
            l2_commit_cooldown_remaining: 0,
            l2_last_consequence_score: 0.0,
            l2_defensive_mode: false,
            l2_negative_consequence_streak: 0,
            l2_stable_consequence_steps: 0,
            l2_reward_change_score: 0.0,
            l2_error_change_score: 0.0,
            l2_awaiting_consequence: false,
            l2_negative_reward_streak: 0,
            l2_negative_reward_required: default_l2_negative_reward_required(),
            l2_detector_history: Vec::new(),
            l2_detector_window: 4,
            l2_detector_pred_threshold: 0.58,
            l2_detector_self_ref_threshold: 0.50,
            l2_detector_cooldown_steps: 5,
            l2_detector_cooldown_remaining: 0,
            self_modify_enabled: false,
            steps_since_last_patch: default_steps_since_last_patch(),
            l2_rollback_effect: None,
            last_l2_decision: None,
            bandit_ucb: None,
            bandit_config: crate::types::BanditConfig::default(),
            l1_previous_effect: None,
            l1_pending_rollback: false,
            l2_controller: crate::l2::control::ResidentController::default(),
            l2_pending_policy: crate::types::L2Policy::default(),
            l2_applied_policy: crate::types::L2Policy::default(),
            l2_pending_l1_rollback: false,
            l2_last_reward: 0.5,
            case_sample_counter: 0,
            external_loop: None,
            adaptive_state: None,
        }
    }
}

impl KernelSnapshot {
    /// Migrate older snapshots into `CURRENT_SCHEMA_VERSION`.
    pub fn migrate(mut self) -> Result<Self> {
        if self.version > CURRENT_SCHEMA_VERSION {
            return Err(OmegaError::Persist(format!(
                "state schema version {} is newer than supported {}",
                self.version, CURRENT_SCHEMA_VERSION
            )));
        }
        if self.version < 1 {
            // v0 → v1: case.priority backfill happens in CaseMemory::restore;
            // ensure capacity is sane and stamp version.
            if self.case_capacity == 0 {
                self.case_capacity = 256;
            }
            self.version = 1;
        }
        if self.version < 2 {
            // v1 → v2: the new safety fields (`self_modify_enabled`,
            // `steps_since_last_patch`, `l2_rollback_effect`) are absent from v1
            // snapshots and therefore already carry their serde defaults. The
            // defaults are intentionally the *safe* pre-v2 behavior: L1 disabled
            // and a warm cooldown. Nothing to backfill beyond stamping the version.
            self.version = 2;
        }
        if self.version < 3 {
            // v3 adds optional UCB statistics and decision explanations. Their
            // defaults preserve the old policy and never enable self-modification.
            self.version = 3;
        }
        if self.version < 4 {
            // v4 adds the resident controller, bounded meta-cache and pending
            // policy. Serde defaults fail closed to DORMANT and KEEP_L0.
            self.l2_pending_policy = crate::types::L2Policy::default();
            self.l2_applied_policy = crate::types::L2Policy::default();
            self.version = 4;
        }
        if self.version < 5 {
            // v5 makes the online Dayan state, duplicate-feedback guard and
            // normalized propensity snapshots explicit. Missing v4 fields are
            // safe serde defaults; permission remains opt-in, never inferred
            // from the presence of a resident controller or a cache entry.
            self.l2_pending_policy = self.l2_pending_policy.effective();
            self.l2_applied_policy = self.l2_applied_policy.effective();
            if !self.l2_enabled {
                self.l2_pending_policy = crate::types::L2Policy::default();
                self.l2_applied_policy = crate::types::L2Policy::default();
                self.l2_controller.gate_state = crate::l2::control::L2GateState::Dormant;
                self.l2_controller.trust.alpha = 0.0;
            }
            self.version = 5;
        }
        if self.version < 6 {
            // v6 makes replay sampling local to the case-memory instance. Legacy
            // snapshots have no meaningful global cursor, so start at zero.
            self.case_sample_counter = 0;
            self.version = 6;
        }
        if self.version < 7 {
            // v7 introduces optional durable Adaptive Kernel Protocol v1 state.
            // Legacy v6 snapshots never grant active adaptation permission.
            if let Some(adaptive) = self.adaptive_state.as_mut() {
                adaptive.active_permission_granted = false;
                adaptive.mode = crate::adaptive::AdaptiveMode::Keep;
            }
            self.version = 7;
        }
        Ok(self)
    }

    /// Redact known user-provided goal text before writing a snapshot.
    /// Numeric learning state and schema remain unchanged.
    pub fn redact_user_content(&mut self) {
        for case in &mut self.cases {
            case.goal = "[REDACTED]".into();
        }
    }

    /// Saves to.
    pub fn save_to(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            crate::private_fs::create_dir_all(parent)
                .map_err(|e| OmegaError::Persist(e.to_string()))?;
        }
        let mut snap = self.clone();
        snap.version = CURRENT_SCHEMA_VERSION;
        let json =
            serde_json::to_string_pretty(&snap).map_err(|e| OmegaError::Persist(e.to_string()))?;
        let parent = path.parent().unwrap_or_else(|| Path::new("."));
        let file_name = path
            .file_name()
            .and_then(|name| name.to_str())
            .ok_or_else(|| {
                OmegaError::Persist(format!("invalid state path: {}", path.display()))
            })?;
        let temp_path = parent.join(format!(".{file_name}.{}.tmp", crate::new_uuid()));
        let result = (|| -> Result<()> {
            use std::io::Write;
            let mut file = crate::private_fs::open_options()
                .write(true)
                .create_new(true)
                .open(&temp_path)
                .map_err(|e| OmegaError::Persist(format!("state temp create: {e}")))?;
            file.write_all(json.as_bytes())
                .and_then(|()| file.sync_all())
                .map_err(|e| OmegaError::Persist(format!("state temp write: {e}")))?;
            fs::rename(&temp_path, path)
                .map_err(|e| OmegaError::Persist(format!("state atomic replace: {e}")))?;
            Ok(())
        })();
        if result.is_err() {
            let _ = fs::remove_file(&temp_path);
        }
        result
    }

    /// Loads from.
    pub fn load_from(path: &Path) -> Result<Self> {
        let mut file = fs::File::open(path).map_err(|e| OmegaError::Persist(e.to_string()))?;
        let mut data = String::new();
        file.by_ref()
            .take(MAX_SNAPSHOT_BYTES + 1)
            .read_to_string(&mut data)
            .map_err(|e| OmegaError::Persist(e.to_string()))?;
        if data.len() as u64 > MAX_SNAPSHOT_BYTES {
            return Err(OmegaError::Persist(format!(
                "snapshot byte limit exceeded: maximum {MAX_SNAPSHOT_BYTES} bytes"
            )));
        }
        Self::from_json(&data)
    }

    /// Converts this value to JSON.
    pub fn to_json(&self) -> Result<String> {
        serde_json::to_string(self).map_err(|e| OmegaError::Persist(e.to_string()))
    }

    /// Creates a value from JSON.
    pub fn from_json(json: &str) -> Result<Self> {
        if json.len() as u64 > MAX_SNAPSHOT_BYTES {
            return Err(OmegaError::Persist(format!(
                "snapshot byte limit exceeded: maximum {MAX_SNAPSHOT_BYTES} bytes"
            )));
        }
        let snap: Self =
            serde_json::from_str(json).map_err(|e| OmegaError::Persist(e.to_string()))?;
        let collection_sizes = [
            snap.cases.len(),
            snap.strategies.len(),
            snap.biases.len(),
            snap.constraints.len(),
            snap.active_modules.len(),
            snap.patch_history.len(),
            snap.l2_detector_history.len(),
        ];
        if collection_sizes
            .into_iter()
            .any(|size| size > MAX_SNAPSHOT_COLLECTION_ITEMS)
        {
            return Err(OmegaError::Persist(format!(
                "snapshot collection item limit exceeded: maximum {MAX_SNAPSHOT_COLLECTION_ITEMS}"
            )));
        }
        snap.migrate()
    }
}

/// Resolves the effective value from the supplied inputs.
pub fn resolve_state_path(explicit: Option<&str>) -> PathBuf {
    explicit
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(DEFAULT_STATE_PATH))
}
/// Pluggable persistence backend for [`KernelSnapshot`].
///
/// Default local file persistence is provided by [`FileStateStore`], and an
/// in-memory backend for tests or ephemeral runtimes is provided by
/// [`MemoryStateStore`]. Future server backends (SQLite, Redis, Postgres)
/// can implement this trait without altering core orchestration.
pub trait StateStore: Send + Sync {
    /// Load the latest persisted snapshot, or `Ok(None)` if no state exists yet.
    fn load_snapshot(&self) -> Result<Option<KernelSnapshot>>;

    /// Persist a snapshot atomically to the backing store.
    fn save_snapshot(&self, snapshot: &KernelSnapshot) -> Result<()>;
}

impl<T: StateStore + ?Sized> StateStore for std::sync::Arc<T> {
    fn load_snapshot(&self) -> Result<Option<KernelSnapshot>> {
        (**self).load_snapshot()
    }

    fn save_snapshot(&self, snapshot: &KernelSnapshot) -> Result<()> {
        (**self).save_snapshot(snapshot)
    }
}

/// Boxed future returned by [`AsyncStateStore`] operations.
#[cfg(feature = "async")]
pub type AsyncStateStoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;

/// Asynchronous access to persisted kernel snapshots.
///
/// The boxed-future contract remains compatible with the Rust 1.89 MSRV proposed for the next release.
/// Implementations should replace a snapshot atomically and return an error
/// when a snapshot cannot be loaded or durably stored.
#[cfg(feature = "async")]
pub trait AsyncStateStore: Send + Sync {
    /// Load the latest persisted snapshot, or `Ok(None)` when no state exists.
    fn load_snapshot(&self) -> AsyncStateStoreFuture<'_, Option<KernelSnapshot>>;

    /// Persist a snapshot atomically to the backing store.
    fn save_snapshot<'a>(&'a self, snapshot: &'a KernelSnapshot) -> AsyncStateStoreFuture<'a, ()>;
}

/// Runs a synchronous [`StateStore`] on Tokio's blocking thread pool.
///
/// This adapter is useful for existing file and SQLite stores when called from
/// an async application. Cancelling the returned future does not cancel a
/// blocking operation that has already started; snapshot writes remain atomic
/// and may complete after the caller stops awaiting them.
#[cfg(feature = "async")]
#[derive(Clone)]
pub struct AsyncStateStoreAdapter {
    store: std::sync::Arc<dyn StateStore>,
}

#[cfg(feature = "async")]
impl AsyncStateStoreAdapter {
    /// Wrap a synchronous store for asynchronous use.
    pub fn new(store: impl StateStore + 'static) -> Self {
        Self {
            store: std::sync::Arc::new(store),
        }
    }

    /// Wrap a shared synchronous store without allocating another store value.
    pub fn from_shared(store: std::sync::Arc<dyn StateStore>) -> Self {
        Self { store }
    }
}

#[cfg(feature = "async")]
impl core::fmt::Debug for AsyncStateStoreAdapter {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("AsyncStateStoreAdapter")
            .finish_non_exhaustive()
    }
}

#[cfg(feature = "async")]
impl AsyncStateStore for AsyncStateStoreAdapter {
    fn load_snapshot(&self) -> AsyncStateStoreFuture<'_, Option<KernelSnapshot>> {
        let store = std::sync::Arc::clone(&self.store);
        Box::pin(async move {
            let runtime = tokio::runtime::Handle::try_current().map_err(|error| {
                OmegaError::Persist(format!(
                    "async state-store operation requires an active Tokio runtime: {error}"
                ))
            })?;
            runtime
                .spawn_blocking(move || store.load_snapshot())
                .await
                .map_err(|error| {
                    OmegaError::Persist(format!("async state-store worker failed: {error}"))
                })?
        })
    }

    fn save_snapshot<'a>(&'a self, snapshot: &'a KernelSnapshot) -> AsyncStateStoreFuture<'a, ()> {
        let store = std::sync::Arc::clone(&self.store);
        Box::pin(async move {
            let runtime = tokio::runtime::Handle::try_current().map_err(|error| {
                OmegaError::Persist(format!(
                    "async state-store operation requires an active Tokio runtime: {error}"
                ))
            })?;
            let snapshot = snapshot.clone();
            runtime
                .spawn_blocking(move || store.save_snapshot(&snapshot))
                .await
                .map_err(|error| {
                    OmegaError::Persist(format!("async state-store worker failed: {error}"))
                })?
        })
    }
}

/// Local filesystem implementation of [`StateStore`] backed by [`KernelSnapshot::save_to`].
#[derive(Debug, Clone)]
pub struct FileStateStore {
    path: PathBuf,
}

impl FileStateStore {
    /// Creates a file-backed store that reads and writes snapshots at `path`.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    /// Returns the path used for the persisted snapshot.
    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl StateStore for FileStateStore {
    fn load_snapshot(&self) -> Result<Option<KernelSnapshot>> {
        if !self.path.exists() {
            return Ok(None);
        }
        KernelSnapshot::load_from(&self.path).map(Some)
    }

    fn save_snapshot(&self, snapshot: &KernelSnapshot) -> Result<()> {
        snapshot.save_to(&self.path)
    }
}

/// Thread-safe in-memory [`StateStore`] for tests and ephemeral runtimes.
#[derive(Debug, Default)]
pub struct MemoryStateStore {
    slot: std::sync::RwLock<Option<KernelSnapshot>>,
}

impl MemoryStateStore {
    /// Creates an empty in-memory snapshot store.
    pub fn new() -> Self {
        Self::default()
    }
}

impl StateStore for MemoryStateStore {
    fn load_snapshot(&self) -> Result<Option<KernelSnapshot>> {
        let guard = self
            .slot
            .read()
            .map_err(|_| OmegaError::Persist(String::from("memory state store lock poisoned")))?;
        Ok(guard.clone())
    }

    fn save_snapshot(&self, snapshot: &KernelSnapshot) -> Result<()> {
        let mut guard = self
            .slot
            .write()
            .map_err(|_| OmegaError::Persist(String::from("memory state store lock poisoned")))?;
        *guard = Some(snapshot.clone());
        Ok(())
    }
}

/// SQLite-backed [`StateStore`] for applications that enable the `sqlite` feature.
///
/// The feature links to system SQLite (not a bundled copy) and requires SQLite
/// 3.54.0 or newer. Both constructors reject older linked versions before opening
/// or creating a database. File-backed stores use WAL mode, a configurable busy
/// timeout (five seconds by default), and transactional snapshot replacement.
#[cfg(feature = "sqlite")]
#[derive(Debug)]
pub struct SqliteStateStore {
    connection: std::sync::Mutex<rusqlite::Connection>,
}

#[cfg(feature = "sqlite")]
const MIN_SQLITE_VERSION_NUMBER: i32 = 3_054_000;

/// Default SQLite lock wait before a busy operation returns an error.
#[cfg(feature = "sqlite")]
pub const DEFAULT_SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

#[cfg(feature = "sqlite")]
fn validate_sqlite_version_number(version_number: i32, version: &str) -> Result<()> {
    if version_number < MIN_SQLITE_VERSION_NUMBER {
        return Err(OmegaError::Persist(format!(
            "SqliteStateStore requires system SQLite 3.54.0 or newer; linked SQLite is {version} ({version_number})"
        )));
    }
    Ok(())
}

#[cfg(feature = "sqlite")]
fn ensure_supported_sqlite_version() -> Result<()> {
    validate_sqlite_version_number(rusqlite::version_number(), rusqlite::version())
}

#[cfg(all(test, feature = "sqlite"))]
mod sqlite_version_tests {
    use super::validate_sqlite_version_number;

    #[test]
    fn rejects_vulnerable_sqlite_versions() {
        let error = validate_sqlite_version_number(3_053_999, "3.53.999")
            .expect_err("SQLite before 3.54.0 must be rejected");
        assert!(error.to_string().contains("SQLite 3.54.0 or newer"));
        assert!(error.to_string().contains("3.53.999"));
    }

    #[test]
    fn accepts_the_minimum_patched_sqlite_version() {
        validate_sqlite_version_number(3_054_000, "3.54.0")
            .expect("SQLite 3.54.0 is the minimum supported version");
    }
}

#[cfg(feature = "sqlite")]
impl SqliteStateStore {
    /// Open or create a file-backed SQLite state database.
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        Self::open_with_busy_timeout(path, DEFAULT_SQLITE_BUSY_TIMEOUT)
    }

    /// Open a file-backed database with an explicit SQLite lock wait duration.
    ///
    /// Pass [`std::time::Duration::ZERO`] to fail immediately on lock
    /// contention. WAL mode remains enabled for file-backed databases.
    pub fn open_with_busy_timeout(
        path: impl AsRef<Path>,
        busy_timeout: std::time::Duration,
    ) -> Result<Self> {
        ensure_supported_sqlite_version()?;
        let path = path.as_ref();
        if let Some(parent) = path
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty())
        {
            crate::private_fs::create_dir_all(parent)
                .map_err(|error| sqlite_persist_error("create SQLite state directory", error))?;
        }
        if !path.exists() {
            match crate::private_fs::open_options()
                .write(true)
                .create_new(true)
                .open(path)
            {
                Ok(file) => drop(file),
                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
                Err(error) => {
                    return Err(sqlite_persist_error("create SQLite state database", error));
                }
            }
        }
        let connection = rusqlite::Connection::open(path)
            .map_err(|error| sqlite_persist_error("open SQLite state database", error))?;
        Self::from_connection(connection, true, busy_timeout)
    }

    /// Create an ephemeral, in-memory SQLite state database.
    pub fn open_in_memory() -> Result<Self> {
        Self::open_in_memory_with_busy_timeout(DEFAULT_SQLITE_BUSY_TIMEOUT)
    }

    /// Create an in-memory database with an explicit SQLite lock wait duration.
    pub fn open_in_memory_with_busy_timeout(busy_timeout: std::time::Duration) -> Result<Self> {
        ensure_supported_sqlite_version()?;
        let connection = rusqlite::Connection::open_in_memory()
            .map_err(|error| sqlite_persist_error("open in-memory SQLite state database", error))?;
        Self::from_connection(connection, false, busy_timeout)
    }

    fn from_connection(
        connection: rusqlite::Connection,
        use_wal: bool,
        busy_timeout: std::time::Duration,
    ) -> Result<Self> {
        connection
            .busy_timeout(busy_timeout)
            .map_err(|error| sqlite_persist_error("configure SQLite busy timeout", error))?;

        if use_wal {
            let journal_mode: String = connection
                .query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))
                .map_err(|error| sqlite_persist_error("enable SQLite WAL mode", error))?;
            if !journal_mode.eq_ignore_ascii_case("wal") {
                return Err(OmegaError::Persist(format!(
                    "SQLite refused WAL mode (reported {journal_mode})"
                )));
            }
        }

        connection
            .execute_batch(
                "PRAGMA synchronous = FULL;
                 CREATE TABLE IF NOT EXISTS omega_state (
                     singleton_id INTEGER PRIMARY KEY CHECK (singleton_id = 1),
                     schema_version INTEGER NOT NULL,
                     updated_at TEXT NOT NULL,
                     payload TEXT NOT NULL
                 );",
            )
            .map_err(|error| sqlite_persist_error("initialize SQLite state schema", error))?;

        Ok(Self {
            connection: std::sync::Mutex::new(connection),
        })
    }
}

#[cfg(feature = "sqlite")]
impl StateStore for SqliteStateStore {
    fn load_snapshot(&self) -> Result<Option<KernelSnapshot>> {
        use rusqlite::OptionalExtension;

        let connection = self
            .connection
            .lock()
            .map_err(|_| OmegaError::Persist(String::from("SQLite state store lock poisoned")))?;
        let record = connection
            .query_row(
                "SELECT schema_version, updated_at, payload
                 FROM omega_state WHERE singleton_id = 1",
                [],
                |row| {
                    Ok((
                        row.get::<_, i64>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, String>(2)?,
                    ))
                },
            )
            .optional()
            .map_err(|error| sqlite_persist_error("read SQLite state snapshot", error))?;

        let Some((schema_version, updated_at, payload)) = record else {
            return Ok(None);
        };
        if schema_version < 0 {
            return Err(OmegaError::Persist(format!(
                "invalid negative SQLite state schema version {schema_version}"
            )));
        }
        if schema_version > i64::from(CURRENT_SCHEMA_VERSION) {
            return Err(OmegaError::Persist(format!(
                "SQLite state schema version {schema_version} is newer than supported {CURRENT_SCHEMA_VERSION}"
            )));
        }
        crate::types::UtcTimestamp::from_rfc3339(&updated_at).map_err(|error| {
            OmegaError::Persist(format!(
                "invalid SQLite state updated_at timestamp: {error}"
            ))
        })?;

        if payload.len() as u64 > MAX_SNAPSHOT_BYTES {
            return Err(OmegaError::Persist(format!(
                "SQLite snapshot byte limit exceeded: maximum {MAX_SNAPSHOT_BYTES} bytes"
            )));
        }

        let payload_value: serde_json::Value = serde_json::from_str(&payload)
            .map_err(|error| sqlite_persist_error("decode SQLite snapshot schema", error))?;
        let payload_version = match payload_value.get("version") {
            None => 0,
            Some(version) => {
                let version = version.as_u64().ok_or_else(|| {
                    OmegaError::Persist(String::from(
                        "SQLite snapshot schema version is not a non-negative integer",
                    ))
                })?;
                u32::try_from(version).map_err(|_| {
                    OmegaError::Persist(String::from(
                        "SQLite snapshot schema version exceeds the supported integer range",
                    ))
                })?
            }
        };
        if i64::from(payload_version) != schema_version {
            return Err(OmegaError::Persist(format!(
                "SQLite state schema metadata ({schema_version}) does not match snapshot payload ({payload_version})"
            )));
        }

        KernelSnapshot::from_json(&payload).map(Some)
    }

    fn save_snapshot(&self, snapshot: &KernelSnapshot) -> Result<()> {
        let mut persisted_snapshot = snapshot.clone();
        persisted_snapshot.version = CURRENT_SCHEMA_VERSION;
        let payload = serde_json::to_string(&persisted_snapshot)
            .map_err(|error| sqlite_persist_error("serialize SQLite state snapshot", error))?;
        if payload.len() as u64 > MAX_SNAPSHOT_BYTES {
            return Err(OmegaError::Persist(format!(
                "SQLite snapshot byte limit exceeded: maximum {MAX_SNAPSHOT_BYTES} bytes"
            )));
        }
        let updated_at = crate::types::UtcTimestamp::now().to_rfc3339();

        let mut connection = self
            .connection
            .lock()
            .map_err(|_| OmegaError::Persist(String::from("SQLite state store lock poisoned")))?;
        let transaction = connection
            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
            .map_err(|error| sqlite_persist_error("begin SQLite snapshot transaction", error))?;
        transaction
            .execute(
                "INSERT INTO omega_state (singleton_id, schema_version, updated_at, payload)
                 VALUES (1, ?1, ?2, ?3)
                 ON CONFLICT(singleton_id) DO UPDATE SET
                     schema_version = excluded.schema_version,
                     updated_at = excluded.updated_at,
                     payload = excluded.payload",
                rusqlite::params![i64::from(CURRENT_SCHEMA_VERSION), updated_at, payload],
            )
            .map_err(|error| sqlite_persist_error("write SQLite state snapshot", error))?;
        transaction
            .commit()
            .map_err(|error| sqlite_persist_error("commit SQLite snapshot transaction", error))
    }
}

#[cfg(feature = "sqlite")]
fn sqlite_persist_error(context: &str, error: impl core::fmt::Display) -> OmegaError {
    OmegaError::Persist(format!("{context}: {error}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::RuleEffect;
    use std::env::temp_dir;

    #[test]
    fn new_snapshots_enable_l2_but_not_l1_self_modification() {
        let snapshot = KernelSnapshot::default();
        assert!(snapshot.l2_enabled);
        assert!(!snapshot.self_modify_enabled);
    }

    #[test]
    fn snapshot_json_rejects_input_over_byte_limit() {
        let oversized = " ".repeat(MAX_SNAPSHOT_BYTES as usize + 1);
        let err = KernelSnapshot::from_json(&oversized)
            .unwrap_err()
            .to_string();
        assert!(err.contains("snapshot byte limit exceeded"), "{err}");
    }
    #[test]
    fn roundtrip_snapshot_file() {
        let path = temp_dir().join(format!("omega-s2-{}.json", crate::new_uuid()));
        let snap = KernelSnapshot {
            version: 1,
            total_steps: 7,
            biases: BTreeMap::from([("stabilize".into(), 0.2)]),
            constraints: BTreeMap::from([("max_risk".into(), 0.65)]),
            cas_total_steps: 7,
            cas_avg_prediction_error: 0.33,
            cas_adaptation_score: 0.67,
            cognitive_effect: RuleEffect {
                error_damping: 0.7,
                action_preference: BTreeMap::from([("stabilize".into(), 1.5)]),
                min_uncertainty: 0.08,
                explore_bonus: -0.2,
                risk_tolerance: 0.4,
            },
            cases: vec![],
            case_capacity: 256,
            strategies: BTreeMap::new(),
            active_modules: BTreeMap::from([("cognitive_rules".into(), "fn x() {}".into())]),
            patch_history: vec![],
            ..KernelSnapshot::default()
        };
        snap.save_to(&path).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(
                fs::metadata(&path).unwrap().permissions().mode() & 0o777,
                0o600
            );
        }
        let loaded = KernelSnapshot::load_from(&path).unwrap();
        assert_eq!(loaded.version, CURRENT_SCHEMA_VERSION);
        assert_eq!(loaded.total_steps, 7);
        assert!((loaded.cognitive_effect.error_damping - 0.7).abs() < 1e-9);
        assert!((loaded.cognitive_effect.explore_bonus + 0.2).abs() < 1e-9);
        assert!((loaded.cognitive_effect.risk_tolerance - 0.4).abs() < 1e-9);
        let _ = fs::remove_file(&path);
    }

    #[test]
    #[cfg(unix)]
    fn failed_atomic_replace_preserves_previous_state() {
        let dir = temp_dir().join(format!("omega-atomic-{}", crate::new_uuid()));
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("state.json");
        fs::create_dir(&path).unwrap();
        fs::write(path.join("marker"), b"previous-state").unwrap();

        let error = KernelSnapshot::default().save_to(&path).unwrap_err();
        assert!(error.to_string().contains("atomic replace"), "{error}");
        assert_eq!(
            fs::read_to_string(path.join("marker")).unwrap(),
            "previous-state"
        );
        assert!(fs::read_dir(&dir)
            .unwrap()
            .filter_map(std::result::Result::ok)
            .all(|entry| entry.path().extension().and_then(|x| x.to_str()) != Some("tmp")));

        let _ = fs::remove_dir_all(dir);
    }

    #[test]
    fn migrates_version_one_to_current() {
        // A v1 snapshot lacks the v2 safety fields entirely; they must default.
        let path = temp_dir().join(format!("omega-v1-{}.json", crate::new_uuid()));
        let raw = r#"{
            "version": 1,
            "total_steps": 12,
            "biases": {},
            "constraints": {},
            "cas_total_steps": 12,
            "cas_avg_prediction_error": 0.1,
            "cas_adaptation_score": 0.9,
            "cognitive_effect": {
                "error_damping": 1.0,
                "action_preference": {},
                "min_uncertainty": 0.05,
                "explore_bonus": 0.0,
                "risk_tolerance": 0.5
            },
            "cases": [],
            "case_capacity": 256,
            "strategies": {},
            "active_modules": {},
            "patch_history": []
        }"#;
        fs::write(&path, raw).unwrap();
        let loaded = KernelSnapshot::load_from(&path).unwrap();
        assert_eq!(loaded.version, CURRENT_SCHEMA_VERSION);
        assert_eq!(loaded.total_steps, 12);
        assert!(!loaded.self_modify_enabled);
        assert_eq!(loaded.steps_since_last_patch, 100);
        assert!(loaded.l2_rollback_effect.is_none());
        assert!(loaded.last_l2_decision.is_none());
        assert_eq!(loaded.bandit_config.min_dwell_steps, 3);
        assert_eq!(
            loaded.l2_controller.gate_state,
            crate::l2::control::L2GateState::Dormant
        );
        assert_eq!(loaded.l2_controller.trust.alpha, 0.0);
        assert!(!loaded.l2_pending_policy.committed);
        assert!(!loaded.l2_applied_policy.committed);
        assert!(loaded.l2_controller.cache.entries.is_empty());
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn roundtrips_v2_safety_fields() {
        let path = temp_dir().join(format!("omega-v2rt-{}.json", crate::new_uuid()));
        let mut snap = KernelSnapshot {
            total_steps: 42,
            ..KernelSnapshot::default()
        };
        snap.self_modify_enabled = true;
        snap.steps_since_last_patch = 3;
        snap.l2_rollback_effect = Some(RuleEffect {
            error_damping: 0.42,
            explore_bonus: 0.11,
            ..RuleEffect::default()
        });
        snap.save_to(&path).unwrap();
        let loaded = KernelSnapshot::load_from(&path).unwrap();
        assert_eq!(loaded.version, CURRENT_SCHEMA_VERSION);
        assert!(loaded.self_modify_enabled);
        assert_eq!(loaded.steps_since_last_patch, 3);
        let rb = loaded
            .l2_rollback_effect
            .expect("rollback effect persisted");
        assert!((rb.error_damping - 0.42).abs() < 1e-9);
        assert!((rb.explore_bonus - 0.11).abs() < 1e-9);
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn migrates_version_zero() {
        let path = temp_dir().join(format!("omega-mig-{}.json", crate::new_uuid()));
        // Pre-0.5 style: omit version field entirely.
        let raw = r#"{
            "total_steps": 3,
            "biases": {},
            "constraints": {"max_risk": 0.65},
            "cas_total_steps": 3,
            "cas_avg_prediction_error": 0.2,
            "cas_adaptation_score": 0.5,
            "cognitive_effect": {
                "error_damping": 1.0,
                "action_preference": {},
                "min_uncertainty": 0.05,
                "explore_bonus": 0.0,
                "risk_tolerance": 0.5
            },
            "cases": [],
            "case_capacity": 0,
            "strategies": {},
            "active_modules": {},
            "patch_history": []
        }"#;
        fs::write(&path, raw).unwrap();
        let loaded = KernelSnapshot::load_from(&path).unwrap();
        assert_eq!(loaded.version, CURRENT_SCHEMA_VERSION);
        assert_eq!(loaded.case_capacity, 256);
        assert_eq!(loaded.total_steps, 3);
        // v2 safety fields fall back to their safe defaults when migrating v0.
        assert!(!loaded.self_modify_enabled);
        assert!(loaded.l2_rollback_effect.is_none());
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn migrates_v3_and_v4_without_inventing_l2_permission() {
        for version in [3, 4] {
            let mut value = serde_json::to_value(KernelSnapshot::default()).unwrap();
            value["version"] = serde_json::json!(version);
            value["l2_enabled"] = serde_json::json!(false);
            value["l2_controller"]["gate_state"] = serde_json::json!("ACTIVE");
            value["l2_controller"]["trust"]["alpha"] = serde_json::json!(0.9);
            value["l2_pending_policy"]["committed"] = serde_json::json!(true);
            value["l2_applied_policy"]["committed"] = serde_json::json!(true);

            let migrated = KernelSnapshot::from_json(&value.to_string()).unwrap();
            assert_eq!(migrated.version, CURRENT_SCHEMA_VERSION);
            assert!(!migrated.l2_enabled);
            assert_eq!(
                migrated.l2_controller.gate_state,
                crate::l2::control::L2GateState::Dormant
            );
            assert_eq!(migrated.l2_controller.trust.alpha, 0.0);
            assert!(!migrated.l2_pending_policy.committed);
            assert!(!migrated.l2_applied_policy.committed);
        }
    }

    #[test]
    fn legacy_decision_cannot_claim_an_l2_intervention() {
        let mut value = serde_json::to_value(crate::types::L2DecisionRecord {
            selected_arm: 0,
            selected_bias: "stabilize".into(),
            candidate_arm: 1,
            mean_reward: 0.5,
            exploration_bonus: 0.1,
            ucb_score: Some(0.5),
            candidate_ucb_score: Some(0.6),
            current_ucb_score: Some(0.5),
            reason: crate::types::L2DecisionReason::DwellHold,
            dwell_steps: 2,
            dwell_suppressed: true,
            margin_suppressed: false,
            l2_policy_applied: true,
            switched: false,
            safety_override: false,
            adjusted_reward: None,
            rollback_count: 0,
            switch_cost_applied: 0.0,
        })
        .unwrap();
        value.as_object_mut().unwrap().remove("l2_policy_applied");
        let record: crate::types::L2DecisionRecord = serde_json::from_value(value).unwrap();
        assert!(!record.l2_policy_applied);
    }

    #[test]
    fn legacy_policy_does_not_enable_spectral_weighting() {
        let mut value = serde_json::to_value(crate::types::L2Policy::default()).unwrap();
        value.as_object_mut().unwrap().remove("spectral_weighting");
        let policy: crate::types::L2Policy = serde_json::from_value(value).unwrap();
        assert!(!policy.spectral_weighting);
        let snapshot = KernelSnapshot::default();
        assert!(!snapshot.l2_pending_policy.spectral_weighting);
        assert!(!snapshot.l2_applied_policy.spectral_weighting);
        assert!(!crate::l2::L2MetaLayer::new().spectral_control_enabled);
    }

    #[test]
    fn rejects_future_schema() {
        let path = temp_dir().join(format!("omega-future-{}.json", crate::new_uuid()));
        let snap = KernelSnapshot {
            version: 99,
            total_steps: 0,
            biases: BTreeMap::new(),
            constraints: BTreeMap::new(),
            cas_total_steps: 0,
            cas_avg_prediction_error: 0.0,
            cas_adaptation_score: 0.0,
            cognitive_effect: RuleEffect::default(),
            cases: vec![],
            case_capacity: 256,
            strategies: BTreeMap::new(),
            active_modules: BTreeMap::new(),
            patch_history: vec![],
            ..KernelSnapshot::default()
        };
        // Bypass save_to stamping by writing raw.
        fs::write(&path, serde_json::to_string(&snap).unwrap()).unwrap();
        let err = KernelSnapshot::load_from(&path).unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("newer") || msg.contains("99"), "{msg}");
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn memory_state_store_round_trip() {
        let store = MemoryStateStore::new();
        assert!(store.load_snapshot().expect("empty load").is_none());

        let mut params = std::collections::BTreeMap::new();
        params.insert(String::from("temperature"), 0.55);
        let snap = KernelSnapshot {
            total_steps: 7,
            external_loop: Some(ExternalLoopState {
                last_external_step_id: Some(7),
                cooldown: crate::orchestrator::CooldownTracker::new(3),
                last_checkpoint_id: Some(String::from("ckpt-7")),
                last_checkpoint_uuid: None,
                current_params: Some(params),
                last_checkpoint_params: None,
            }),
            ..KernelSnapshot::default()
        };
        store.save_snapshot(&snap).expect("save memory snapshot");

        let loaded = store
            .load_snapshot()
            .expect("reload memory snapshot")
            .expect("snapshot present");
        assert_eq!(loaded.total_steps, 7);
        let ext = loaded.external_loop.expect("external loop state");
        assert_eq!(ext.last_external_step_id, Some(7));
        assert_eq!(ext.current_params.expect("params")["temperature"], 0.55);
    }

    #[test]
    fn file_state_store_round_trip() {
        let dir = std::env::temp_dir().join(format!(
            "omega-file-store-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("system time")
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("state.json");
        let store = FileStateStore::new(path.clone());
        assert_eq!(store.path(), path.as_path());
        assert!(store.load_snapshot().expect("missing file load").is_none());

        let snap = KernelSnapshot {
            total_steps: 11,
            ..KernelSnapshot::default()
        };
        store.save_snapshot(&snap).expect("save file snapshot");
        let loaded = store
            .load_snapshot()
            .expect("load file snapshot")
            .expect("file snapshot present");
        assert_eq!(loaded.total_steps, 11);

        let _ = std::fs::remove_dir_all(dir);
    }
}