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