omega-cognitive-kernel 1.0.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! TOML configuration for product-facing Kernel knobs.

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

use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

/// When the assistant/kernel may escalate beyond the user's local frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum InterventionMode {
    /// DX / tool friction: allow path alternatives after friction threshold.
    #[default]
    Exploration,
    /// High-stakes domains: answer in-frame only; never decide for the user.
    Strict,
}

/// Highest intervention the system is allowed to take under current mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum InterventionLevel {
    /// No unsolicited guidance.
    Silent,
    /// Stay inside the user's stated problem frame.
    #[default]
    InFrame,
    /// May propose an alternative path (e.g. Codespaces vs local MSVC).
    SuggestAlternative,
    /// Must not decide; only checklist / refuse-to-decide.
    RefuseToDecide,
}

/// Strategy-governance knobs (friction + risk domain).
///
/// Additive for 0.4.x — all fields optional with safe defaults.
/// See `docs/INTERVENTION_POLICY.md`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct InterventionPolicy {
    /// exploration = DX efficiency; strict = high-stakes governance.
    pub mode: InterventionMode,
    /// Cap on how far the system may escalate under this mode.
    pub max_level: InterventionLevel,
    /// Consecutive similar env/build failures before suggesting an alternative path.
    /// Only honored when `mode = exploration` and `max_level` allows it.
    pub friction_threshold: u32,
    /// If true, emit audit-friendly notes when escalation is suppressed or allowed.
    pub audit_escalations: bool,
}

impl Default for InterventionPolicy {
    fn default() -> Self {
        Self {
            mode: InterventionMode::Exploration,
            max_level: InterventionLevel::SuggestAlternative,
            friction_threshold: 2,
            audit_escalations: true,
        }
    }
}

impl InterventionPolicy {
    /// Effective max level after applying mode constraints.
    pub fn effective_max_level(&self) -> InterventionLevel {
        match self.mode {
            InterventionMode::Strict => match self.max_level {
                InterventionLevel::Silent | InterventionLevel::InFrame => self.max_level,
                // Strict mode never allows unsolicited path-alternatives as auto-decide.
                InterventionLevel::SuggestAlternative | InterventionLevel::RefuseToDecide => {
                    InterventionLevel::RefuseToDecide
                }
            },
            InterventionMode::Exploration => self.max_level,
        }
    }

    /// Whether friction streak may trigger a path-alternative suggestion.
    pub fn may_suggest_alternative(&self, consecutive_failures: u32) -> bool {
        matches!(self.mode, InterventionMode::Exploration)
            && matches!(
                self.effective_max_level(),
                InterventionLevel::SuggestAlternative
            )
            && consecutive_failures >= self.friction_threshold
    }
}

/// Persistence privacy controls. Redaction is opt-in to preserve legacy output.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PrivacyConfig {
    /// Replace known user-provided goal/task/checkpoint-label text in persisted output.
    pub redact_user_content: bool,
}

/// Serializable product config (omega.toml).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct KernelConfig {
    /// Path for state.json (relative or absolute).
    pub state_path: Option<String>,
    /// Whether autosave is enabled or active.
    pub autosave: bool,
    /// Whether auto checkpoint on patch is enabled or active.
    pub auto_checkpoint_on_patch: bool,
    /// L1 reflector: mean-error threshold that can trigger a patch.
    pub error_threshold: f64,
    /// L1 reflector: minimum steps between accepted patches.
    pub min_steps_between_patches: u64,
    /// L0 constraint: max_risk used in decision scoring.
    pub max_risk: f64,
    /// Optional initial goal string for CLI convenience (not enforced by Kernel).
    pub default_goal: Option<String>,
    /// Optional strategy-governance policy (friction + domain mode).
    pub intervention: InterventionPolicy,
    /// Master switch for autonomous cognitive code / rule evolution (L1 patches).
    /// Default **false** — self-modification only when explicitly enabled.
    pub self_modify_enabled: bool,
    #[serde(default)]
    /// Whether L1 shadow mode is enabled or active.
    pub l1_shadow_mode: bool,
    /// If true, every step appends a full trajectory record to trajectory.jsonl
    /// beside the state file. Default true for auditability.
    pub dump_trajectory: bool,
    /// Optional privacy controls for user-provided text persisted to disk.
    pub privacy: PrivacyConfig,
    /// Hysteresis and consequence costs for UCB-backed bandit decisions.
    pub bandit: crate::types::BanditConfig,
    /// Resident L2 controller. Monitoring is always on; bounded interventions
    /// are enabled by default and can be disabled with `l2.enabled = false`.
    pub l2: L2Config,
    #[serde(default)]
    /// Layers for this value.
    pub layers: LayerSwitches,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional policy schema.
    pub policy_schema: Option<PolicySchema>,
}

