Skip to main content

omega_cognitive_kernel/
persist.rs

1//! Disk persistence for kernel state (S2 product surface).
2
3#[allow(unused_imports)]
4use crate::prelude::*;
5
6use crate::error::{OmegaError, Result};
7use crate::memory::case::Case;
8use crate::memory::strategy::Strategy;
9use crate::types::{CognitivePatch, MetaMetrics, RuleEffect};
10use alloc::collections::BTreeMap;
11use serde::{Deserialize, Serialize};
12use std::fs;
13#[cfg(feature = "async")]
14use std::future::Future;
15use std::io::Read;
16use std::path::{Path, PathBuf};
17#[cfg(feature = "async")]
18use std::pin::Pin;
19
20/// Constant defining default state path.
21pub const DEFAULT_STATE_PATH: &str = ".omega/state.json";
22/// Maximum serialized snapshot accepted by file and string loaders.
23pub const MAX_SNAPSHOT_BYTES: u64 = 64 * 1024 * 1024;
24/// Maximum number of entries in each persisted collection.
25pub const MAX_SNAPSHOT_COLLECTION_ITEMS: usize = 1_000_000;
26
27/// Current on-disk schema. Bump only with a migration path.
28pub const CURRENT_SCHEMA_VERSION: u32 = 6;
29
30fn default_schema_version() -> u32 {
31    0
32}
33
34/// Pre-v2 default for the L1 self-modify master switch was `false` (safe).
35fn default_self_modify_enabled() -> bool {
36    false
37}
38
39/// Pre-v2 the cooldown counter started "warm" so the first patch could fire
40/// immediately once self-modify was enabled.
41fn default_steps_since_last_patch() -> u64 {
42    100
43}
44
45fn default_l2_enabled() -> bool {
46    // Missing legacy flags must not acquire permission to alter L0 on upgrade.
47    false
48}
49
50fn default_l2_commit_threshold() -> f64 {
51    0.82
52}
53
54fn default_l2_commit_cooldown() -> u64 {
55    5
56}
57
58fn default_l2_negative_reward_required() -> u32 {
59    3
60}
61
62fn default_l2_detector_window() -> usize {
63    4
64}
65
66fn default_l2_detector_pred_threshold() -> f64 {
67    0.58
68}
69
70fn default_l2_detector_self_ref_threshold() -> f64 {
71    0.50
72}
73
74fn default_l2_detector_cooldown() -> usize {
75    5
76}
77
78#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
79/// Data structure representing external loop state.
80pub struct ExternalLoopState {
81    #[serde(default)]
82    /// Identifier for the last external step.
83    pub last_external_step_id: Option<u64>,
84    /// Cooldown for this value.
85    pub cooldown: crate::orchestrator::CooldownTracker,
86    #[serde(default)]
87    /// Identifier for the last checkpoint.
88    pub last_checkpoint_id: Option<String>,
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    /// Most recent checkpoint UUID.
91    pub last_checkpoint_uuid: Option<String>,
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    /// Optional current params.
94    pub current_params: Option<std::collections::BTreeMap<String, f64>>,
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    /// Most recent checkpoint params.
97    pub last_checkpoint_params: Option<std::collections::BTreeMap<String, f64>>,
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize)]
101/// Serializable snapshot of the kernel state.
102pub struct KernelSnapshot {
103    /// On-disk schema version. Missing / 0 treated as pre-0.5 and migrated up to
104    /// [`CURRENT_SCHEMA_VERSION`] (currently 6) on load.
105    #[serde(default = "default_schema_version")]
106    pub version: u32,
107    /// Total number of kernel steps completed.
108    pub total_steps: u64,
109    /// Mapping of biases.
110    pub biases: BTreeMap<String, f64>,
111    /// Mapping of constraints.
112    pub constraints: BTreeMap<String, f64>,
113    /// Number of CAS total.
114    pub cas_total_steps: u64,
115    /// Cas average prediction error for this value.
116    pub cas_avg_prediction_error: f64,
117    /// Cas adaptation score for this value.
118    pub cas_adaptation_score: f64,
119    /// Cognitive effect for this value.
120    pub cognitive_effect: RuleEffect,
121    /// Collection of cases.
122    pub cases: Vec<Case>,
123    /// Case capacity for this value.
124    pub case_capacity: usize,
125    /// Mapping of strategies.
126    pub strategies: BTreeMap<String, Strategy>,
127    /// Number of active cognitive modules.
128    pub active_modules: BTreeMap<String, String>,
129    /// Collection of patch history.
130    pub patch_history: Vec<(CognitivePatch, String)>,
131    #[serde(default = "default_l2_enabled")]
132    /// Whether the L2 meta-controller is enabled.
133    pub l2_enabled: bool,
134    #[serde(default)]
135    /// Whether L2 in fixed point is enabled or active.
136    pub l2_in_fixed_point: bool,
137    #[serde(default)]
138    /// Number of L2 dwell.
139    pub l2_dwell_steps: u64,
140    #[serde(default)]
141    /// L2 last alignment score for this value.
142    pub l2_last_alignment_score: f64,
143    #[serde(default = "default_l2_commit_threshold")]
144    /// L2 commit threshold for this value.
145    pub l2_commit_threshold: f64,
146    #[serde(default = "default_l2_commit_cooldown")]
147    /// Number of L2 commit cooldown.
148    pub l2_commit_cooldown_steps: u64,
149    #[serde(default)]
150    /// L2 commit cooldown remaining for this value.
151    pub l2_commit_cooldown_remaining: u64,
152    #[serde(default)]
153    /// L2 last consequence score for this value.
154    pub l2_last_consequence_score: f64,
155    #[serde(default)]
156    /// Whether L2 is operating in defensive mode.
157    pub l2_defensive_mode: bool,
158    #[serde(default)]
159    /// Number of consecutive negative consequences observed by L2.
160    pub l2_negative_consequence_streak: u32,
161    #[serde(default)]
162    /// Number of L2 stable consequence.
163    pub l2_stable_consequence_steps: u32,
164    #[serde(default)]
165    /// L2 reward change score for this value.
166    pub l2_reward_change_score: f64,
167    #[serde(default)]
168    /// L2 error change score for this value.
169    pub l2_error_change_score: f64,
170    #[serde(default)]
171    /// Whether L2 awaiting consequence is enabled or active.
172    pub l2_awaiting_consequence: bool,
173    #[serde(default)]
174    /// L2 negative reward streak for this value.
175    pub l2_negative_reward_streak: u32,
176    #[serde(default = "default_l2_negative_reward_required")]
177    /// L2 negative reward required for this value.
178    pub l2_negative_reward_required: u32,
179    #[serde(default)]
180    /// Collection of L2 detector history.
181    pub l2_detector_history: Vec<MetaMetrics>,
182    #[serde(default = "default_l2_detector_window")]
183    /// L2 detector window for this value.
184    pub l2_detector_window: usize,
185    #[serde(default = "default_l2_detector_pred_threshold")]
186    /// L2 detector pred threshold for this value.
187    pub l2_detector_pred_threshold: f64,
188    #[serde(default = "default_l2_detector_self_ref_threshold")]
189    /// L2 detector self ref threshold for this value.
190    pub l2_detector_self_ref_threshold: f64,
191    #[serde(default = "default_l2_detector_cooldown")]
192    /// Number of L2 detector cooldown.
193    pub l2_detector_cooldown_steps: usize,
194    #[serde(default)]
195    /// L2 detector cooldown remaining for this value.
196    pub l2_detector_cooldown_remaining: usize,
197    /// L1 self-modify master switch (v2+). Restored so that enabling L1 then
198    /// restarting does not silently fall back to the safe default-off.
199    #[serde(default = "default_self_modify_enabled")]
200    pub self_modify_enabled: bool,
201    /// L1 patch cooldown counter (v2+). Restored so a restart cannot reset the
202    /// min-steps-between-patches cooldown.
203    #[serde(default = "default_steps_since_last_patch")]
204    pub steps_since_last_patch: u64,
205    /// L2 rollback policy snapshot (v2+). Restored so that after an L2 commit a
206    /// restart retains the pre-commit policy needed for negative-feedback rollback.
207    #[serde(default)]
208    pub l2_rollback_effect: Option<RuleEffect>,
209    /// Last UCB-backed L2 decision, available to status and trajectory replay.
210    #[serde(default)]
211    pub last_l2_decision: Option<crate::types::L2DecisionRecord>,
212    /// Complete local bandit state when the kernel uses BanditUcbDecisionMaker.
213    #[serde(default)]
214    pub bandit_ucb: Option<crate::l0::bandit_decision::BanditUcbSnapshot>,
215    #[serde(default)]
216    /// Bandit config for this value.
217    pub bandit_config: crate::types::BanditConfig,
218    #[serde(default)]
219    /// Optional L1 previous effect.
220    pub l1_previous_effect: Option<RuleEffect>,
221    #[serde(default)]
222    /// Whether L1 pending rollback is enabled or active.
223    pub l1_pending_rollback: bool,
224    /// Resident L2 controller and one-step pending policy (v4+). Missing legacy
225    /// state is dormant with zero trust, so migration cannot inject a bias.
226    #[serde(default)]
227    pub l2_controller: crate::l2::control::ResidentController,
228    #[serde(default)]
229    /// L2 policy proposed but not yet applied.
230    pub l2_pending_policy: crate::types::L2Policy,
231    #[serde(default)]
232    /// L2 policy currently applied at the control boundary.
233    pub l2_applied_policy: crate::types::L2Policy,
234    #[serde(default)]
235    /// Whether L2 pending L1 rollback is enabled or active.
236    pub l2_pending_l1_rollback: bool,
237    #[serde(default)]
238    /// L2 last reward for this value.
239    pub l2_last_reward: f64,
240    /// Per-instance prioritized-replay cursor (v6+), independent of other kernels.
241    #[serde(default)]
242    pub case_sample_counter: u32,
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    /// Optional external loop.
245    pub external_loop: Option<ExternalLoopState>,
246}
247
248impl Default for KernelSnapshot {
249    fn default() -> Self {
250        Self {
251            version: CURRENT_SCHEMA_VERSION,
252            total_steps: 0,
253            biases: BTreeMap::new(),
254            constraints: BTreeMap::new(),
255            cas_total_steps: 0,
256            cas_avg_prediction_error: 0.0,
257            cas_adaptation_score: 0.0,
258            cognitive_effect: RuleEffect::default(),
259            cases: Vec::new(),
260            case_capacity: 256,
261            strategies: BTreeMap::new(),
262            active_modules: BTreeMap::new(),
263            patch_history: Vec::new(),
264            l2_enabled: true,
265            l2_in_fixed_point: false,
266            l2_dwell_steps: 0,
267            l2_last_alignment_score: 0.0,
268            l2_commit_threshold: default_l2_commit_threshold(),
269            l2_commit_cooldown_steps: default_l2_commit_cooldown(),
270            l2_commit_cooldown_remaining: 0,
271            l2_last_consequence_score: 0.0,
272            l2_defensive_mode: false,
273            l2_negative_consequence_streak: 0,
274            l2_stable_consequence_steps: 0,
275            l2_reward_change_score: 0.0,
276            l2_error_change_score: 0.0,
277            l2_awaiting_consequence: false,
278            l2_negative_reward_streak: 0,
279            l2_negative_reward_required: default_l2_negative_reward_required(),
280            l2_detector_history: Vec::new(),
281            l2_detector_window: 4,
282            l2_detector_pred_threshold: 0.58,
283            l2_detector_self_ref_threshold: 0.50,
284            l2_detector_cooldown_steps: 5,
285            l2_detector_cooldown_remaining: 0,
286            self_modify_enabled: false,
287            steps_since_last_patch: default_steps_since_last_patch(),
288            l2_rollback_effect: None,
289            last_l2_decision: None,
290            bandit_ucb: None,
291            bandit_config: crate::types::BanditConfig::default(),
292            l1_previous_effect: None,
293            l1_pending_rollback: false,
294            l2_controller: crate::l2::control::ResidentController::default(),
295            l2_pending_policy: crate::types::L2Policy::default(),
296            l2_applied_policy: crate::types::L2Policy::default(),
297            l2_pending_l1_rollback: false,
298            l2_last_reward: 0.5,
299            case_sample_counter: 0,
300            external_loop: None,
301        }
302    }
303}
304
305impl KernelSnapshot {
306    /// Migrate older snapshots into `CURRENT_SCHEMA_VERSION`.
307    pub fn migrate(mut self) -> Result<Self> {
308        if self.version > CURRENT_SCHEMA_VERSION {
309            return Err(OmegaError::Persist(format!(
310                "state schema version {} is newer than supported {}",
311                self.version, CURRENT_SCHEMA_VERSION
312            )));
313        }
314        if self.version < 1 {
315            // v0 → v1: case.priority backfill happens in CaseMemory::restore;
316            // ensure capacity is sane and stamp version.
317            if self.case_capacity == 0 {
318                self.case_capacity = 256;
319            }
320            self.version = 1;
321        }
322        if self.version < 2 {
323            // v1 → v2: the new safety fields (`self_modify_enabled`,
324            // `steps_since_last_patch`, `l2_rollback_effect`) are absent from v1
325            // snapshots and therefore already carry their serde defaults. The
326            // defaults are intentionally the *safe* pre-v2 behavior: L1 disabled
327            // and a warm cooldown. Nothing to backfill beyond stamping the version.
328            self.version = 2;
329        }
330        if self.version < 3 {
331            // v3 adds optional UCB statistics and decision explanations. Their
332            // defaults preserve the old policy and never enable self-modification.
333            self.version = 3;
334        }
335        if self.version < 4 {
336            // v4 adds the resident controller, bounded meta-cache and pending
337            // policy. Serde defaults fail closed to DORMANT and KEEP_L0.
338            self.l2_pending_policy = crate::types::L2Policy::default();
339            self.l2_applied_policy = crate::types::L2Policy::default();
340            self.version = 4;
341        }
342        if self.version < 5 {
343            // v5 makes the online Dayan state, duplicate-feedback guard and
344            // normalized propensity snapshots explicit. Missing v4 fields are
345            // safe serde defaults; permission remains opt-in, never inferred
346            // from the presence of a resident controller or a cache entry.
347            self.l2_pending_policy = self.l2_pending_policy.effective();
348            self.l2_applied_policy = self.l2_applied_policy.effective();
349            if !self.l2_enabled {
350                self.l2_pending_policy = crate::types::L2Policy::default();
351                self.l2_applied_policy = crate::types::L2Policy::default();
352                self.l2_controller.gate_state = crate::l2::control::L2GateState::Dormant;
353                self.l2_controller.trust.alpha = 0.0;
354            }
355            self.version = 5;
356        }
357        if self.version < 6 {
358            // v6 makes replay sampling local to the case-memory instance. Legacy
359            // snapshots have no meaningful global cursor, so start at zero.
360            self.case_sample_counter = 0;
361            self.version = 6;
362        }
363        Ok(self)
364    }
365
366    /// Redact known user-provided goal text before writing a snapshot.
367    /// Numeric learning state and schema remain unchanged.
368    pub fn redact_user_content(&mut self) {
369        for case in &mut self.cases {
370            case.goal = "[REDACTED]".into();
371        }
372    }
373
374    /// Saves to.
375    pub fn save_to(&self, path: &Path) -> Result<()> {
376        if let Some(parent) = path.parent() {
377            crate::private_fs::create_dir_all(parent)
378                .map_err(|e| OmegaError::Persist(e.to_string()))?;
379        }
380        let mut snap = self.clone();
381        snap.version = CURRENT_SCHEMA_VERSION;
382        let json =
383            serde_json::to_string_pretty(&snap).map_err(|e| OmegaError::Persist(e.to_string()))?;
384        let parent = path.parent().unwrap_or_else(|| Path::new("."));
385        let file_name = path
386            .file_name()
387            .and_then(|name| name.to_str())
388            .ok_or_else(|| {
389                OmegaError::Persist(format!("invalid state path: {}", path.display()))
390            })?;
391        let temp_path = parent.join(format!(".{file_name}.{}.tmp", crate::new_uuid()));
392        let result = (|| -> Result<()> {
393            use std::io::Write;
394            let mut file = crate::private_fs::open_options()
395                .write(true)
396                .create_new(true)
397                .open(&temp_path)
398                .map_err(|e| OmegaError::Persist(format!("state temp create: {e}")))?;
399            file.write_all(json.as_bytes())
400                .and_then(|()| file.sync_all())
401                .map_err(|e| OmegaError::Persist(format!("state temp write: {e}")))?;
402            fs::rename(&temp_path, path)
403                .map_err(|e| OmegaError::Persist(format!("state atomic replace: {e}")))?;
404            Ok(())
405        })();
406        if result.is_err() {
407            let _ = fs::remove_file(&temp_path);
408        }
409        result
410    }
411
412    /// Loads from.
413    pub fn load_from(path: &Path) -> Result<Self> {
414        let mut file = fs::File::open(path).map_err(|e| OmegaError::Persist(e.to_string()))?;
415        let mut data = String::new();
416        file.by_ref()
417            .take(MAX_SNAPSHOT_BYTES + 1)
418            .read_to_string(&mut data)
419            .map_err(|e| OmegaError::Persist(e.to_string()))?;
420        if data.len() as u64 > MAX_SNAPSHOT_BYTES {
421            return Err(OmegaError::Persist(format!(
422                "snapshot byte limit exceeded: maximum {MAX_SNAPSHOT_BYTES} bytes"
423            )));
424        }
425        Self::from_json(&data)
426    }
427
428    /// Converts this value to JSON.
429    pub fn to_json(&self) -> Result<String> {
430        serde_json::to_string(self).map_err(|e| OmegaError::Persist(e.to_string()))
431    }
432
433    /// Creates a value from JSON.
434    pub fn from_json(json: &str) -> Result<Self> {
435        if json.len() as u64 > MAX_SNAPSHOT_BYTES {
436            return Err(OmegaError::Persist(format!(
437                "snapshot byte limit exceeded: maximum {MAX_SNAPSHOT_BYTES} bytes"
438            )));
439        }
440        let snap: Self =
441            serde_json::from_str(json).map_err(|e| OmegaError::Persist(e.to_string()))?;
442        let collection_sizes = [
443            snap.cases.len(),
444            snap.strategies.len(),
445            snap.biases.len(),
446            snap.constraints.len(),
447            snap.active_modules.len(),
448            snap.patch_history.len(),
449            snap.l2_detector_history.len(),
450        ];
451        if collection_sizes
452            .into_iter()
453            .any(|size| size > MAX_SNAPSHOT_COLLECTION_ITEMS)
454        {
455            return Err(OmegaError::Persist(format!(
456                "snapshot collection item limit exceeded: maximum {MAX_SNAPSHOT_COLLECTION_ITEMS}"
457            )));
458        }
459        snap.migrate()
460    }
461}
462
463/// Resolves the effective value from the supplied inputs.
464pub fn resolve_state_path(explicit: Option<&str>) -> PathBuf {
465    explicit
466        .map(PathBuf::from)
467        .unwrap_or_else(|| PathBuf::from(DEFAULT_STATE_PATH))
468}
469/// Pluggable persistence backend for [`KernelSnapshot`].
470///
471/// Default local file persistence is provided by [`FileStateStore`], and an
472/// in-memory backend for tests or ephemeral runtimes is provided by
473/// [`MemoryStateStore`]. Future server backends (SQLite, Redis, Postgres)
474/// can implement this trait without altering core orchestration.
475pub trait StateStore: Send + Sync {
476    /// Load the latest persisted snapshot, or `Ok(None)` if no state exists yet.
477    fn load_snapshot(&self) -> Result<Option<KernelSnapshot>>;
478
479    /// Persist a snapshot atomically to the backing store.
480    fn save_snapshot(&self, snapshot: &KernelSnapshot) -> Result<()>;
481}
482
483impl<T: StateStore + ?Sized> StateStore for std::sync::Arc<T> {
484    fn load_snapshot(&self) -> Result<Option<KernelSnapshot>> {
485        (**self).load_snapshot()
486    }
487
488    fn save_snapshot(&self, snapshot: &KernelSnapshot) -> Result<()> {
489        (**self).save_snapshot(snapshot)
490    }
491}
492
493/// Boxed future returned by [`AsyncStateStore`] operations.
494#[cfg(feature = "async")]
495pub type AsyncStateStoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;
496
497/// Asynchronous access to persisted kernel snapshots.
498///
499/// The boxed-future contract remains compatible with the Rust 1.89 MSRV proposed for the next release.
500/// Implementations should replace a snapshot atomically and return an error
501/// when a snapshot cannot be loaded or durably stored.
502#[cfg(feature = "async")]
503pub trait AsyncStateStore: Send + Sync {
504    /// Load the latest persisted snapshot, or `Ok(None)` when no state exists.
505    fn load_snapshot(&self) -> AsyncStateStoreFuture<'_, Option<KernelSnapshot>>;
506
507    /// Persist a snapshot atomically to the backing store.
508    fn save_snapshot<'a>(&'a self, snapshot: &'a KernelSnapshot) -> AsyncStateStoreFuture<'a, ()>;
509}
510
511/// Runs a synchronous [`StateStore`] on Tokio's blocking thread pool.
512///
513/// This adapter is useful for existing file and SQLite stores when called from
514/// an async application. Cancelling the returned future does not cancel a
515/// blocking operation that has already started; snapshot writes remain atomic
516/// and may complete after the caller stops awaiting them.
517#[cfg(feature = "async")]
518#[derive(Clone)]
519pub struct AsyncStateStoreAdapter {
520    store: std::sync::Arc<dyn StateStore>,
521}
522
523#[cfg(feature = "async")]
524impl AsyncStateStoreAdapter {
525    /// Wrap a synchronous store for asynchronous use.
526    pub fn new(store: impl StateStore + 'static) -> Self {
527        Self {
528            store: std::sync::Arc::new(store),
529        }
530    }
531
532    /// Wrap a shared synchronous store without allocating another store value.
533    pub fn from_shared(store: std::sync::Arc<dyn StateStore>) -> Self {
534        Self { store }
535    }
536}
537
538#[cfg(feature = "async")]
539impl core::fmt::Debug for AsyncStateStoreAdapter {
540    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
541        formatter
542            .debug_struct("AsyncStateStoreAdapter")
543            .finish_non_exhaustive()
544    }
545}
546
547#[cfg(feature = "async")]
548impl AsyncStateStore for AsyncStateStoreAdapter {
549    fn load_snapshot(&self) -> AsyncStateStoreFuture<'_, Option<KernelSnapshot>> {
550        let store = std::sync::Arc::clone(&self.store);
551        Box::pin(async move {
552            let runtime = tokio::runtime::Handle::try_current().map_err(|error| {
553                OmegaError::Persist(format!(
554                    "async state-store operation requires an active Tokio runtime: {error}"
555                ))
556            })?;
557            runtime
558                .spawn_blocking(move || store.load_snapshot())
559                .await
560                .map_err(|error| {
561                    OmegaError::Persist(format!("async state-store worker failed: {error}"))
562                })?
563        })
564    }
565
566    fn save_snapshot<'a>(&'a self, snapshot: &'a KernelSnapshot) -> AsyncStateStoreFuture<'a, ()> {
567        let store = std::sync::Arc::clone(&self.store);
568        Box::pin(async move {
569            let runtime = tokio::runtime::Handle::try_current().map_err(|error| {
570                OmegaError::Persist(format!(
571                    "async state-store operation requires an active Tokio runtime: {error}"
572                ))
573            })?;
574            let snapshot = snapshot.clone();
575            runtime
576                .spawn_blocking(move || store.save_snapshot(&snapshot))
577                .await
578                .map_err(|error| {
579                    OmegaError::Persist(format!("async state-store worker failed: {error}"))
580                })?
581        })
582    }
583}
584
585/// Local filesystem implementation of [`StateStore`] backed by [`KernelSnapshot::save_to`].
586#[derive(Debug, Clone)]
587pub struct FileStateStore {
588    path: PathBuf,
589}
590
591impl FileStateStore {
592    /// Creates a file-backed store that reads and writes snapshots at `path`.
593    pub fn new(path: impl Into<PathBuf>) -> Self {
594        Self { path: path.into() }
595    }
596
597    /// Returns the path used for the persisted snapshot.
598    pub fn path(&self) -> &Path {
599        &self.path
600    }
601}
602
603impl StateStore for FileStateStore {
604    fn load_snapshot(&self) -> Result<Option<KernelSnapshot>> {
605        if !self.path.exists() {
606            return Ok(None);
607        }
608        KernelSnapshot::load_from(&self.path).map(Some)
609    }
610
611    fn save_snapshot(&self, snapshot: &KernelSnapshot) -> Result<()> {
612        snapshot.save_to(&self.path)
613    }
614}
615
616/// Thread-safe in-memory [`StateStore`] for tests and ephemeral runtimes.
617#[derive(Debug, Default)]
618pub struct MemoryStateStore {
619    slot: std::sync::RwLock<Option<KernelSnapshot>>,
620}
621
622impl MemoryStateStore {
623    /// Creates an empty in-memory snapshot store.
624    pub fn new() -> Self {
625        Self::default()
626    }
627}
628
629impl StateStore for MemoryStateStore {
630    fn load_snapshot(&self) -> Result<Option<KernelSnapshot>> {
631        let guard = self
632            .slot
633            .read()
634            .map_err(|_| OmegaError::Persist(String::from("memory state store lock poisoned")))?;
635        Ok(guard.clone())
636    }
637
638    fn save_snapshot(&self, snapshot: &KernelSnapshot) -> Result<()> {
639        let mut guard = self
640            .slot
641            .write()
642            .map_err(|_| OmegaError::Persist(String::from("memory state store lock poisoned")))?;
643        *guard = Some(snapshot.clone());
644        Ok(())
645    }
646}
647
648/// SQLite-backed [`StateStore`] for applications that enable the `sqlite` feature.
649///
650/// The feature links to system SQLite (not a bundled copy) and requires SQLite
651/// 3.54.0 or newer. Both constructors reject older linked versions before opening
652/// or creating a database. File-backed stores use WAL mode, a configurable busy
653/// timeout (five seconds by default), and transactional snapshot replacement.
654#[cfg(feature = "sqlite")]
655#[derive(Debug)]
656pub struct SqliteStateStore {
657    connection: std::sync::Mutex<rusqlite::Connection>,
658}
659
660#[cfg(feature = "sqlite")]
661const MIN_SQLITE_VERSION_NUMBER: i32 = 3_054_000;
662
663/// Default SQLite lock wait before a busy operation returns an error.
664#[cfg(feature = "sqlite")]
665pub const DEFAULT_SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
666
667#[cfg(feature = "sqlite")]
668fn validate_sqlite_version_number(version_number: i32, version: &str) -> Result<()> {
669    if version_number < MIN_SQLITE_VERSION_NUMBER {
670        return Err(OmegaError::Persist(format!(
671            "SqliteStateStore requires system SQLite 3.54.0 or newer; linked SQLite is {version} ({version_number})"
672        )));
673    }
674    Ok(())
675}
676
677#[cfg(feature = "sqlite")]
678fn ensure_supported_sqlite_version() -> Result<()> {
679    validate_sqlite_version_number(rusqlite::version_number(), rusqlite::version())
680}
681
682#[cfg(all(test, feature = "sqlite"))]
683mod sqlite_version_tests {
684    use super::validate_sqlite_version_number;
685
686    #[test]
687    fn rejects_vulnerable_sqlite_versions() {
688        let error = validate_sqlite_version_number(3_053_999, "3.53.999")
689            .expect_err("SQLite before 3.54.0 must be rejected");
690        assert!(error.to_string().contains("SQLite 3.54.0 or newer"));
691        assert!(error.to_string().contains("3.53.999"));
692    }
693
694    #[test]
695    fn accepts_the_minimum_patched_sqlite_version() {
696        validate_sqlite_version_number(3_054_000, "3.54.0")
697            .expect("SQLite 3.54.0 is the minimum supported version");
698    }
699}
700
701#[cfg(feature = "sqlite")]
702impl SqliteStateStore {
703    /// Open or create a file-backed SQLite state database.
704    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
705        Self::open_with_busy_timeout(path, DEFAULT_SQLITE_BUSY_TIMEOUT)
706    }
707
708    /// Open a file-backed database with an explicit SQLite lock wait duration.
709    ///
710    /// Pass [`std::time::Duration::ZERO`] to fail immediately on lock
711    /// contention. WAL mode remains enabled for file-backed databases.
712    pub fn open_with_busy_timeout(
713        path: impl AsRef<Path>,
714        busy_timeout: std::time::Duration,
715    ) -> Result<Self> {
716        ensure_supported_sqlite_version()?;
717        let path = path.as_ref();
718        if let Some(parent) = path
719            .parent()
720            .filter(|parent| !parent.as_os_str().is_empty())
721        {
722            crate::private_fs::create_dir_all(parent)
723                .map_err(|error| sqlite_persist_error("create SQLite state directory", error))?;
724        }
725        if !path.exists() {
726            match crate::private_fs::open_options()
727                .write(true)
728                .create_new(true)
729                .open(path)
730            {
731                Ok(file) => drop(file),
732                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
733                Err(error) => {
734                    return Err(sqlite_persist_error("create SQLite state database", error));
735                }
736            }
737        }
738        let connection = rusqlite::Connection::open(path)
739            .map_err(|error| sqlite_persist_error("open SQLite state database", error))?;
740        Self::from_connection(connection, true, busy_timeout)
741    }
742
743    /// Create an ephemeral, in-memory SQLite state database.
744    pub fn open_in_memory() -> Result<Self> {
745        Self::open_in_memory_with_busy_timeout(DEFAULT_SQLITE_BUSY_TIMEOUT)
746    }
747
748    /// Create an in-memory database with an explicit SQLite lock wait duration.
749    pub fn open_in_memory_with_busy_timeout(busy_timeout: std::time::Duration) -> Result<Self> {
750        ensure_supported_sqlite_version()?;
751        let connection = rusqlite::Connection::open_in_memory()
752            .map_err(|error| sqlite_persist_error("open in-memory SQLite state database", error))?;
753        Self::from_connection(connection, false, busy_timeout)
754    }
755
756    fn from_connection(
757        connection: rusqlite::Connection,
758        use_wal: bool,
759        busy_timeout: std::time::Duration,
760    ) -> Result<Self> {
761        connection
762            .busy_timeout(busy_timeout)
763            .map_err(|error| sqlite_persist_error("configure SQLite busy timeout", error))?;
764
765        if use_wal {
766            let journal_mode: String = connection
767                .query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))
768                .map_err(|error| sqlite_persist_error("enable SQLite WAL mode", error))?;
769            if !journal_mode.eq_ignore_ascii_case("wal") {
770                return Err(OmegaError::Persist(format!(
771                    "SQLite refused WAL mode (reported {journal_mode})"
772                )));
773            }
774        }
775
776        connection
777            .execute_batch(
778                "PRAGMA synchronous = FULL;
779                 CREATE TABLE IF NOT EXISTS omega_state (
780                     singleton_id INTEGER PRIMARY KEY CHECK (singleton_id = 1),
781                     schema_version INTEGER NOT NULL,
782                     updated_at TEXT NOT NULL,
783                     payload TEXT NOT NULL
784                 );",
785            )
786            .map_err(|error| sqlite_persist_error("initialize SQLite state schema", error))?;
787
788        Ok(Self {
789            connection: std::sync::Mutex::new(connection),
790        })
791    }
792}
793
794#[cfg(feature = "sqlite")]
795impl StateStore for SqliteStateStore {
796    fn load_snapshot(&self) -> Result<Option<KernelSnapshot>> {
797        use rusqlite::OptionalExtension;
798
799        let connection = self
800            .connection
801            .lock()
802            .map_err(|_| OmegaError::Persist(String::from("SQLite state store lock poisoned")))?;
803        let record = connection
804            .query_row(
805                "SELECT schema_version, updated_at, payload
806                 FROM omega_state WHERE singleton_id = 1",
807                [],
808                |row| {
809                    Ok((
810                        row.get::<_, i64>(0)?,
811                        row.get::<_, String>(1)?,
812                        row.get::<_, String>(2)?,
813                    ))
814                },
815            )
816            .optional()
817            .map_err(|error| sqlite_persist_error("read SQLite state snapshot", error))?;
818
819        let Some((schema_version, updated_at, payload)) = record else {
820            return Ok(None);
821        };
822        if schema_version < 0 {
823            return Err(OmegaError::Persist(format!(
824                "invalid negative SQLite state schema version {schema_version}"
825            )));
826        }
827        if schema_version > i64::from(CURRENT_SCHEMA_VERSION) {
828            return Err(OmegaError::Persist(format!(
829                "SQLite state schema version {schema_version} is newer than supported {CURRENT_SCHEMA_VERSION}"
830            )));
831        }
832        crate::types::UtcTimestamp::from_rfc3339(&updated_at).map_err(|error| {
833            OmegaError::Persist(format!(
834                "invalid SQLite state updated_at timestamp: {error}"
835            ))
836        })?;
837
838        if payload.len() as u64 > MAX_SNAPSHOT_BYTES {
839            return Err(OmegaError::Persist(format!(
840                "SQLite snapshot byte limit exceeded: maximum {MAX_SNAPSHOT_BYTES} bytes"
841            )));
842        }
843
844        let payload_value: serde_json::Value = serde_json::from_str(&payload)
845            .map_err(|error| sqlite_persist_error("decode SQLite snapshot schema", error))?;
846        let payload_version = match payload_value.get("version") {
847            None => 0,
848            Some(version) => {
849                let version = version.as_u64().ok_or_else(|| {
850                    OmegaError::Persist(String::from(
851                        "SQLite snapshot schema version is not a non-negative integer",
852                    ))
853                })?;
854                u32::try_from(version).map_err(|_| {
855                    OmegaError::Persist(String::from(
856                        "SQLite snapshot schema version exceeds the supported integer range",
857                    ))
858                })?
859            }
860        };
861        if i64::from(payload_version) != schema_version {
862            return Err(OmegaError::Persist(format!(
863                "SQLite state schema metadata ({schema_version}) does not match snapshot payload ({payload_version})"
864            )));
865        }
866
867        KernelSnapshot::from_json(&payload).map(Some)
868    }
869
870    fn save_snapshot(&self, snapshot: &KernelSnapshot) -> Result<()> {
871        let mut persisted_snapshot = snapshot.clone();
872        persisted_snapshot.version = CURRENT_SCHEMA_VERSION;
873        let payload = serde_json::to_string(&persisted_snapshot)
874            .map_err(|error| sqlite_persist_error("serialize SQLite state snapshot", error))?;
875        if payload.len() as u64 > MAX_SNAPSHOT_BYTES {
876            return Err(OmegaError::Persist(format!(
877                "SQLite snapshot byte limit exceeded: maximum {MAX_SNAPSHOT_BYTES} bytes"
878            )));
879        }
880        let updated_at = crate::types::UtcTimestamp::now().to_rfc3339();
881
882        let mut connection = self
883            .connection
884            .lock()
885            .map_err(|_| OmegaError::Persist(String::from("SQLite state store lock poisoned")))?;
886        let transaction = connection
887            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
888            .map_err(|error| sqlite_persist_error("begin SQLite snapshot transaction", error))?;
889        transaction
890            .execute(
891                "INSERT INTO omega_state (singleton_id, schema_version, updated_at, payload)
892                 VALUES (1, ?1, ?2, ?3)
893                 ON CONFLICT(singleton_id) DO UPDATE SET
894                     schema_version = excluded.schema_version,
895                     updated_at = excluded.updated_at,
896                     payload = excluded.payload",
897                rusqlite::params![i64::from(CURRENT_SCHEMA_VERSION), updated_at, payload],
898            )
899            .map_err(|error| sqlite_persist_error("write SQLite state snapshot", error))?;
900        transaction
901            .commit()
902            .map_err(|error| sqlite_persist_error("commit SQLite snapshot transaction", error))
903    }
904}
905
906#[cfg(feature = "sqlite")]
907fn sqlite_persist_error(context: &str, error: impl core::fmt::Display) -> OmegaError {
908    OmegaError::Persist(format!("{context}: {error}"))
909}
910
911#[cfg(test)]
912mod tests {
913    use super::*;
914    use crate::types::RuleEffect;
915    use std::env::temp_dir;
916
917    #[test]
918    fn new_snapshots_enable_l2_but_not_l1_self_modification() {
919        let snapshot = KernelSnapshot::default();
920        assert!(snapshot.l2_enabled);
921        assert!(!snapshot.self_modify_enabled);
922    }
923
924    #[test]
925    fn snapshot_json_rejects_input_over_byte_limit() {
926        let oversized = " ".repeat(MAX_SNAPSHOT_BYTES as usize + 1);
927        let err = KernelSnapshot::from_json(&oversized)
928            .unwrap_err()
929            .to_string();
930        assert!(err.contains("snapshot byte limit exceeded"), "{err}");
931    }
932    #[test]
933    fn roundtrip_snapshot_file() {
934        let path = temp_dir().join(format!("omega-s2-{}.json", crate::new_uuid()));
935        let snap = KernelSnapshot {
936            version: 1,
937            total_steps: 7,
938            biases: BTreeMap::from([("stabilize".into(), 0.2)]),
939            constraints: BTreeMap::from([("max_risk".into(), 0.65)]),
940            cas_total_steps: 7,
941            cas_avg_prediction_error: 0.33,
942            cas_adaptation_score: 0.67,
943            cognitive_effect: RuleEffect {
944                error_damping: 0.7,
945                action_preference: BTreeMap::from([("stabilize".into(), 1.5)]),
946                min_uncertainty: 0.08,
947                explore_bonus: -0.2,
948                risk_tolerance: 0.4,
949            },
950            cases: vec![],
951            case_capacity: 256,
952            strategies: BTreeMap::new(),
953            active_modules: BTreeMap::from([("cognitive_rules".into(), "fn x() {}".into())]),
954            patch_history: vec![],
955            ..KernelSnapshot::default()
956        };
957        snap.save_to(&path).unwrap();
958        #[cfg(unix)]
959        {
960            use std::os::unix::fs::PermissionsExt;
961            assert_eq!(
962                fs::metadata(&path).unwrap().permissions().mode() & 0o777,
963                0o600
964            );
965        }
966        let loaded = KernelSnapshot::load_from(&path).unwrap();
967        assert_eq!(loaded.version, CURRENT_SCHEMA_VERSION);
968        assert_eq!(loaded.total_steps, 7);
969        assert!((loaded.cognitive_effect.error_damping - 0.7).abs() < 1e-9);
970        assert!((loaded.cognitive_effect.explore_bonus + 0.2).abs() < 1e-9);
971        assert!((loaded.cognitive_effect.risk_tolerance - 0.4).abs() < 1e-9);
972        let _ = fs::remove_file(&path);
973    }
974
975    #[test]
976    #[cfg(unix)]
977    fn failed_atomic_replace_preserves_previous_state() {
978        let dir = temp_dir().join(format!("omega-atomic-{}", crate::new_uuid()));
979        fs::create_dir_all(&dir).unwrap();
980        let path = dir.join("state.json");
981        fs::create_dir(&path).unwrap();
982        fs::write(path.join("marker"), b"previous-state").unwrap();
983
984        let error = KernelSnapshot::default().save_to(&path).unwrap_err();
985        assert!(error.to_string().contains("atomic replace"), "{error}");
986        assert_eq!(
987            fs::read_to_string(path.join("marker")).unwrap(),
988            "previous-state"
989        );
990        assert!(fs::read_dir(&dir)
991            .unwrap()
992            .filter_map(std::result::Result::ok)
993            .all(|entry| entry.path().extension().and_then(|x| x.to_str()) != Some("tmp")));
994
995        let _ = fs::remove_dir_all(dir);
996    }
997
998    #[test]
999    fn migrates_version_one_to_current() {
1000        // A v1 snapshot lacks the v2 safety fields entirely; they must default.
1001        let path = temp_dir().join(format!("omega-v1-{}.json", crate::new_uuid()));
1002        let raw = r#"{
1003            "version": 1,
1004            "total_steps": 12,
1005            "biases": {},
1006            "constraints": {},
1007            "cas_total_steps": 12,
1008            "cas_avg_prediction_error": 0.1,
1009            "cas_adaptation_score": 0.9,
1010            "cognitive_effect": {
1011                "error_damping": 1.0,
1012                "action_preference": {},
1013                "min_uncertainty": 0.05,
1014                "explore_bonus": 0.0,
1015                "risk_tolerance": 0.5
1016            },
1017            "cases": [],
1018            "case_capacity": 256,
1019            "strategies": {},
1020            "active_modules": {},
1021            "patch_history": []
1022        }"#;
1023        fs::write(&path, raw).unwrap();
1024        let loaded = KernelSnapshot::load_from(&path).unwrap();
1025        assert_eq!(loaded.version, CURRENT_SCHEMA_VERSION);
1026        assert_eq!(loaded.total_steps, 12);
1027        assert!(!loaded.self_modify_enabled);
1028        assert_eq!(loaded.steps_since_last_patch, 100);
1029        assert!(loaded.l2_rollback_effect.is_none());
1030        assert!(loaded.last_l2_decision.is_none());
1031        assert_eq!(loaded.bandit_config.min_dwell_steps, 3);
1032        assert_eq!(
1033            loaded.l2_controller.gate_state,
1034            crate::l2::control::L2GateState::Dormant
1035        );
1036        assert_eq!(loaded.l2_controller.trust.alpha, 0.0);
1037        assert!(!loaded.l2_pending_policy.committed);
1038        assert!(!loaded.l2_applied_policy.committed);
1039        assert!(loaded.l2_controller.cache.entries.is_empty());
1040        let _ = fs::remove_file(&path);
1041    }
1042
1043    #[test]
1044    fn roundtrips_v2_safety_fields() {
1045        let path = temp_dir().join(format!("omega-v2rt-{}.json", crate::new_uuid()));
1046        let mut snap = KernelSnapshot {
1047            total_steps: 42,
1048            ..KernelSnapshot::default()
1049        };
1050        snap.self_modify_enabled = true;
1051        snap.steps_since_last_patch = 3;
1052        snap.l2_rollback_effect = Some(RuleEffect {
1053            error_damping: 0.42,
1054            explore_bonus: 0.11,
1055            ..RuleEffect::default()
1056        });
1057        snap.save_to(&path).unwrap();
1058        let loaded = KernelSnapshot::load_from(&path).unwrap();
1059        assert_eq!(loaded.version, CURRENT_SCHEMA_VERSION);
1060        assert!(loaded.self_modify_enabled);
1061        assert_eq!(loaded.steps_since_last_patch, 3);
1062        let rb = loaded
1063            .l2_rollback_effect
1064            .expect("rollback effect persisted");
1065        assert!((rb.error_damping - 0.42).abs() < 1e-9);
1066        assert!((rb.explore_bonus - 0.11).abs() < 1e-9);
1067        let _ = fs::remove_file(&path);
1068    }
1069
1070    #[test]
1071    fn migrates_version_zero() {
1072        let path = temp_dir().join(format!("omega-mig-{}.json", crate::new_uuid()));
1073        // Pre-0.5 style: omit version field entirely.
1074        let raw = r#"{
1075            "total_steps": 3,
1076            "biases": {},
1077            "constraints": {"max_risk": 0.65},
1078            "cas_total_steps": 3,
1079            "cas_avg_prediction_error": 0.2,
1080            "cas_adaptation_score": 0.5,
1081            "cognitive_effect": {
1082                "error_damping": 1.0,
1083                "action_preference": {},
1084                "min_uncertainty": 0.05,
1085                "explore_bonus": 0.0,
1086                "risk_tolerance": 0.5
1087            },
1088            "cases": [],
1089            "case_capacity": 0,
1090            "strategies": {},
1091            "active_modules": {},
1092            "patch_history": []
1093        }"#;
1094        fs::write(&path, raw).unwrap();
1095        let loaded = KernelSnapshot::load_from(&path).unwrap();
1096        assert_eq!(loaded.version, CURRENT_SCHEMA_VERSION);
1097        assert_eq!(loaded.case_capacity, 256);
1098        assert_eq!(loaded.total_steps, 3);
1099        // v2 safety fields fall back to their safe defaults when migrating v0.
1100        assert!(!loaded.self_modify_enabled);
1101        assert!(loaded.l2_rollback_effect.is_none());
1102        let _ = fs::remove_file(&path);
1103    }
1104
1105    #[test]
1106    fn migrates_v3_and_v4_without_inventing_l2_permission() {
1107        for version in [3, 4] {
1108            let mut value = serde_json::to_value(KernelSnapshot::default()).unwrap();
1109            value["version"] = serde_json::json!(version);
1110            value["l2_enabled"] = serde_json::json!(false);
1111            value["l2_controller"]["gate_state"] = serde_json::json!("ACTIVE");
1112            value["l2_controller"]["trust"]["alpha"] = serde_json::json!(0.9);
1113            value["l2_pending_policy"]["committed"] = serde_json::json!(true);
1114            value["l2_applied_policy"]["committed"] = serde_json::json!(true);
1115
1116            let migrated = KernelSnapshot::from_json(&value.to_string()).unwrap();
1117            assert_eq!(migrated.version, CURRENT_SCHEMA_VERSION);
1118            assert!(!migrated.l2_enabled);
1119            assert_eq!(
1120                migrated.l2_controller.gate_state,
1121                crate::l2::control::L2GateState::Dormant
1122            );
1123            assert_eq!(migrated.l2_controller.trust.alpha, 0.0);
1124            assert!(!migrated.l2_pending_policy.committed);
1125            assert!(!migrated.l2_applied_policy.committed);
1126        }
1127    }
1128
1129    #[test]
1130    fn legacy_decision_cannot_claim_an_l2_intervention() {
1131        let mut value = serde_json::to_value(crate::types::L2DecisionRecord {
1132            selected_arm: 0,
1133            selected_bias: "stabilize".into(),
1134            candidate_arm: 1,
1135            mean_reward: 0.5,
1136            exploration_bonus: 0.1,
1137            ucb_score: Some(0.5),
1138            candidate_ucb_score: Some(0.6),
1139            current_ucb_score: Some(0.5),
1140            reason: crate::types::L2DecisionReason::DwellHold,
1141            dwell_steps: 2,
1142            dwell_suppressed: true,
1143            margin_suppressed: false,
1144            l2_policy_applied: true,
1145            switched: false,
1146            safety_override: false,
1147            adjusted_reward: None,
1148            rollback_count: 0,
1149            switch_cost_applied: 0.0,
1150        })
1151        .unwrap();
1152        value.as_object_mut().unwrap().remove("l2_policy_applied");
1153        let record: crate::types::L2DecisionRecord = serde_json::from_value(value).unwrap();
1154        assert!(!record.l2_policy_applied);
1155    }
1156
1157    #[test]
1158    fn legacy_policy_does_not_enable_spectral_weighting() {
1159        let mut value = serde_json::to_value(crate::types::L2Policy::default()).unwrap();
1160        value.as_object_mut().unwrap().remove("spectral_weighting");
1161        let policy: crate::types::L2Policy = serde_json::from_value(value).unwrap();
1162        assert!(!policy.spectral_weighting);
1163        let snapshot = KernelSnapshot::default();
1164        assert!(!snapshot.l2_pending_policy.spectral_weighting);
1165        assert!(!snapshot.l2_applied_policy.spectral_weighting);
1166        assert!(!crate::l2::L2MetaLayer::new().spectral_control_enabled);
1167    }
1168
1169    #[test]
1170    fn rejects_future_schema() {
1171        let path = temp_dir().join(format!("omega-future-{}.json", crate::new_uuid()));
1172        let snap = KernelSnapshot {
1173            version: 99,
1174            total_steps: 0,
1175            biases: BTreeMap::new(),
1176            constraints: BTreeMap::new(),
1177            cas_total_steps: 0,
1178            cas_avg_prediction_error: 0.0,
1179            cas_adaptation_score: 0.0,
1180            cognitive_effect: RuleEffect::default(),
1181            cases: vec![],
1182            case_capacity: 256,
1183            strategies: BTreeMap::new(),
1184            active_modules: BTreeMap::new(),
1185            patch_history: vec![],
1186            ..KernelSnapshot::default()
1187        };
1188        // Bypass save_to stamping by writing raw.
1189        fs::write(&path, serde_json::to_string(&snap).unwrap()).unwrap();
1190        let err = KernelSnapshot::load_from(&path).unwrap_err();
1191        let msg = format!("{err}");
1192        assert!(msg.contains("newer") || msg.contains("99"), "{msg}");
1193        let _ = fs::remove_file(&path);
1194    }
1195
1196    #[test]
1197    fn memory_state_store_round_trip() {
1198        let store = MemoryStateStore::new();
1199        assert!(store.load_snapshot().expect("empty load").is_none());
1200
1201        let mut params = std::collections::BTreeMap::new();
1202        params.insert(String::from("temperature"), 0.55);
1203        let snap = KernelSnapshot {
1204            total_steps: 7,
1205            external_loop: Some(ExternalLoopState {
1206                last_external_step_id: Some(7),
1207                cooldown: crate::orchestrator::CooldownTracker::new(3),
1208                last_checkpoint_id: Some(String::from("ckpt-7")),
1209                last_checkpoint_uuid: None,
1210                current_params: Some(params),
1211                last_checkpoint_params: None,
1212            }),
1213            ..KernelSnapshot::default()
1214        };
1215        store.save_snapshot(&snap).expect("save memory snapshot");
1216
1217        let loaded = store
1218            .load_snapshot()
1219            .expect("reload memory snapshot")
1220            .expect("snapshot present");
1221        assert_eq!(loaded.total_steps, 7);
1222        let ext = loaded.external_loop.expect("external loop state");
1223        assert_eq!(ext.last_external_step_id, Some(7));
1224        assert_eq!(ext.current_params.expect("params")["temperature"], 0.55);
1225    }
1226
1227    #[test]
1228    fn file_state_store_round_trip() {
1229        let dir = std::env::temp_dir().join(format!(
1230            "omega-file-store-test-{}-{}",
1231            std::process::id(),
1232            std::time::SystemTime::now()
1233                .duration_since(std::time::UNIX_EPOCH)
1234                .expect("system time")
1235                .as_nanos()
1236        ));
1237        std::fs::create_dir_all(&dir).expect("create temp dir");
1238        let path = dir.join("state.json");
1239        let store = FileStateStore::new(path.clone());
1240        assert_eq!(store.path(), path.as_path());
1241        assert!(store.load_snapshot().expect("missing file load").is_none());
1242
1243        let snap = KernelSnapshot {
1244            total_steps: 11,
1245            ..KernelSnapshot::default()
1246        };
1247        store.save_snapshot(&snap).expect("save file snapshot");
1248        let loaded = store
1249            .load_snapshot()
1250            .expect("load file snapshot")
1251            .expect("file snapshot present");
1252        assert_eq!(loaded.total_steps, 11);
1253
1254        let _ = std::fs::remove_dir_all(dir);
1255    }
1256}