1#[allow(unused_imports)]
4use crate::prelude::*;
5
6use serde::{Deserialize, Serialize};
7use std::collections::{BTreeMap, BTreeSet};
8use std::path::PathBuf;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
12#[serde(rename_all = "snake_case")]
13pub enum InterventionMode {
14 #[default]
16 Exploration,
17 Strict,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
23#[serde(rename_all = "snake_case")]
24pub enum InterventionLevel {
25 Silent,
27 #[default]
29 InFrame,
30 SuggestAlternative,
32 RefuseToDecide,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
41#[serde(default)]
42pub struct InterventionPolicy {
43 pub mode: InterventionMode,
45 pub max_level: InterventionLevel,
47 pub friction_threshold: u32,
50 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 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 InterventionLevel::SuggestAlternative | InterventionLevel::RefuseToDecide => {
73 InterventionLevel::RefuseToDecide
74 }
75 },
76 InterventionMode::Exploration => self.max_level,
77 }
78 }
79
80 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#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
93#[serde(default)]
94pub struct PrivacyConfig {
95 pub redact_user_content: bool,
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
101#[serde(default)]
102pub struct KernelConfig {
103 pub state_path: Option<String>,
105 pub autosave: bool,
107 pub auto_checkpoint_on_patch: bool,
109 pub error_threshold: f64,
111 pub min_steps_between_patches: u64,
113 pub max_risk: f64,
115 pub default_goal: Option<String>,
117 pub intervention: InterventionPolicy,
119 pub self_modify_enabled: bool,
122 #[serde(default)]
123 pub l1_shadow_mode: bool,
125 pub dump_trajectory: bool,
128 pub privacy: PrivacyConfig,
130 pub bandit: crate::types::BanditConfig,
132 pub l2: L2Config,
135 #[serde(default)]
136 pub layers: LayerSwitches,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub policy_schema: Option<PolicySchema>,
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
147#[serde(default)]
148pub struct L2Config {
149 pub enabled: bool,
151 pub commit_threshold: f64,
153 pub commit_cooldown_steps: u64,
155 pub negative_reward_required: u32,
157 pub alpha_max: f64,
159 pub alpha_rise_rate: f64,
161 pub trust_cooldown_steps: u32,
163 pub error_margin: f64,
165 pub reward_drop_margin: f64,
167 pub rollback_wakeup: u32,
169 pub calm_required: u32,
171 pub window_size: usize,
173 pub beta_max: f64,
175 pub lyapunov_gamma: f64,
177 pub lyapunov_epsilon: f64,
179 pub hedge_forgetting: f64,
181 pub hedge_learning_rate: f64,
183 pub dayan_relaxation: f64,
185 pub meta_cache_capacity: usize,
187 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 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 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)]
365pub struct LayerSwitches {
367 pub l0: bool,
369 pub l1: bool,
371 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]
388pub enum LoopPreset {
390 Deterministic,
392 HotPatcher,
394 MetaGuard,
396 FastAdapt,
398 SteadyPrior,
400 ControlPlane,
402 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")]
450pub enum PatchDirection {
452 DecreaseOnError,
454 IncreaseOnError,
456}
457
458#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
459pub struct ParameterSpec {
461 pub name: String,
463 pub min: f64,
465 pub max: f64,
467 pub initial: f64,
469 pub max_step: f64,
471 pub direction: PatchDirection,
473}
474
475impl ParameterSpec {
476 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)]
501pub struct PolicySchema {
526 pub params: Vec<ParameterSpec>,
528}
529
530impl PolicySchema {
531 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 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 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)]
561pub enum LoopMode {
563 InternalWorld,
565 ExternalTelemetry,
567}
568
569impl LayerSwitches {
570 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]
583pub enum L1RuntimeGate {
585 Disabled,
587 Active,
589 ShadowOnly,
591 BlockedByL2,
593}
594
595impl KernelConfig {
596 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 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}