/// Pure-numeric resident-control parameters. Bounds are checked when applied
/// to the controller so untrusted configuration cannot invalidate the safety
/// certificate or EXP3 support assumptions.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct L2Config {
    /// Whether enabled is enabled or active.
    pub enabled: bool,
    /// Commit threshold for this value.
    pub commit_threshold: f64,
    /// Number of commit cooldown.
    pub commit_cooldown_steps: u64,
    /// Negative reward required for this value.
    pub negative_reward_required: u32,
    /// Alpha maximum for this value.
    pub alpha_max: f64,
    /// Alpha rise rate for this value.
    pub alpha_rise_rate: f64,
    /// Number of trust cooldown.
    pub trust_cooldown_steps: u32,
    /// Error margin for this value.
    pub error_margin: f64,
    /// Reward drop margin for this value.
    pub reward_drop_margin: f64,
    /// Rollback wakeup for this value.
    pub rollback_wakeup: u32,
    /// Calm required for this value.
    pub calm_required: u32,
    /// Window size for this value.
    pub window_size: usize,
    /// Beta maximum for this value.
    pub beta_max: f64,
    /// Lyapunov gamma for this value.
    pub lyapunov_gamma: f64,
    /// Lyapunov epsilon for this value.
    pub lyapunov_epsilon: f64,
    /// Hedge forgetting for this value.
    pub hedge_forgetting: f64,
    /// Hedge learning rate for this value.
    pub hedge_learning_rate: f64,
    /// Dayan relaxation for this value.
    pub dayan_relaxation: f64,
    /// Meta cache capacity for this value.
    pub meta_cache_capacity: usize,
    /// Meta cache hit threshold for this value.
    pub meta_cache_hit_threshold: f64,
}

impl Default for L2Config {
    fn default() -> Self {
        Self {
            enabled: true,
            commit_threshold: 0.82,
            commit_cooldown_steps: 5,
            negative_reward_required: 3,
            alpha_max: 0.35,
            alpha_rise_rate: 0.08,
            trust_cooldown_steps: 3,
            error_margin: 0.04,
            reward_drop_margin: 0.18,
            rollback_wakeup: 2,
            calm_required: 3,
            window_size: 16,
            beta_max: 2.0,
            lyapunov_gamma: 0.05,
            lyapunov_epsilon: 0.01,
            hedge_forgetting: 0.97,
            hedge_learning_rate: 0.35,
            dayan_relaxation: 0.35,
            meta_cache_capacity: 16,
            meta_cache_hit_threshold: 0.78,
        }
    }
}

fn finite_or(value: f64, fallback: f64) -> f64 {
    if value.is_finite() {
        value
    } else {
        fallback
    }
}

