Skip to main content

omega_cognitive_kernel/
config.rs

1//! TOML configuration for product-facing Kernel knobs.
2
3#[allow(unused_imports)]
4use crate::prelude::*;
5
6use serde::{Deserialize, Serialize};
7use std::collections::{BTreeMap, BTreeSet};
8use std::path::PathBuf;
9
10/// When the assistant/kernel may escalate beyond the user's local frame.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
12#[serde(rename_all = "snake_case")]
13pub enum InterventionMode {
14    /// DX / tool friction: allow path alternatives after friction threshold.
15    #[default]
16    Exploration,
17    /// High-stakes domains: answer in-frame only; never decide for the user.
18    Strict,
19}
20
21/// Highest intervention the system is allowed to take under current mode.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
23#[serde(rename_all = "snake_case")]
24pub enum InterventionLevel {
25    /// No unsolicited guidance.
26    Silent,
27    /// Stay inside the user's stated problem frame.
28    #[default]
29    InFrame,
30    /// May propose an alternative path (e.g. Codespaces vs local MSVC).
31    SuggestAlternative,
32    /// Must not decide; only checklist / refuse-to-decide.
33    RefuseToDecide,
34}
35
36/// Strategy-governance knobs (friction + risk domain).
37///
38/// Additive for 0.4.x — all fields optional with safe defaults.
39/// See `docs/INTERVENTION_POLICY.md`.
40#[derive(Debug, Clone, Serialize, Deserialize)]
41#[serde(default)]
42pub struct InterventionPolicy {
43    /// exploration = DX efficiency; strict = high-stakes governance.
44    pub mode: InterventionMode,
45    /// Cap on how far the system may escalate under this mode.
46    pub max_level: InterventionLevel,
47    /// Consecutive similar env/build failures before suggesting an alternative path.
48    /// Only honored when `mode = exploration` and `max_level` allows it.
49    pub friction_threshold: u32,
50    /// If true, emit audit-friendly notes when escalation is suppressed or allowed.
51    pub audit_escalations: bool,
52}
53
54impl Default for InterventionPolicy {
55    fn default() -> Self {
56        Self {
57            mode: InterventionMode::Exploration,
58            max_level: InterventionLevel::SuggestAlternative,
59            friction_threshold: 2,
60            audit_escalations: true,
61        }
62    }
63}
64
65impl InterventionPolicy {
66    /// Effective max level after applying mode constraints.
67    pub fn effective_max_level(&self) -> InterventionLevel {
68        match self.mode {
69            InterventionMode::Strict => match self.max_level {
70                InterventionLevel::Silent | InterventionLevel::InFrame => self.max_level,
71                // Strict mode never allows unsolicited path-alternatives as auto-decide.
72                InterventionLevel::SuggestAlternative | InterventionLevel::RefuseToDecide => {
73                    InterventionLevel::RefuseToDecide
74                }
75            },
76            InterventionMode::Exploration => self.max_level,
77        }
78    }
79
80    /// Whether friction streak may trigger a path-alternative suggestion.
81    pub fn may_suggest_alternative(&self, consecutive_failures: u32) -> bool {
82        matches!(self.mode, InterventionMode::Exploration)
83            && matches!(
84                self.effective_max_level(),
85                InterventionLevel::SuggestAlternative
86            )
87            && consecutive_failures >= self.friction_threshold
88    }
89}
90
91/// Persistence privacy controls. Redaction is opt-in to preserve legacy output.
92#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
93#[serde(default)]
94pub struct PrivacyConfig {
95    /// Replace known user-provided goal/task/checkpoint-label text in persisted output.
96    pub redact_user_content: bool,
97}
98
99/// Serializable product config (omega.toml).
100#[derive(Debug, Clone, Serialize, Deserialize)]
101#[serde(default)]
102pub struct KernelConfig {
103    /// Path for state.json (relative or absolute).
104    pub state_path: Option<String>,
105    /// Whether autosave is enabled or active.
106    pub autosave: bool,
107    /// Whether auto checkpoint on patch is enabled or active.
108    pub auto_checkpoint_on_patch: bool,
109    /// L1 reflector: mean-error threshold that can trigger a patch.
110    pub error_threshold: f64,
111    /// L1 reflector: minimum steps between accepted patches.
112    pub min_steps_between_patches: u64,
113    /// L0 constraint: max_risk used in decision scoring.
114    pub max_risk: f64,
115    /// Optional initial goal string for CLI convenience (not enforced by Kernel).
116    pub default_goal: Option<String>,
117    /// Optional strategy-governance policy (friction + domain mode).
118    pub intervention: InterventionPolicy,
119    /// Master switch for autonomous cognitive code / rule evolution (L1 patches).
120    /// Default **false** — self-modification only when explicitly enabled.
121    pub self_modify_enabled: bool,
122    #[serde(default)]
123    /// Whether L1 shadow mode is enabled or active.
124    pub l1_shadow_mode: bool,
125    /// If true, every step appends a full trajectory record to trajectory.jsonl
126    /// beside the state file. Default true for auditability.
127    pub dump_trajectory: bool,
128    /// Optional privacy controls for user-provided text persisted to disk.
129    pub privacy: PrivacyConfig,
130    /// Hysteresis and consequence costs for UCB-backed bandit decisions.
131    pub bandit: crate::types::BanditConfig,
132    /// Resident L2 controller. Monitoring is always on; bounded interventions
133    /// are enabled by default and can be disabled with `l2.enabled = false`.
134    pub l2: L2Config,
135    #[serde(default)]
136    /// Layers for this value.
137    pub layers: LayerSwitches,
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    /// Optional policy schema.
140    pub policy_schema: Option<PolicySchema>,
141}
142
143/// Pure-numeric resident-control parameters. Bounds are checked when applied
144/// to the controller so untrusted configuration cannot invalidate the safety
145/// certificate or EXP3 support assumptions.
146#[derive(Debug, Clone, Serialize, Deserialize)]
147#[serde(default)]
148pub struct L2Config {
149    /// Whether enabled is enabled or active.
150    pub enabled: bool,
151    /// Commit threshold for this value.
152    pub commit_threshold: f64,
153    /// Number of commit cooldown.
154    pub commit_cooldown_steps: u64,
155    /// Negative reward required for this value.
156    pub negative_reward_required: u32,
157    /// Alpha maximum for this value.
158    pub alpha_max: f64,
159    /// Alpha rise rate for this value.
160    pub alpha_rise_rate: f64,
161    /// Number of trust cooldown.
162    pub trust_cooldown_steps: u32,
163    /// Error margin for this value.
164    pub error_margin: f64,
165    /// Reward drop margin for this value.
166    pub reward_drop_margin: f64,
167    /// Rollback wakeup for this value.
168    pub rollback_wakeup: u32,
169    /// Calm required for this value.
170    pub calm_required: u32,
171    /// Window size for this value.
172    pub window_size: usize,
173    /// Beta maximum for this value.
174    pub beta_max: f64,
175    /// Lyapunov gamma for this value.
176    pub lyapunov_gamma: f64,
177    /// Lyapunov epsilon for this value.
178    pub lyapunov_epsilon: f64,
179    /// Hedge forgetting for this value.
180    pub hedge_forgetting: f64,
181    /// Hedge learning rate for this value.
182    pub hedge_learning_rate: f64,
183    /// Dayan relaxation for this value.
184    pub dayan_relaxation: f64,
185    /// Meta cache capacity for this value.
186    pub meta_cache_capacity: usize,
187    /// Meta cache hit threshold for this value.
188    pub meta_cache_hit_threshold: f64,
189}
190
191impl Default for L2Config {
192    fn default() -> Self {
193        Self {
194            enabled: true,
195            commit_threshold: 0.82,
196            commit_cooldown_steps: 5,
197            negative_reward_required: 3,
198            alpha_max: 0.35,
199            alpha_rise_rate: 0.08,
200            trust_cooldown_steps: 3,
201            error_margin: 0.04,
202            reward_drop_margin: 0.18,
203            rollback_wakeup: 2,
204            calm_required: 3,
205            window_size: 16,
206            beta_max: 2.0,
207            lyapunov_gamma: 0.05,
208            lyapunov_epsilon: 0.01,
209            hedge_forgetting: 0.97,
210            hedge_learning_rate: 0.35,
211            dayan_relaxation: 0.35,
212            meta_cache_capacity: 16,
213            meta_cache_hit_threshold: 0.78,
214        }
215    }
216}
217
218fn finite_or(value: f64, fallback: f64) -> f64 {
219    if value.is_finite() {
220        value
221    } else {
222        fallback
223    }
224}
225
226impl L2Config {
227    /// Applies these settings to an L2 layer, bounding numeric values to supported ranges.
228    pub fn apply_to(&self, layer: &mut crate::l2::L2MetaLayer) {
229        layer.enabled = self.enabled;
230        layer.commit_threshold = finite_or(self.commit_threshold, 0.82).clamp(0.0, 1.0);
231        layer.commit_cooldown_steps = self.commit_cooldown_steps.min(10_000);
232        layer.commit_cooldown_remaining = layer
233            .commit_cooldown_remaining
234            .min(layer.commit_cooldown_steps);
235        layer.negative_reward_required = self.negative_reward_required.max(1);
236        let controller = &mut layer.controller;
237        controller.trust.alpha_max = finite_or(self.alpha_max, 0.35).clamp(0.0, 0.35);
238        controller.trust.rise_rate = finite_or(self.alpha_rise_rate, 0.08).clamp(0.0, 0.35);
239        controller.trust.cooldown_steps = self.trust_cooldown_steps.min(10_000);
240        controller.trust.alpha = controller.trust.alpha.min(controller.trust.alpha_max);
241        controller.error_margin = finite_or(self.error_margin, 0.04).clamp(0.0, 1.0);
242        controller.reward_drop_margin = finite_or(self.reward_drop_margin, 0.18).clamp(0.0, 1.0);
243        controller.rollback_wakeup = self.rollback_wakeup.max(1);
244        controller.calm_required = self.calm_required.max(1);
245        controller.max_error_history = self.window_size.clamp(2, 1024);
246        controller.errors.truncate(controller.max_error_history);
247        controller.rewards.truncate(controller.max_error_history);
248        controller.beta_max = finite_or(self.beta_max, 2.0).clamp(0.0, 100.0);
249        controller.certificate.gamma = finite_or(self.lyapunov_gamma, 0.05).clamp(0.0, 1.0);
250        controller.certificate.epsilon = finite_or(self.lyapunov_epsilon, 0.01).clamp(0.0, 1.0);
251        controller.experts.forgetting = finite_or(self.hedge_forgetting, 0.97).clamp(0.0, 0.999999);
252        controller.experts.learning_rate =
253            finite_or(self.hedge_learning_rate, 0.35).clamp(0.0, 1.0);
254        controller.dayan_relaxation = finite_or(self.dayan_relaxation, 0.35).clamp(0.01, 1.0);
255        controller.cache.capacity = self.meta_cache_capacity.clamp(1, 256);
256        controller.cache.entries.truncate(controller.cache.capacity);
257        controller.cache.hit_threshold =
258            finite_or(self.meta_cache_hit_threshold, 0.78).clamp(0.0, 1.0);
259        if !self.enabled {
260            controller.gate_state = crate::l2::control::L2GateState::Dormant;
261            controller.retire_requested = false;
262            controller.trust.alpha = 0.0;
263            layer.pending_policy = crate::types::L2Policy::default();
264            layer.applied_policy = crate::types::L2Policy::default();
265        }
266    }
267}
268
269impl Default for KernelConfig {
270    fn default() -> Self {
271        Self {
272            state_path: None,
273            autosave: true,
274            auto_checkpoint_on_patch: true,
275            error_threshold: 0.30,
276            min_steps_between_patches: 3,
277            max_risk: 0.65,
278            default_goal: None,
279            intervention: InterventionPolicy::default(),
280            self_modify_enabled: false,
281            l1_shadow_mode: false,
282            dump_trajectory: true,
283            privacy: PrivacyConfig::default(),
284            bandit: crate::types::BanditConfig::default(),
285            l2: L2Config::default(),
286            layers: LayerSwitches::default(),
287            policy_schema: None,
288        }
289    }
290}
291
292impl KernelConfig {
293    /// Returns the configured state path, or the crate's default path when none is set.
294    pub fn resolved_state_path(&self) -> PathBuf {
295        self.state_path
296            .as_ref()
297            .map(PathBuf::from)
298            .unwrap_or_else(|| PathBuf::from(crate::persist::DEFAULT_STATE_PATH))
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305
306    #[test]
307    fn l2_config_bounds_nonfinite_values_and_preserves_bandit_settings() {
308        let mut layer = crate::l2::L2MetaLayer::new();
309        let config = L2Config {
310            enabled: false,
311            commit_threshold: f64::NAN,
312            commit_cooldown_steps: u64::MAX,
313            alpha_max: f64::NAN,
314            alpha_rise_rate: f64::INFINITY,
315            error_margin: f64::NAN,
316            reward_drop_margin: f64::NEG_INFINITY,
317            beta_max: f64::NAN,
318            lyapunov_gamma: f64::NAN,
319            lyapunov_epsilon: f64::INFINITY,
320            hedge_forgetting: f64::NAN,
321            hedge_learning_rate: f64::INFINITY,
322            dayan_relaxation: f64::NAN,
323            meta_cache_hit_threshold: f64::NAN,
324            ..L2Config::default()
325        };
326        config.apply_to(&mut layer);
327        assert_eq!(layer.commit_threshold, 0.82);
328        assert_eq!(layer.commit_cooldown_steps, 10_000);
329        assert_eq!(layer.controller.trust.alpha_max, 0.35);
330        assert_eq!(layer.controller.trust.rise_rate, 0.08);
331        assert_eq!(layer.controller.error_margin, 0.04);
332        assert_eq!(layer.controller.reward_drop_margin, 0.18);
333        assert_eq!(layer.controller.beta_max, 2.0);
334        assert_eq!(layer.controller.certificate.gamma, 0.05);
335        assert_eq!(layer.controller.certificate.epsilon, 0.01);
336        assert_eq!(layer.controller.experts.forgetting, 0.97);
337        assert_eq!(layer.controller.experts.learning_rate, 0.35);
338        assert_eq!(layer.controller.dayan_relaxation, 0.35);
339        assert_eq!(layer.controller.cache.hit_threshold, 0.78);
340        assert!(!layer.enabled);
341        assert!(!layer.pending_policy.committed);
342        assert!(!layer.applied_policy.committed);
343    }
344
345    #[test]
346    fn intervention_strict_blocks_alternative() {
347        let p = InterventionPolicy {
348            mode: InterventionMode::Strict,
349            max_level: InterventionLevel::SuggestAlternative,
350            friction_threshold: 1,
351            audit_escalations: true,
352        };
353        assert!(!p.may_suggest_alternative(5));
354        assert_eq!(p.effective_max_level(), InterventionLevel::RefuseToDecide);
355    }
356
357    #[test]
358    fn intervention_exploration_allows_after_threshold() {
359        let p = InterventionPolicy::default();
360        assert!(!p.may_suggest_alternative(1));
361        assert!(p.may_suggest_alternative(2));
362    }
363}
364#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
365/// Enablement settings for the L0, L1, and L2 layers.
366pub struct LayerSwitches {
367    /// Whether the L0 internal-world layer is enabled.
368    pub l0: bool,
369    /// Whether the L1 learning and patch layer is enabled.
370    pub l1: bool,
371    /// Whether the L2 meta-control layer is enabled.
372    pub l2: bool,
373}
374
375impl Default for LayerSwitches {
376    fn default() -> Self {
377        Self {
378            l0: true,
379            l1: false,
380            l2: true,
381        }
382    }
383}
384
385#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
386#[serde(rename_all = "snake_case")]
387#[non_exhaustive]
388/// Named preset for enabling a predefined combination of cognitive layers.
389pub enum LoopPreset {
390    /// Enables only L0 for deterministic internal-world execution.
391    Deterministic,
392    /// Enables only L1 for a patch-focused control loop.
393    HotPatcher,
394    /// Enables only L2 for meta-control without L0 execution or L1 patching.
395    MetaGuard,
396    /// Enables L0 and L1 for internal execution with adaptation.
397    FastAdapt,
398    /// Enables L0 and L2 while keeping L1 patching disabled.
399    SteadyPrior,
400    /// Enables L1 and L2 for an external control plane.
401    ControlPlane,
402    /// Enables L0, L1, and L2 together.
403    FullKernel,
404}
405
406impl From<LoopPreset> for LayerSwitches {
407    fn from(preset: LoopPreset) -> Self {
408        match preset {
409            LoopPreset::Deterministic => Self {
410                l0: true,
411                l1: false,
412                l2: false,
413            },
414            LoopPreset::HotPatcher => Self {
415                l0: false,
416                l1: true,
417                l2: false,
418            },
419            LoopPreset::MetaGuard => Self {
420                l0: false,
421                l1: false,
422                l2: true,
423            },
424            LoopPreset::FastAdapt => Self {
425                l0: true,
426                l1: true,
427                l2: false,
428            },
429            LoopPreset::SteadyPrior => Self {
430                l0: true,
431                l1: false,
432                l2: true,
433            },
434            LoopPreset::ControlPlane => Self {
435                l0: false,
436                l1: true,
437                l2: true,
438            },
439            LoopPreset::FullKernel => Self {
440                l0: true,
441                l1: true,
442                l2: true,
443            },
444        }
445    }
446}
447
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
449#[serde(rename_all = "snake_case")]
450/// Direction in which a policy parameter changes in response to error.
451pub enum PatchDirection {
452    /// Move the parameter downward when prediction error calls for a patch.
453    DecreaseOnError,
454    /// Move the parameter upward when prediction error calls for a patch.
455    IncreaseOnError,
456}
457
458#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
459/// Bounds and update rules for one named policy parameter.
460pub struct ParameterSpec {
461    /// Unique name used to address this policy parameter.
462    pub name: String,
463    /// Inclusive lower bound for the parameter value.
464    pub min: f64,
465    /// Inclusive upper bound for the parameter value.
466    pub max: f64,
467    /// Initial value assigned to the parameter.
468    pub initial: f64,
469    /// Largest permitted change to the parameter in one update.
470    pub max_step: f64,
471    /// Direction in which the parameter changes in response to prediction error.
472    pub direction: PatchDirection,
473}
474
475impl ParameterSpec {
476    /// Validates the name, finite bounds, initial value, and positive step limit.
477    ///
478    /// The initial value must lie within the inclusive `[min, max]` range.
479    pub fn validate(&self) -> std::result::Result<(), &'static str> {
480        if self.name.trim().is_empty() {
481            return Err("parameter name cannot be empty");
482        }
483        if !(self.min.is_finite()
484            && self.max.is_finite()
485            && self.initial.is_finite()
486            && self.max_step.is_finite())
487        {
488            return Err("parameter bounds and step must be finite");
489        }
490        if self.min > self.max || self.initial < self.min || self.initial > self.max {
491            return Err("parameter requires min <= initial <= max");
492        }
493        if self.max_step <= 0.0 {
494            return Err("parameter max_step must be positive");
495        }
496        Ok(())
497    }
498}
499
500#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
501/// Set of uniquely named policy parameters with bounds and initial values.
502///
503/// Validation rejects duplicate names, non-finite values, invalid bounds, and non-positive
504/// maximum step sizes. [`initial_values`](Self::initial_values) extracts a map of names to
505/// starting values.
506///
507/// # Examples
508///
509/// ```
510/// use omega_cognitive_kernel::config::{ParameterSpec, PatchDirection, PolicySchema};
511///
512/// let schema = PolicySchema {
513///     params: vec![ParameterSpec {
514///         name: "temperature".into(),
515///         min: 0.0,
516///         max: 1.0,
517///         initial: 0.25,
518///         max_step: 0.1,
519///         direction: PatchDirection::DecreaseOnError,
520///     }],
521/// };
522/// assert!(schema.validate().is_ok());
523/// assert_eq!(schema.initial_values()["temperature"], 0.25);
524/// ```
525pub struct PolicySchema {
526    /// Parameter specifications included in this policy schema.
527    pub params: Vec<ParameterSpec>,
528}
529
530impl PolicySchema {
531    /// Validates every parameter and rejects duplicate names.
532    pub fn validate(&self) -> std::result::Result<(), &'static str> {
533        let mut seen = BTreeSet::new();
534        for spec in &self.params {
535            spec.validate()?;
536            if !seen.insert(spec.name.as_str()) {
537                return Err("duplicate parameter name in PolicySchema");
538            }
539        }
540        Ok(())
541    }
542
543    /// Returns a map from each parameter name to its configured initial value.
544    pub fn initial_values(&self) -> BTreeMap<String, f64> {
545        self.params
546            .iter()
547            .map(|p| (p.name.clone(), p.initial))
548            .collect()
549    }
550}
551
552impl KernelConfig {
553    /// Sets the schema used to initialize and validate named policy parameters.
554    pub fn with_policy_schema(mut self, schema: PolicySchema) -> Self {
555        self.policy_schema = Some(schema);
556        self
557    }
558}
559
560#[derive(Debug, Clone, Copy, PartialEq, Eq)]
561/// Execution mode implied by a valid [`LayerSwitches`] combination.
562pub enum LoopMode {
563    /// L0 executes steps inside the kernel.
564    InternalWorld,
565    /// The host executes steps and supplies telemetry to the kernel.
566    ExternalTelemetry,
567}
568
569impl LayerSwitches {
570    /// Rejects combinations with no enabled layer and returns the resulting execution mode.
571    pub fn validate(&self) -> std::result::Result<LoopMode, &'static str> {
572        match (self.l0, self.l1, self.l2) {
573            (false, false, false) => Err("at least one of L0, L1, or L2 must be enabled"),
574            (true, _, _) => Ok(LoopMode::InternalWorld),
575            (false, _, _) => Ok(LoopMode::ExternalTelemetry),
576        }
577    }
578}
579
580#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
581#[serde(rename_all = "snake_case")]
582#[non_exhaustive]
583/// Runtime disposition of L1 processing for the current step.
584pub enum L1RuntimeGate {
585    /// Variant representing disabled.
586    Disabled,
587    /// Variant representing active.
588    Active,
589    /// Variant representing shadow only.
590    ShadowOnly,
591    /// Variant representing blocked by L2.
592    BlockedByL2,
593}
594
595impl KernelConfig {
596    /// Creates or updates a value with loop preset.
597    pub fn with_loop_preset(mut self, preset: LoopPreset) -> Self {
598        let switches: LayerSwitches = preset.into();
599        self.layers = switches;
600        self.self_modify_enabled = switches.l1;
601        self.l2.enabled = switches.l2;
602        self
603    }
604}
605impl KernelConfig {
606    /// Returns the effective settings after applying defaults and safety gates.
607    pub fn effective_switches(&self) -> LayerSwitches {
608        let default_layers = LayerSwitches::default();
609        if self.layers != default_layers {
610            self.layers
611        } else {
612            LayerSwitches {
613                l0: self.layers.l0,
614                l1: self.self_modify_enabled || self.layers.l1,
615                l2: self.l2.enabled,
616            }
617        }
618    }
619}