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 crate::error::{OmegaError, Result};
7use serde::{Deserialize, Serialize};
8use std::path::{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/// Serializable product config (omega.toml).
92#[derive(Debug, Clone, Serialize, Deserialize)]
93#[serde(default)]
94pub struct KernelConfig {
95    /// Path for state.json (relative or absolute).
96    pub state_path: Option<String>,
97    pub autosave: bool,
98    pub auto_checkpoint_on_patch: bool,
99    /// L1 reflector: mean-error threshold that can trigger a patch.
100    pub error_threshold: f64,
101    /// L1 reflector: minimum steps between accepted patches.
102    pub min_steps_between_patches: u64,
103    /// L0 constraint: max_risk used in decision scoring.
104    pub max_risk: f64,
105    /// Optional initial goal string for CLI convenience (not enforced by Kernel).
106    pub default_goal: Option<String>,
107    /// Optional strategy-governance policy (friction + domain mode).
108    pub intervention: InterventionPolicy,
109    /// Master switch for autonomous cognitive code / rule evolution (L1 patches).
110    /// Default **false** — self-modification only when explicitly enabled.
111    pub self_modify_enabled: bool,
112    /// If true, every step appends a full trajectory record to trajectory.jsonl
113    /// beside the state file. Default true for auditability.
114    pub dump_trajectory: bool,
115}
116
117impl Default for KernelConfig {
118    fn default() -> Self {
119        Self {
120            state_path: None,
121            autosave: true,
122            auto_checkpoint_on_patch: true,
123            error_threshold: 0.30,
124            min_steps_between_patches: 3,
125            max_risk: 0.65,
126            default_goal: None,
127            intervention: InterventionPolicy::default(),
128            self_modify_enabled: false,
129            dump_trajectory: true,
130        }
131    }
132}
133
134impl KernelConfig {
135    pub fn from_toml(s: &str) -> Result<Self> {
136        toml::from_str(s).map_err(|e| OmegaError::Config(format!("parse TOML: {e}")))
137    }
138
139    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
140        let path = path.as_ref();
141        let raw = std::fs::read_to_string(path)
142            .map_err(|e| OmegaError::Config(format!("read {}: {e}", path.display())))?;
143        Self::from_toml(&raw)
144    }
145
146    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
147        let path = path.as_ref();
148        let body = toml::to_string_pretty(self)
149            .map_err(|e| OmegaError::Config(format!("serialize TOML: {e}")))?;
150        std::fs::write(path, body)
151            .map_err(|e| OmegaError::Config(format!("write {}: {e}", path.display())))?;
152        Ok(())
153    }
154
155    pub fn resolved_state_path(&self) -> PathBuf {
156        self.state_path
157            .as_ref()
158            .map(PathBuf::from)
159            .unwrap_or_else(|| PathBuf::from(crate::persist::DEFAULT_STATE_PATH))
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn roundtrip_defaults() {
169        let c = KernelConfig::default();
170        let s = toml::to_string_pretty(&c).unwrap();
171        let c2 = KernelConfig::from_toml(&s).unwrap();
172        assert!((c2.error_threshold - 0.30).abs() < 1e-9);
173        assert_eq!(c2.min_steps_between_patches, 3);
174        assert!((c2.max_risk - 0.65).abs() < 1e-9);
175        assert_eq!(c2.intervention.friction_threshold, 2);
176        assert!(!c2.self_modify_enabled);
177        assert!(c2.dump_trajectory);
178    }
179
180    #[test]
181    fn parse_partial() {
182        let s = r#"
183max_risk = 0.4
184error_threshold = 0.25
185autosave = false
186self_modify_enabled = true
187"#;
188        let c = KernelConfig::from_toml(s).unwrap();
189        assert!((c.max_risk - 0.4).abs() < 1e-9);
190        assert!((c.error_threshold - 0.25).abs() < 1e-9);
191        assert!(!c.autosave);
192        assert!(c.auto_checkpoint_on_patch); // default
193        assert_eq!(c.intervention.mode, InterventionMode::Exploration);
194        assert!(c.self_modify_enabled);
195    }
196
197    #[test]
198    fn intervention_strict_blocks_alternative() {
199        let p = InterventionPolicy {
200            mode: InterventionMode::Strict,
201            max_level: InterventionLevel::SuggestAlternative,
202            friction_threshold: 1,
203            audit_escalations: true,
204        };
205        assert!(!p.may_suggest_alternative(5));
206        assert_eq!(p.effective_max_level(), InterventionLevel::RefuseToDecide);
207    }
208
209    #[test]
210    fn intervention_exploration_allows_after_threshold() {
211        let p = InterventionPolicy::default();
212        assert!(!p.may_suggest_alternative(1));
213        assert!(p.may_suggest_alternative(2));
214    }
215
216    #[test]
217    fn parse_intervention_table() {
218        let s = r#"
219[intervention]
220mode = "strict"
221max_level = "in_frame"
222friction_threshold = 5
223audit_escalations = false
224"#;
225        let c = KernelConfig::from_toml(s).unwrap();
226        assert_eq!(c.intervention.mode, InterventionMode::Strict);
227        assert_eq!(c.intervention.max_level, InterventionLevel::InFrame);
228        assert_eq!(c.intervention.friction_threshold, 5);
229        assert!(!c.intervention.audit_escalations);
230    }
231}