impl L2Config {
    /// Applies these settings to an L2 layer, bounding numeric values to supported ranges.
    pub fn apply_to(&self, layer: &mut crate::l2::L2MetaLayer) {
        layer.enabled = self.enabled;
        layer.commit_threshold = finite_or(self.commit_threshold, 0.82).clamp(0.0, 1.0);
        layer.commit_cooldown_steps = self.commit_cooldown_steps.min(10_000);
        layer.commit_cooldown_remaining = layer
            .commit_cooldown_remaining
            .min(layer.commit_cooldown_steps);
        layer.negative_reward_required = self.negative_reward_required.max(1);
        let controller = &mut layer.controller;
        controller.trust.alpha_max = finite_or(self.alpha_max, 0.35).clamp(0.0, 0.35);
        controller.trust.rise_rate = finite_or(self.alpha_rise_rate, 0.08).clamp(0.0, 0.35);
        controller.trust.cooldown_steps = self.trust_cooldown_steps.min(10_000);
        controller.trust.alpha = controller.trust.alpha.min(controller.trust.alpha_max);
        controller.error_margin = finite_or(self.error_margin, 0.04).clamp(0.0, 1.0);
        controller.reward_drop_margin = finite_or(self.reward_drop_margin, 0.18).clamp(0.0, 1.0);
        controller.rollback_wakeup = self.rollback_wakeup.max(1);
        controller.calm_required = self.calm_required.max(1);
        controller.max_error_history = self.window_size.clamp(2, 1024);
        controller.errors.truncate(controller.max_error_history);
        controller.rewards.truncate(controller.max_error_history);
        controller.beta_max = finite_or(self.beta_max, 2.0).clamp(0.0, 100.0);
        controller.certificate.gamma = finite_or(self.lyapunov_gamma, 0.05).clamp(0.0, 1.0);
        controller.certificate.epsilon = finite_or(self.lyapunov_epsilon, 0.01).clamp(0.0, 1.0);
        controller.experts.forgetting = finite_or(self.hedge_forgetting, 0.97).clamp(0.0, 0.999999);
        controller.experts.learning_rate =
            finite_or(self.hedge_learning_rate, 0.35).clamp(0.0, 1.0);
        controller.dayan_relaxation = finite_or(self.dayan_relaxation, 0.35).clamp(0.01, 1.0);
        controller.cache.capacity = self.meta_cache_capacity.clamp(1, 256);
        controller.cache.entries.truncate(controller.cache.capacity);
        controller.cache.hit_threshold =
            finite_or(self.meta_cache_hit_threshold, 0.78).clamp(0.0, 1.0);
        if !self.enabled {
            controller.gate_state = crate::l2::control::L2GateState::Dormant;
            controller.retire_requested = false;
            controller.trust.alpha = 0.0;
            layer.pending_policy = crate::types::L2Policy::default();
            layer.applied_policy = crate::types::L2Policy::default();
        }
    }
}

impl Default for KernelConfig {
    fn default() -> Self {
        Self {
            state_path: None,
            autosave: true,
            auto_checkpoint_on_patch: true,
            error_threshold: 0.30,
            min_steps_between_patches: 3,
            max_risk: 0.65,
            default_goal: None,
            intervention: InterventionPolicy::default(),
            self_modify_enabled: false,
            l1_shadow_mode: false,
            dump_trajectory: true,
            privacy: PrivacyConfig::default(),
            bandit: crate::types::BanditConfig::default(),
            l2: L2Config::default(),
            layers: LayerSwitches::default(),
            policy_schema: None,
        }
    }
}

