#[allow(unused_imports)]
use crate::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum InterventionMode {
#[default]
Exploration,
Strict,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum InterventionLevel {
Silent,
#[default]
InFrame,
SuggestAlternative,
RefuseToDecide,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct InterventionPolicy {
pub mode: InterventionMode,
pub max_level: InterventionLevel,
pub friction_threshold: u32,
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 {
pub fn effective_max_level(&self) -> InterventionLevel {
match self.mode {
InterventionMode::Strict => match self.max_level {
InterventionLevel::Silent | InterventionLevel::InFrame => self.max_level,
InterventionLevel::SuggestAlternative | InterventionLevel::RefuseToDecide => {
InterventionLevel::RefuseToDecide
}
},
InterventionMode::Exploration => self.max_level,
}
}
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
}
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PrivacyConfig {
pub redact_user_content: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct KernelConfig {
pub state_path: Option<String>,
pub autosave: bool,
pub auto_checkpoint_on_patch: bool,
pub error_threshold: f64,
pub min_steps_between_patches: u64,
pub max_risk: f64,
pub default_goal: Option<String>,
pub intervention: InterventionPolicy,
pub self_modify_enabled: bool,
#[serde(default)]
pub l1_shadow_mode: bool,
pub dump_trajectory: bool,
pub privacy: PrivacyConfig,
pub bandit: crate::types::BanditConfig,
pub l2: L2Config,
#[serde(default)]
pub layers: LayerSwitches,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policy_schema: Option<PolicySchema>,
}
#[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(),
policy_schema: None,
}
}
}
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")]
#[non_exhaustive]
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, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PatchDirection {
DecreaseOnError,
IncreaseOnError,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ParameterSpec {
pub name: String,
pub min: f64,
pub max: f64,
pub initial: f64,
pub max_step: f64,
pub direction: PatchDirection,
}
impl ParameterSpec {
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)]
pub struct PolicySchema {
pub params: Vec<ParameterSpec>,
}
impl PolicySchema {
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(())
}
pub fn initial_values(&self) -> BTreeMap<String, f64> {
self.params
.iter()
.map(|p| (p.name.clone(), p.initial))
.collect()
}
}
impl KernelConfig {
pub fn with_policy_schema(mut self, schema: PolicySchema) -> Self {
self.policy_schema = Some(schema);
self
}
}
#[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")]
#[non_exhaustive]
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,
}
}
}
}