1#[allow(unused_imports)]
2use crate::prelude::*;
3
4use crate::l1::spectral::{L1SpectralReflector, SpectralPatch};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum CognitiveRealm {
9 FirstMountainKeepL0,
11 NotMountainDeconstruct,
13 StillMountainRestore,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum L2State {
20 Dormant,
22 Active,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq)]
27pub enum L2Decision {
29 KeepL0,
31 InjectBias(f64),
33}
34
35#[derive(Debug, Clone, Copy)]
36pub struct L2Config {
38 pub window_size: usize,
40 pub enter_dc_drift: f64,
42 pub exit_dc_drift: f64,
44 pub enter_lf_ratio: f64,
46 pub dormant_confirm_steps: usize,
48 pub anchor_ema_alpha: f64,
50 pub decay_gamma: f64,
52 pub inject_eta: f64,
54 pub deadband_eps: f64,
56 pub tail_avg_len: usize,
58 pub min_ac_energy: f64,
61 pub enter_lf_snr: f64,
63 pub high_freq_penalty: f64,
65 pub max_bias: f64,
67 pub control_enabled: bool,
69 pub purity_prior_enabled: bool,
71 pub history_discount_enabled: bool,
73 pub history_discount_factor: f64,
75 pub reverse_brake_enabled: bool,
77}
78
79impl L2Config {
80 pub fn with_window(window_size: usize) -> Self {
82 let n = window_size.max(1) as f64;
83 let decay_gamma = libm::exp(-2.0 / n);
84 Self {
85 window_size,
86 enter_dc_drift: 0.15,
87 exit_dc_drift: 0.05,
88 enter_lf_ratio: 0.65,
89 dormant_confirm_steps: 3,
90 anchor_ema_alpha: 0.05,
91 decay_gamma,
92 inject_eta: 1.0 - decay_gamma,
93 deadband_eps: 1e-4,
94 tail_avg_len: 3,
95 min_ac_energy: 1e-12,
96 enter_lf_snr: 0.01,
97 high_freq_penalty: 2.0,
98 max_bias: 1.0,
99 control_enabled: false,
103 purity_prior_enabled: false,
104 history_discount_enabled: false,
105 history_discount_factor: 0.85,
106 reverse_brake_enabled: false,
107 }
108 }
109
110 fn sanitized(mut self) -> Self {
111 self.window_size = self.window_size.max(2);
112 self.enter_dc_drift = libm::fabs(self.enter_dc_drift);
113 self.exit_dc_drift = libm::fabs(self.exit_dc_drift).min(self.enter_dc_drift);
114 self.enter_lf_ratio = self.enter_lf_ratio.clamp(0.0, 1.0);
115 self.anchor_ema_alpha = self.anchor_ema_alpha.clamp(0.0, 1.0);
116 self.decay_gamma = self.decay_gamma.clamp(0.0, 0.999999);
117 self.inject_eta = self.inject_eta.max(0.0);
118 self.min_ac_energy = self.min_ac_energy.max(0.0);
119 self.enter_lf_snr = self.enter_lf_snr.max(0.0);
120 self.high_freq_penalty = self.high_freq_penalty.max(0.0);
121 self.max_bias = self.max_bias.max(1e-9);
122 self.history_discount_factor = self.history_discount_factor.clamp(0.01, 1.0);
123 self
124 }
125}
126
127#[derive(Debug, Clone, Copy)]
128pub struct KernelStepOutput {
130 pub realm: CognitiveRealm,
132 pub state: L2State,
134 pub decision: L2Decision,
136 pub bias: f64,
138 pub dc_anchor: f64,
140 pub convergence_residual: f64,
142 pub dc_drift: f64,
144 pub normalized_energy: f64,
146 pub low_freq_ratio: f64,
148 pub eta_eff: f64,
150 pub regime_detected: bool,
154}
155
156pub struct L2CognitiveGate {
158 cfg: L2Config,
159 state: L2State,
160 bias: f64,
161 dc_anchor: f64,
162 anchor_initialized: bool,
163 calm_streak: usize,
164}
165
166impl L2CognitiveGate {
167 pub fn new(cfg: L2Config) -> Self {
169 Self {
170 cfg: cfg.sanitized(),
171 state: L2State::Dormant,
172 bias: 0.0,
173 dc_anchor: 0.0,
174 anchor_initialized: false,
175 calm_streak: 0,
176 }
177 }
178
179 pub fn step(
181 &mut self,
182 reflector: &L1SpectralReflector,
183 l0_rewards: &[f64],
184 ) -> KernelStepOutput {
185 let latest = l0_rewards.last().copied().unwrap_or(0.0);
186
187 if !self.anchor_initialized
188 && l0_rewards.len() >= self.cfg.window_size
189 && self.cfg.window_size > 0
190 {
191 let win = &l0_rewards[l0_rewards.len() - self.cfg.window_size..];
192 self.dc_anchor = win.iter().sum::<f64>() / (self.cfg.window_size as f64);
193 self.anchor_initialized = true;
194 }
195
196 let patch_opt = if self.anchor_initialized {
197 reflector.reflect_and_patch_anchored(l0_rewards, self.dc_anchor)
198 } else {
199 None
200 };
201 let mut dc_drift = 0.0;
202 let mut normalized_energy = 0.0;
203 let mut low_freq_ratio = 0.0;
204 let mut eta_eff = 0.0;
205 let mut regime_detected = false;
206
207 let realm = match patch_opt {
208 None => {
209 if self.state == L2State::Active {
210 self.calm_streak += 1;
211 if self.calm_streak >= self.cfg.dormant_confirm_steps {
212 self.state = L2State::Dormant;
213 self.calm_streak = 0;
214 }
215 }
216 self.decay_bias_only();
217
218 if self.state == L2State::Dormant && self.anchor_initialized {
219 self.dc_anchor = (1.0 - self.cfg.anchor_ema_alpha) * self.dc_anchor
220 + self.cfg.anchor_ema_alpha * latest;
221 }
222
223 if self.bias == 0.0 && self.state == L2State::Dormant {
224 CognitiveRealm::FirstMountainKeepL0
225 } else {
226 CognitiveRealm::StillMountainRestore
227 }
228 }
229
230 Some(patch) => {
231 if !self.anchor_initialized {
232 self.dc_anchor = patch.dc_baseline;
233 self.anchor_initialized = true;
234 }
235
236 dc_drift = libm::fabs(patch.dc_baseline - self.dc_anchor);
237 normalized_energy = patch.normalized_energy;
238 low_freq_ratio = 1.0 - patch.high_freq_ratio;
239 let anchor_power = self.dc_anchor * self.dc_anchor;
240 let low_freq_snr = (patch.total_ac * low_freq_ratio) / anchor_power.max(1.0);
241 let significant_dc = dc_drift > self.cfg.enter_dc_drift;
242 let significant_low_freq = low_freq_ratio > self.cfg.enter_lf_ratio
243 && patch.total_ac >= self.cfg.min_ac_energy
244 && low_freq_snr > self.cfg.enter_lf_snr;
245
246 match self.state {
247 L2State::Dormant => {
248 if significant_dc || significant_low_freq {
249 self.state = L2State::Active;
250 self.calm_streak = 0;
251 regime_detected = significant_dc;
252 eta_eff = self.inject_from_patch(&patch);
253 CognitiveRealm::StillMountainRestore
254 } else {
255 self.decay_bias_only();
256 self.dc_anchor = (1.0 - self.cfg.anchor_ema_alpha) * self.dc_anchor
257 + self.cfg.anchor_ema_alpha * patch.dc_baseline;
258
259 if self.bias == 0.0 {
260 CognitiveRealm::NotMountainDeconstruct
261 } else {
262 CognitiveRealm::StillMountainRestore
263 }
264 }
265 }
266
267 L2State::Active => {
268 if dc_drift < self.cfg.exit_dc_drift && !significant_low_freq {
269 self.calm_streak += 1;
270 if self.calm_streak >= self.cfg.dormant_confirm_steps {
271 self.state = L2State::Dormant;
272 self.calm_streak = 0;
273 self.decay_bias_only();
274 } else {
275 eta_eff = self.inject_from_patch(&patch);
276 }
277 } else {
278 self.calm_streak = 0;
279 eta_eff = self.inject_from_patch(&patch);
280 }
281 CognitiveRealm::StillMountainRestore
282 }
283 }
284 }
285 };
286
287 self.clamp_bias();
288 let decision = if realm != CognitiveRealm::StillMountainRestore {
289 L2Decision::KeepL0
290 } else {
291 L2Decision::InjectBias(self.bias)
292 };
293
294 let convergence_residual = latest - (self.dc_anchor + self.bias);
295
296 KernelStepOutput {
297 realm,
298 state: self.state,
299 decision,
300 bias: self.bias,
301 dc_anchor: self.dc_anchor,
302 convergence_residual,
303 dc_drift,
304 normalized_energy,
305 low_freq_ratio,
306 eta_eff,
307 regime_detected: regime_detected && self.cfg.history_discount_enabled,
308 }
309 }
310
311 fn inject_from_patch(&mut self, patch: &SpectralPatch) -> f64 {
312 let restored = L1SpectralReflector::inverse_restore(&patch.filtered_spectrum);
313 if restored.is_empty() {
314 self.decay_bias_only();
315 return 0.0;
316 }
317 let k = self.cfg.tail_avg_len.max(1).min(restored.len());
318 let tail_avg = restored[restored.len() - k..].iter().sum::<f64>() / (k as f64);
319 let trend_delta = tail_avg - self.dc_anchor;
320 if !trend_delta.is_finite() {
321 self.decay_bias_only();
322 return 0.0;
323 }
324 let gamma = if self.cfg.reverse_brake_enabled
325 && self.bias != 0.0
326 && trend_delta * self.bias < 0.0
327 {
328 self.cfg.decay_gamma * self.cfg.decay_gamma
329 } else {
330 self.cfg.decay_gamma
331 };
332 let lf_ratio = 1.0 - patch.high_freq_ratio;
333 let eta_eff = self.cfg.inject_eta * lf_ratio
334 / (1.0 + self.cfg.high_freq_penalty * patch.high_freq_ratio);
335 self.bias = gamma * self.bias + eta_eff * trend_delta;
336 self.clamp_bias();
337 eta_eff
338 }
339
340 fn clamp_bias(&mut self) {
341 self.bias = if self.bias.is_finite() {
342 self.bias.clamp(-self.cfg.max_bias, self.cfg.max_bias)
343 } else {
344 0.0
345 };
346 }
347
348 pub fn configure_control(&mut self, enabled: bool) {
350 self.cfg.control_enabled = enabled;
351 }
352
353 pub fn configure_ablation(
355 &mut self,
356 purity_prior: bool,
357 reverse_brake: bool,
358 history_discount: bool,
359 ) {
360 self.cfg.purity_prior_enabled = purity_prior;
361 self.cfg.reverse_brake_enabled = reverse_brake;
362 self.cfg.history_discount_enabled = history_discount;
363 }
364
365 pub fn permits_intervention(&self, output: &KernelStepOutput) -> bool {
367 !self.cfg.control_enabled || output.realm == CognitiveRealm::StillMountainRestore
368 }
369
370 pub fn explore_prior(&self, output: &KernelStepOutput) -> [f64; 2] {
372 if !self.cfg.purity_prior_enabled {
373 return [0.1, 0.9];
374 }
375 let strength = (libm::fabs(output.bias) / self.cfg.max_bias).clamp(0.0, 1.0);
376 [1.0 - strength, strength]
377 }
378
379 pub fn history_discount_factor(&self) -> f64 {
381 self.cfg.history_discount_factor
382 }
383
384 fn decay_bias_only(&mut self) {
385 self.bias *= self.cfg.decay_gamma;
386 self.clamp_bias();
387 if self.state == L2State::Dormant && libm::fabs(self.bias) < self.cfg.deadband_eps {
388 self.bias = 0.0;
389 }
390 }
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 #[test]
398 fn first_mountain_stays_keep_l0_on_steady_rewards() {
399 let reflector = L1SpectralReflector::new(8, 1e-4, 1);
400 let mut gate = L2CognitiveGate::new(L2Config::with_window(8));
401 let out = gate.step(&reflector, &[0.5; 8]);
402 assert_eq!(out.realm, CognitiveRealm::FirstMountainKeepL0);
403 assert_eq!(out.state, L2State::Dormant);
404 assert_eq!(out.decision, L2Decision::KeepL0);
405 assert_eq!(out.bias, 0.0);
406 }
407
408 #[test]
409 fn high_frequency_jitter_stays_in_second_realm_without_injecting_bias() {
410 let reflector = L1SpectralReflector::new(8, 1e-4, 1);
411 let mut gate = L2CognitiveGate::new(L2Config::with_window(8));
412 let _ = gate.step(&reflector, &[0.0; 8]);
413 let jitter = [0.5, -0.5, 0.5, -0.5, 0.5, -0.5, 0.5, -0.5];
414 let out = gate.step(&reflector, &jitter);
415 assert_eq!(out.realm, CognitiveRealm::NotMountainDeconstruct);
416 assert_eq!(out.state, L2State::Dormant);
417 assert_eq!(out.decision, L2Decision::KeepL0);
418 }
419
420 fn experiment_config() -> L2Config {
421 L2Config {
422 control_enabled: true,
423 purity_prior_enabled: true,
424 reverse_brake_enabled: true,
425 history_discount_enabled: true,
426 ..L2Config::with_window(8)
427 }
428 }
429
430 #[test]
431 fn experimental_components_are_disabled_until_explicitly_enabled() {
432 let config = L2Config::with_window(8);
433 assert!(!config.control_enabled);
434 assert!(!config.purity_prior_enabled);
435 assert!(!config.reverse_brake_enabled);
436 assert!(!config.history_discount_enabled);
437 let reflector = L1SpectralReflector::new(8, 1e-4, 1);
438 let mut gate = L2CognitiveGate::new(config);
439 let _ = gate.step(&reflector, &[0.0; 8]);
440 let shift = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0];
441 let output = gate.step(&reflector, &shift);
442 assert!(
443 !output.regime_detected,
444 "history discount is not armed without opt-in"
445 );
446 assert!(gate.permits_intervention(&output));
447 assert_eq!(gate.explore_prior(&output), [0.1, 0.9]);
448 }
449
450 #[test]
451 fn regime_shift_activates_third_realm_and_injects_bounded_bias() {
452 let reflector = L1SpectralReflector::new(8, 1e-4, 1);
453 let mut gate = L2CognitiveGate::new(experiment_config());
454 let _ = gate.step(&reflector, &[0.0; 8]);
455 let shift = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0];
456 let out = gate.step(&reflector, &shift);
457 assert_eq!(out.realm, CognitiveRealm::StillMountainRestore);
458 assert_eq!(out.state, L2State::Active);
459 assert!(matches!(out.decision, L2Decision::InjectBias(b) if b > 0.0));
460 assert!(out.dc_drift > 0.0);
461 assert!(out.regime_detected);
462 }
463
464 #[test]
465 fn tiny_slow_drift_stays_in_second_realm() {
466 let reflector = L1SpectralReflector::new(8, 1e-4, 1);
467 let mut gate = L2CognitiveGate::new(L2Config::with_window(8));
468 let _ = gate.step(&reflector, &[1.0; 8]);
469 let tiny = [1.0, 1.0, 1.0, 1.0, 1.2, 1.2, 1.2, 1.2];
470 let out = gate.step(&reflector, &tiny);
471 assert_eq!(out.realm, CognitiveRealm::NotMountainDeconstruct);
472 assert_eq!(out.decision, L2Decision::KeepL0);
473 }
474
475 #[test]
476 fn opposite_trend_brakes_and_bias_is_bounded() {
477 let reflector = L1SpectralReflector::new(8, 1e-4, 1);
478 let config = L2Config {
479 max_bias: 0.2,
480 ..experiment_config()
481 };
482 let mut gate = L2CognitiveGate::new(config);
483 let _ = gate.step(&reflector, &[0.0; 8]);
484 let up = gate.step(&reflector, &[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]);
485 assert!(up.bias > 0.0 && up.bias <= 0.2);
486 let down = gate.step(&reflector, &[0.0, 0.0, 0.0, 0.0, -1.0, -1.0, -1.0, -1.0]);
487 assert!(down.bias.abs() <= 0.2);
488 assert!(down.bias < up.bias);
489 }
490}