impl KernelConfig {
    /// Returns the configured state path, or the crate's default path when none is set.
    pub fn resolved_state_path(&self) -> PathBuf {
        self.state_path
            .as_ref()
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from(crate::persist::DEFAULT_STATE_PATH))
    }
}

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

    #[test]
    fn l2_config_bounds_nonfinite_values_and_preserves_bandit_settings() {
        let mut layer = crate::l2::L2MetaLayer::new();
        let config = L2Config {
            enabled: false,
            commit_threshold: f64::NAN,
            commit_cooldown_steps: u64::MAX,
            alpha_max: f64::NAN,
            alpha_rise_rate: f64::INFINITY,
            error_margin: f64::NAN,
            reward_drop_margin: f64::NEG_INFINITY,
            beta_max: f64::NAN,
            lyapunov_gamma: f64::NAN,
            lyapunov_epsilon: f64::INFINITY,
            hedge_forgetting: f64::NAN,
            hedge_learning_rate: f64::INFINITY,
            dayan_relaxation: f64::NAN,
            meta_cache_hit_threshold: f64::NAN,
            ..L2Config::default()
        };
        config.apply_to(&mut layer);
        assert_eq!(layer.commit_threshold, 0.82);
        assert_eq!(layer.commit_cooldown_steps, 10_000);
        assert_eq!(layer.controller.trust.alpha_max, 0.35);
        assert_eq!(layer.controller.trust.rise_rate, 0.08);
        assert_eq!(layer.controller.error_margin, 0.04);
        assert_eq!(layer.controller.reward_drop_margin, 0.18);
        assert_eq!(layer.controller.beta_max, 2.0);
        assert_eq!(layer.controller.certificate.gamma, 0.05);
        assert_eq!(layer.controller.certificate.epsilon, 0.01);
        assert_eq!(layer.controller.experts.forgetting, 0.97);
        assert_eq!(layer.controller.experts.learning_rate, 0.35);
        assert_eq!(layer.controller.dayan_relaxation, 0.35);
        assert_eq!(layer.controller.cache.hit_threshold, 0.78);
        assert!(!layer.enabled);
        assert!(!layer.pending_policy.committed);
        assert!(!layer.applied_policy.committed);
    }

    #[test]
    fn intervention_strict_blocks_alternative() {
        let p = InterventionPolicy {
            mode: InterventionMode::Strict,
            max_level: InterventionLevel::SuggestAlternative,
            friction_threshold: 1,
            audit_escalations: true,
        };
        assert!(!p.may_suggest_alternative(5));
        assert_eq!(p.effective_max_level(), InterventionLevel::RefuseToDecide);
    }

    #[test]
    fn intervention_exploration_allows_after_threshold() {
        let p = InterventionPolicy::default();
        assert!(!p.may_suggest_alternative(1));
        assert!(p.may_suggest_alternative(2));
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
/// Enablement settings for the L0, L1, and L2 layers.
pub struct LayerSwitches {
    /// Whether the L0 internal-world layer is enabled.
    pub l0: bool,
    /// Whether the L1 learning and patch layer is enabled.
    pub l1: bool,
    /// Whether the L2 meta-control layer is enabled.
    pub l2: bool,
}

impl Default for LayerSwitches {
    fn default() -> Self {
        Self {
            l0: true,
            l1: false,
            l2: true,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// Named preset for enabling a predefined combination of cognitive layers.
pub enum LoopPreset {
    /// Enables only L0 for deterministic internal-world execution.
    Deterministic,
    /// Enables only L1 for a patch-focused control loop.
    HotPatcher,
    /// Enables only L2 for meta-control without L0 execution or L1 patching.
    MetaGuard,
    /// Enables L0 and L1 for internal execution with adaptation.
    FastAdapt,
    /// Enables L0 and L2 while keeping L1 patching disabled.
    SteadyPrior,
    /// Enables L1 and L2 for an external control plane.
    ControlPlane,
    /// Enables L0, L1, and L2 together.
    FullKernel,
}

impl From<LoopPreset> for LayerSwitches {
    fn from(preset: LoopPreset) -> Self {
        match preset {
            LoopPreset::Deterministic => Self {
                l0: true,
                l1: false,
                l2: false,
            },
            LoopPreset::HotPatcher => Self {
                l0: false,
                l1: true,
                l2: false,
            },
            LoopPreset::MetaGuard => Self {
                l0: false,
                l1: false,
                l2: true,
            },
            LoopPreset::FastAdapt => Self {
                l0: true,
                l1: true,
                l2: false,
            },
            LoopPreset::SteadyPrior => Self {
                l0: true,
                l1: false,
                l2: true,
            },
            LoopPreset::ControlPlane => Self {
                l0: false,
                l1: true,
                l2: true,
            },
            LoopPreset::FullKernel => Self {
                l0: true,
                l1: true,
                l2: true,
            },
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
/// Direction in which a policy parameter changes in response to error.
pub enum PatchDirection {
    /// Move the parameter downward when prediction error calls for a patch.
    DecreaseOnError,
    /// Move the parameter upward when prediction error calls for a patch.
    IncreaseOnError,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Bounds and update rules for one named policy parameter.
pub struct ParameterSpec {
    /// Unique name used to address this policy parameter.
    pub name: String,
    /// Inclusive lower bound for the parameter value.
    pub min: f64,
    /// Inclusive upper bound for the parameter value.
    pub max: f64,
    /// Initial value assigned to the parameter.
    pub initial: f64,
    /// Largest permitted change to the parameter in one update.
    pub max_step: f64,
    /// Direction in which the parameter changes in response to prediction error.
    pub direction: PatchDirection,
}

impl ParameterSpec {
    /// Validates the name, finite bounds, initial value, and positive step limit.
    ///
    /// The initial value must lie within the inclusive `[min, max]` range.
    pub fn validate(&self) -> std::result::Result<(), &'static str> {
        if self.name.trim().is_empty() {
            return Err("parameter name cannot be empty");
        }
        if !(self.min.is_finite()
            && self.max.is_finite()
            && self.initial.is_finite()
            && self.max_step.is_finite())
        {
            return Err("parameter bounds and step must be finite");
        }
        if self.min > self.max || self.initial < self.min || self.initial > self.max {
            return Err("parameter requires min <= initial <= max");
        }
        if self.max_step <= 0.0 {
            return Err("parameter max_step must be positive");
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
/// Set of uniquely named policy parameters with bounds and initial values.
///
/// Validation rejects duplicate names, non-finite values, invalid bounds, and non-positive
/// maximum step sizes. [`initial_values`](Self::initial_values) extracts a map of names to
/// starting values.
///
/// # Examples
///
/// ```
/// use omega_cognitive_kernel::config::{ParameterSpec, PatchDirection, PolicySchema};
///
/// let schema = PolicySchema {
///     params: vec![ParameterSpec {
///         name: "temperature".into(),
///         min: 0.0,
///         max: 1.0,
///         initial: 0.25,
///         max_step: 0.1,
///         direction: PatchDirection::DecreaseOnError,
///     }],
/// };
/// assert!(schema.validate().is_ok());
/// assert_eq!(schema.initial_values()["temperature"], 0.25);
/// ```
pub struct PolicySchema {
    /// Parameter specifications included in this policy schema.
    pub params: Vec<ParameterSpec>,
}

impl PolicySchema {
    /// Validates every parameter and rejects duplicate names.
    pub fn validate(&self) -> std::result::Result<(), &'static str> {
        let mut seen = BTreeSet::new();
        for spec in &self.params {
            spec.validate()?;
            if !seen.insert(spec.name.as_str()) {
                return Err("duplicate parameter name in PolicySchema");
            }
        }
        Ok(())
    }

    /// Returns a map from each parameter name to its configured initial value.
    pub fn initial_values(&self) -> BTreeMap<String, f64> {
        self.params
            .iter()
            .map(|p| (p.name.clone(), p.initial))
            .collect()
    }
}

impl KernelConfig {
    /// Sets the schema used to initialize and validate named policy parameters.
    pub fn with_policy_schema(mut self, schema: PolicySchema) -> Self {
        self.policy_schema = Some(schema);
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Execution mode implied by a valid [`LayerSwitches`] combination.
pub enum LoopMode {
    /// L0 executes steps inside the kernel.
    InternalWorld,
    /// The host executes steps and supplies telemetry to the kernel.
    ExternalTelemetry,
}

impl LayerSwitches {
    /// Rejects combinations with no enabled layer and returns the resulting execution mode.
    pub fn validate(&self) -> std::result::Result<LoopMode, &'static str> {
        match (self.l0, self.l1, self.l2) {
            (false, false, false) => Err("at least one of L0, L1, or L2 must be enabled"),
            (true, _, _) => Ok(LoopMode::InternalWorld),
            (false, _, _) => Ok(LoopMode::ExternalTelemetry),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// Runtime disposition of L1 processing for the current step.
pub enum L1RuntimeGate {
    /// Variant representing disabled.
    Disabled,
    /// Variant representing active.
    Active,
    /// Variant representing shadow only.
    ShadowOnly,
    /// Variant representing blocked by L2.
    BlockedByL2,
}

impl KernelConfig {
    /// Creates or updates a value with loop preset.
    pub fn with_loop_preset(mut self, preset: LoopPreset) -> Self {
        let switches: LayerSwitches = preset.into();
        self.layers = switches;
        self.self_modify_enabled = switches.l1;
        self.l2.enabled = switches.l2;
        self
    }
}
impl KernelConfig {
    /// Returns the effective settings after applying defaults and safety gates.
    pub fn effective_switches(&self) -> LayerSwitches {
        let default_layers = LayerSwitches::default();
        if self.layers != default_layers {
            self.layers
        } else {
            LayerSwitches {
                l0: self.layers.l0,
                l1: self.self_modify_enabled || self.layers.l1,
                l2: self.l2.enabled,
            }
        }
    }
}