omega-cognitive-kernel 0.9.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
//! TOML configuration for product-facing Kernel knobs.

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

use serde::{Deserialize, Serialize};
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>,
    pub autosave: bool,
    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)]
    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)]
    pub layers: LayerSwitches,
}

/// 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 {
    pub enabled: bool,
    pub commit_threshold: f64,
    pub commit_cooldown_steps: u64,
    pub negative_reward_required: u32,
    pub alpha_max: f64,
    pub alpha_rise_rate: f64,
    pub trust_cooldown_steps: u32,
    pub error_margin: f64,
    pub reward_drop_margin: f64,
    pub rollback_wakeup: u32,
    pub calm_required: u32,
    pub window_size: usize,
    pub beta_max: f64,
    pub lyapunov_gamma: f64,
    pub lyapunov_epsilon: f64,
    pub hedge_forgetting: f64,
    pub hedge_learning_rate: f64,
    pub dayan_relaxation: f64,
    pub meta_cache_capacity: usize,
    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 {
    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(),
        }
    }
}

impl KernelConfig {
    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)]
pub struct LayerSwitches {
    pub l0: bool,
    pub l1: bool,
    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")]
pub enum LoopPreset {
    Deterministic,
    HotPatcher,
    MetaGuard,
    FastAdapt,
    SteadyPrior,
    ControlPlane,
    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)]
pub enum LoopMode {
    InternalWorld,
    ExternalTelemetry,
}

impl LayerSwitches {
    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")]
pub enum L1RuntimeGate {
    Disabled,
    Active,
    ShadowOnly,
    BlockedByL2,
}

impl KernelConfig {
    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 {
    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,
            }
        }
    }
}