omega-cognitive-kernel 1.3.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
#[allow(unused_imports)]
use crate::prelude::*;

pub mod control;
/// Emergence signals and regime-transition logic for L2.
pub mod emergence;
/// Fixed-point detection and stability criteria for L2.
pub mod fixed_point;
/// Cache structures used by the L2 meta-controller.
pub mod meta_cache;
/// L2 policy modulation and bounded parameter updates.
pub mod modulator;
/// Runtime monitors for L2 stability and safety.
pub mod monitor;
/// Spectral checks that gate L2 policy changes.
pub mod spectral_gate;

pub use spectral_gate::{
    CognitiveRealm, KernelStepOutput, L2CognitiveGate, L2Config as SpectralGateConfig, L2Decision,
    L2State,
};

use crate::error::Result;
use crate::types::{MetaMetrics, RuleEffect, SystemState};
use alloc::collections::BTreeMap;
use control::{L2GateState, ResidentController, KEEP_L0};
use emergence::EmergenceDetector;
use fixed_point::{OmegaDayanFixedPoint, ScoreSignals};
use modulator::MetaModulator;
use monitor::MetaMonitor;

#[derive(Debug)]
/// Data structure representing L2 result.
pub struct L2Result {
    /// Metrics for this value.
    pub metrics: MetaMetrics,
    /// Whether L2 is currently in a fixed-point regime.
    pub in_fixed_point: bool,
    /// Mapping of biases.
    pub biases: BTreeMap<String, f64>,
    /// Mapping of constraints.
    pub constraints: BTreeMap<String, f64>,
    /// Whether entered fixed point is enabled or active.
    pub entered_fixed_point: bool,
    /// Whether exited fixed point is enabled or active.
    pub exited_fixed_point: bool,
    /// Alignment score for this value.
    pub alignment_score: f64,
    /// Candidate alignment score for this value.
    pub candidate_alignment_score: f64,
    /// Number of steps spent in the current regime or arm.
    pub dwell_steps: u64,
    /// Candidate score for this value.
    pub candidate_score: f64,
    /// Whether modulation proposed is enabled or active.
    pub modulation_proposed: bool,
    /// Whether modulation committed is enabled or active.
    pub modulation_committed: bool,
    /// Modulation gain for this value.
    pub modulation_gain: f64,
    /// Mapping of score breakdown.
    pub score_breakdown: BTreeMap<String, f64>,
    /// Optional bounded `RuleEffect` update for compatibility paths. The
    /// ordinary UCB intervention path uses `L2Policy` instead.
    pub effect_nudge: Option<RuleEffect>,
    /// The local UCB selection that caused this step's L1/L2 consequences.
    pub decision: Option<crate::types::L2DecisionRecord>,
    /// Latest candidate fixed-point residual: alignment target minus raw alignment.
    pub dayan_residual: f64,
    /// Gate state for this value.
    pub gate_state: L2GateState,
    /// Alpha for this value.
    pub alpha: f64,
    /// Beta for this value.
    pub beta: f64,
    /// Mapping of expert weights.
    pub expert_weights: BTreeMap<String, f64>,
    /// Lyapunov potential for this value.
    pub lyapunov_potential: f64,
    /// Whether lyapunov veto is enabled or active.
    pub lyapunov_veto: bool,
    /// Whether meta cache hit is enabled or active.
    pub meta_cache_hit: bool,
    /// Selected expert for this value.
    pub selected_expert: String,
    /// L2 policy for this value.
    pub l2_policy: crate::types::L2Policy,
    /// Policy that governed the L0 action in this result, not the policy queued
    /// for the next action. This distinction makes IPS and replay causal.
    pub applied_policy: crate::types::L2Policy,
    /// Optional veto reason.
    pub veto_reason: Option<String>,
    /// Optional rejection reason.
    pub rejection_reason: Option<String>,
    /// Optional spectral output.
    pub spectral_output: Option<KernelStepOutput>,
}

/// Data structure representing L2 meta layer.
pub struct L2MetaLayer {
    /// Monitor for this value.
    pub monitor: MetaMonitor,
    /// Detector for this value.
    pub detector: EmergenceDetector,
    /// Fixed point for this value.
    pub fixed_point: OmegaDayanFixedPoint,
    /// Modulator for this value.
    pub modulator: MetaModulator,
    /// Whether L2 is allowed to change biases, constraints, or RuleEffect.
    /// The monitor still runs when disabled so benchmark baselines retain
    /// comparable observability without receiving L2 interventions.
    ///
    /// New kernels enable bounded interventions by default. Use
    /// `Kernel::set_l2_enabled(false)` for an observational baseline.
    pub enabled: bool,
    /// Whether L2 is currently in a fixed-point regime.
    pub in_fixed_point: bool,
    /// How many consecutive steps we have been inside the fixed point.
    pub dwell_steps: u64,
    /// Most recent L2 alignment score.
    pub last_alignment_score: f64,
    /// Commit threshold for this value.
    pub commit_threshold: f64,
    /// Number of commit cooldown.
    pub commit_cooldown_steps: u64,
    /// Commit cooldown remaining for this value.
    pub commit_cooldown_remaining: u64,
    /// Most recent consequence score.
    pub last_consequence_score: f64,
    /// Whether defensive mode is enabled or active.
    pub defensive_mode: bool,
    /// Negative consequence streak for this value.
    pub negative_consequence_streak: u32,
    /// Optional rollback effect.
    pub rollback_effect: Option<RuleEffect>,
    /// Whether external attention is enabled or active.
    pub external_attention: bool,
    /// Number of stable consequence.
    pub stable_consequence_steps: u32,
    /// Reward change score for this value.
    pub reward_change_score: f64,
    /// Error change score for this value.
    pub error_change_score: f64,
    /// Whether awaiting consequence is enabled or active.
    pub awaiting_consequence: bool,
    /// Negative reward streak for this value.
    pub negative_reward_streak: u32,
    /// Negative reward required for this value.
    pub negative_reward_required: u32,
    /// Controller for this value.
    pub controller: ResidentController,
    /// Whether pending L1 rollback is enabled or active.
    pub pending_l1_rollback: bool,
    /// Most recent rejection reason.
    pub last_rejection_reason: Option<String>,
    /// Pending policy for this value.
    pub pending_policy: crate::types::L2Policy,
    /// Validated policy used by the current L0 decision and its outcome.
    pub applied_policy: crate::types::L2Policy,
    /// Most recent error.
    pub last_error: Option<f64>,
    /// Most recent reward.
    pub last_reward: f64,
    /// Consecutive l1 rollbacks for this value.
    pub consecutive_l1_rollbacks: u32,
    /// Current cycle recoveries for this value.
    pub current_cycle_recoveries: u32,
    /// Spectral reflector for this value.
    pub spectral_reflector: crate::l1::spectral::L1SpectralReflector,
    /// Spectral gate for this value.
    pub spectral_gate: L2CognitiveGate,
    /// Collection of spectral history.
    pub spectral_history: Vec<f64>,
    /// Whether spectral control enabled.
    pub spectral_control_enabled: bool,
}

impl L2MetaLayer {
    /// Returns `true` when L2 holds exclusive write priority over `RuleEffect`
    /// (active gate intervention, defensive mode, committed policy, or cooldown).
    pub fn blocks_l1_write(&self) -> bool {
        if !self.enabled {
            return false;
        }
        self.defensive_mode
            || self.controller.gate_state == control::L2GateState::Active
            || self.controller.trust.cooldown_remaining > 0
            || self.commit_cooldown_remaining > 0
            || self.applied_policy.committed
    }
    /// Creates a new value of this type.
    pub fn new() -> Self {
        let mut gate_cfg = SpectralGateConfig::with_window(16);
        gate_cfg.history_discount_enabled = true;
        gate_cfg.history_discount_factor = 0.25;
        Self {
            monitor: MetaMonitor,
            detector: EmergenceDetector::default(),
            fixed_point: OmegaDayanFixedPoint,
            modulator: MetaModulator,
            enabled: true,
            in_fixed_point: false,
            dwell_steps: 0,
            last_alignment_score: 0.0,
            commit_threshold: 0.82,
            commit_cooldown_steps: 5,
            commit_cooldown_remaining: 0,
            last_consequence_score: 0.0,
            defensive_mode: false,
            negative_consequence_streak: 0,
            rollback_effect: None,
            external_attention: false,
            stable_consequence_steps: 0,
            reward_change_score: 0.0,
            error_change_score: 0.0,
            awaiting_consequence: false,
            negative_reward_streak: 0,
            negative_reward_required: 3,
            controller: ResidentController::default(),
            pending_l1_rollback: false,
            pending_policy: crate::types::L2Policy::default(),
            last_rejection_reason: None,
            applied_policy: crate::types::L2Policy::default(),
            last_error: None,
            last_reward: 0.5,
            consecutive_l1_rollbacks: 0,
            current_cycle_recoveries: 0,
            spectral_reflector: crate::l1::spectral::L1SpectralReflector::default(),
            spectral_gate: L2CognitiveGate::new(gate_cfg),
            spectral_history: Vec::new(),
            spectral_control_enabled: false,
        }
    }

    /// Performs step for this type.
    pub fn step(
        &mut self,
        state: &SystemState,
        biases: BTreeMap<String, f64>,
        constraints: BTreeMap<String, f64>,
        _current_effect: &RuleEffect,
    ) -> Result<L2Result> {
        let metrics = self.monitor.evaluate(state)?;
        let mut entered = false;
        let mut exited = false;
        if self.pending_l1_rollback {
            self.consecutive_l1_rollbacks = self.consecutive_l1_rollbacks.saturating_add(1);
            self.pending_l1_rollback = false;
        } else {
            self.consecutive_l1_rollbacks = 0;
        }
        self.commit_cooldown_remaining = self.commit_cooldown_remaining.saturating_sub(1);
        self.controller.meta_cache_hit = false;
        self.controller.certificate.lyapunov_veto = false;
        let mut modulation_proposed = false;
        let mut modulation_committed = false;
        let mut modulation_gain = 0.0;
        let mut rejection_reason = None;

        // Refresh observability even when the intervention switch is off. A
        // disabled baseline therefore reports the real residual, not a sentinel.
        let fp = self.fixed_point.enter_with_signals(
            state,
            ScoreSignals {
                reward_change_score: self.reward_change_score,
                error_change_score: self.error_change_score,
                stability_score: metrics.self_ref_stability,
            },
        )?;
        let candidate_alignment = fp.alignment_score;
        let candidate_score = fp.score;
        let score_breakdown = fp.breakdown.clone();
        self.last_alignment_score = fp.score;
        self.controller.update_dayan(candidate_alignment);

        if !self.enabled {
            self.in_fixed_point = false;
            self.dwell_steps = 0;
            self.controller.gate_state = L2GateState::Dormant;
            self.controller.retire_requested = false;
            self.controller.trust.alpha = 0.0;
            self.controller.last_selected_expert = KEEP_L0;
            self.pending_policy = crate::types::L2Policy::default();
            return self.result(
                metrics,
                biases,
                constraints,
                candidate_score,
                candidate_alignment,
                score_breakdown,
                false,
                false,
                false,
                0,
                candidate_score,
                modulation_proposed,
                modulation_committed,
                modulation_gain,
            );
        }

        if self.consecutive_l1_rollbacks >= self.controller.rollback_wakeup {
            self.controller.trust.alpha = 0.0;
            self.controller.trust.cooldown_remaining = self.controller.trust.cooldown_steps;
        }
        if self.in_fixed_point {
            self.dwell_steps = self.dwell_steps.saturating_add(1);
            if self.detector.should_exit(&metrics) || self.dwell_steps > 40 {
                self.in_fixed_point = false;
                self.dwell_steps = 0;
                exited = true;
            }
        } else if self.detector.should_trigger(&metrics) || self.external_attention {
            entered = fp.aligned;
            self.in_fixed_point = fp.aligned;
            if fp.aligned {
                self.dwell_steps = 1;
            }
        }
        self.external_attention = false;

        self.pending_policy = crate::types::L2Policy::default();
        let spectral_out = self.advance_spectral_output(state);
        let spectral_permits = !self.spectral_control_enabled
            || self.spectral_gate.permits_intervention(&spectral_out);
        let spectral_rejection = self.spectral_control_enabled && !spectral_permits;
        if self.controller.gate_state == L2GateState::Active && self.controller.surprise_started {
            // Recording a recovery context is independent of proposal trust.
            // A cooldown suppresses intervention, not the episode's cache key.
            self.controller.cache_prepared = true;
            self.controller.cache_prepared_fingerprint = self.controller.surprise_fingerprint;
            self.controller.episode_start_residual = self.controller.residual;
            if let Some((_index, weights, alpha)) =
                self.controller.cache.lookup(&self.controller.fingerprint())
            {
                self.controller.experts.warm_start(weights);
                self.controller.trust.alpha = alpha.min(self.controller.trust.alpha_max);
                self.controller.meta_cache_hit = true;
                self.controller.cache_hits = self.controller.cache_hits.saturating_add(1);
            }
        }
        let can_propose = self.controller.gate_state == L2GateState::Active
            && self.controller.trust.cooldown_remaining == 0
            && !self.controller.retire_requested
            && spectral_permits;
        if can_propose {
            let probabilities = self.controller.experts.probabilities();
            let mut selected = if self.controller.meta_cache_hit {
                (1..4)
                    .max_by(|a, b| {
                        self.controller.experts.weights[*a]
                            .partial_cmp(&self.controller.experts.weights[*b])
                            .unwrap_or(core::cmp::Ordering::Equal)
                    })
                    .unwrap_or(1)
            } else {
                self.controller.experts.select(self.controller.ema_error)
            };
            if spectral_out.regime_detected {
                selected = 2;
            } else if spectral_out.realm == CognitiveRealm::FirstMountainKeepL0 && selected == 2 {
                selected = KEEP_L0;
            }
            self.controller.last_selected_expert = selected;
            modulation_proposed = selected != KEEP_L0;
            if selected != KEEP_L0 {
                let predicted_residual = self.controller.predicted_residual(
                    state.avg_prediction_error,
                    self.controller.trust.alpha,
                    selected,
                );
                self.controller.certificate = self
                    .controller
                    .certificate
                    .check(self.controller.residual, predicted_residual);
                if self.controller.certificate.lyapunov_veto {
                    self.controller.veto_count = self.controller.veto_count.saturating_add(1);
                }
                let mut beta = self.controller.beta_for(self.spectral_control_enabled);
                if spectral_out.regime_detected {
                    beta = beta.max(1.0);
                }
                // A high anomaly score is evidence for waking up, not evidence
                // that an intervention will help. Commit confidence comes from
                // the residual model; the Lyapunov certificate is the final
                // predicted-stability guard. This preserves the public
                // commit_threshold knob as a conservative confidence gate.
                let allowed = self.controller.trust.alpha > 0.0
                    && beta > 0.0
                    && !self.controller.certificate.lyapunov_veto
                    && self.commit_cooldown_remaining == 0
                    && !self.defensive_mode
                    && self.controller.model_confidence >= self.commit_threshold.clamp(0.0, 1.0);
                if allowed {
                    self.pending_policy = crate::types::L2Policy {
                        prior: if selected == 2 && self.spectral_control_enabled {
                            self.spectral_gate.explore_prior(&spectral_out)
                        } else {
                            self.controller.prior()
                        },
                        beta,
                        alpha: self.controller.trust.alpha,
                        committed: true,
                        expert: selected,
                        expert_probabilities: probabilities,
                        gate_state: self.controller.gate_state,
                        confidence: self.controller.model_confidence,
                        spectral_weighting: self.spectral_control_enabled,
                    };
                    modulation_committed = true;
                    modulation_gain = self.controller.trust.alpha;
                    self.commit_cooldown_remaining = self.commit_cooldown_steps;
                    self.awaiting_consequence = true;
                } else if self.controller.certificate.lyapunov_veto {
                    rejection_reason = Some("lyapunov_veto".into());
                } else if self.controller.trust.alpha <= 0.0 || beta <= 0.0 {
                    rejection_reason = Some("trust_or_confidence_zero".into());
                } else if self.commit_cooldown_remaining != 0 {
                    rejection_reason = Some("commit_cooldown".into());
                } else if self.defensive_mode {
                    rejection_reason = Some("defensive_mode".into());
                } else {
                    rejection_reason = Some("commit_threshold".into());
                }
            }
        } else {
            self.controller.last_selected_expert = KEEP_L0;
            self.controller.certificate.lyapunov_veto = false;
        }
        if spectral_rejection {
            rejection_reason = Some("spectral_gate".into());
        }
        let mut score_breakdown = score_breakdown;
        score_breakdown.insert("spectral_bias".to_string(), spectral_out.bias);
        score_breakdown.insert(
            "spectral_residual".to_string(),
            spectral_out.convergence_residual,
        );
        let mut result = self.result(
            metrics,
            biases,
            constraints,
            candidate_score,
            candidate_alignment,
            score_breakdown,
            entered,
            exited,
            self.in_fixed_point,
            self.dwell_steps,
            candidate_score,
            modulation_proposed,
            modulation_committed,
            modulation_gain,
        )?;
        result.rejection_reason = rejection_reason.clone();
        self.last_rejection_reason = rejection_reason;
        result.spectral_output = Some(spectral_out);
        Ok(result)
    }

    /// Performs configure spectral control for this type.
    pub fn configure_spectral_control(&mut self, enabled: bool) {
        self.spectral_control_enabled = enabled;
        self.spectral_gate.configure_control(enabled);
    }

    fn advance_spectral_output(&mut self, state: &SystemState) -> KernelStepOutput {
        self.spectral_history
            .push(1.0 - state.avg_prediction_error.clamp(0.0, 1.0));
        if self.spectral_history.len() > 32 {
            self.spectral_history.remove(0);
        }
        self.spectral_gate
            .step(&self.spectral_reflector, &self.spectral_history)
    }

    #[allow(clippy::too_many_arguments)]
    fn result(
        &self,
        metrics: crate::types::MetaMetrics,
        biases: BTreeMap<String, f64>,
        constraints: BTreeMap<String, f64>,
        candidate_score: f64,
        candidate_alignment: f64,
        score_breakdown: BTreeMap<String, f64>,
        entered: bool,
        exited: bool,
        in_fixed_point: bool,
        dwell_steps: u64,
        _legacy_score: f64,
        modulation_proposed: bool,
        modulation_committed: bool,
        modulation_gain: f64,
    ) -> Result<L2Result> {
        Ok(L2Result {
            metrics,
            in_fixed_point,
            biases,
            constraints,
            entered_fixed_point: entered,
            exited_fixed_point: exited,
            alignment_score: candidate_score,
            candidate_alignment_score: candidate_alignment,
            dwell_steps,
            candidate_score,
            modulation_proposed,
            modulation_committed,
            modulation_gain,
            score_breakdown,
            effect_nudge: None,
            decision: None,
            dayan_residual: self.controller.residual,
            gate_state: self.controller.gate_state,
            alpha: self.controller.trust.alpha,
            beta: if self.controller.gate_state == L2GateState::Dormant
                || self.controller.last_selected_expert == KEEP_L0
                || !self.pending_policy.committed
            {
                0.0
            } else {
                self.controller.beta()
            },
            expert_weights: self.controller.expert_weights(),
            lyapunov_potential: self.controller.residual * self.controller.residual,
            lyapunov_veto: self.controller.certificate.lyapunov_veto,
            meta_cache_hit: self.controller.meta_cache_hit,
            selected_expert: control::EXPERT_NAMES
                .get(self.controller.last_selected_expert)
                .copied()
                .unwrap_or(control::EXPERT_NAMES[KEEP_L0])
                .into(),
            l2_policy: self.pending_policy,
            applied_policy: crate::types::L2Policy::default(),
            veto_reason: self
                .controller
                .certificate
                .lyapunov_veto
                .then(|| "lyapunov_veto".into()),
            rejection_reason: None,
            spectral_output: None,
        })
    }

    /// Feed back the short-term consequence of the last committed modulation.
    /// Negative outcomes extend the commit cooldown and leave fixed-point mode.
    pub fn observe_consequence(&mut self, reward_delta: f64, error_delta: f64, risk_delta: f64) {
        let score = 0.60 * reward_delta - 0.25 * error_delta - 0.15 * risk_delta;
        self.last_consequence_score = score;
        if reward_delta < -0.05 {
            self.negative_reward_streak = self.negative_reward_streak.saturating_add(1);
        } else {
            self.negative_reward_streak = 0;
        }
        self.reward_change_score = if self.negative_reward_streak >= self.negative_reward_required {
            ((-reward_delta) / 0.5).clamp(0.0, 1.0)
        } else {
            0.0
        };
        self.error_change_score = (error_delta / 0.15).clamp(0.0, 1.0);
        if !self.awaiting_consequence {
            return;
        }
        self.awaiting_consequence = false;
        if score < -0.05 {
            self.external_attention = true;
            self.stable_consequence_steps = 0;
            self.negative_consequence_streak = self.negative_consequence_streak.saturating_add(1);
            self.commit_cooldown_remaining = self
                .commit_cooldown_remaining
                .max(self.commit_cooldown_steps.saturating_mul(2));
            self.in_fixed_point = false;
            self.dwell_steps = 0;
            if self.negative_consequence_streak >= 2 {
                self.defensive_mode = true;
            }
        } else if score > 0.05 {
            self.stable_consequence_steps = self.stable_consequence_steps.saturating_add(1);
            self.negative_consequence_streak = 0;
            if self.defensive_mode && score > 0.15 {
                self.defensive_mode = false;
            }
        }
    }

    /// Performs take rollback effect for this type.
    pub fn take_rollback_effect(&mut self) -> Option<RuleEffect> {
        if self.last_consequence_score < -0.05 {
            self.rollback_effect.take()
        } else {
            None
        }
    }
}

impl Default for L2MetaLayer {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::{control, L2MetaLayer};
    use crate::l1::spectral::L1SpectralReflector;
    use crate::l2::spectral_gate::{L2CognitiveGate, L2Config};
    use crate::types::{L2Policy, RuleEffect, SystemState};
    use alloc::collections::BTreeMap;

    #[test]
    fn spectral_permission_is_required_only_for_new_proposals() {
        let mut layer = L2MetaLayer::new();
        layer.configure_spectral_control(true);
        layer.controller.gate_state = control::L2GateState::Active;
        layer.controller.trust.alpha = 0.08;
        layer.controller.model_confidence = 1.0;
        layer.controller.residual = 0.0;
        layer.controller.dayan_state = 0.0;
        layer.commit_threshold = 0.0;
        layer.controller.experts.weights = [1e-12, 1.0, 1.0, 1.0];
        let mut state = SystemState {
            highest_attractor: "maintain coherent self-model omega dayan".into(),
            generative_base: Some("auxiliary_base".into()),
            avg_prediction_error: 0.5,
            ..SystemState::default()
        };
        state
            .active_code
            .insert("cognitive_rules".into(), "self bias damp".into());
        for _ in 0..16 {
            let result = layer
                .step(
                    &state,
                    BTreeMap::new(),
                    BTreeMap::new(),
                    &RuleEffect::default(),
                )
                .unwrap();
            assert_eq!(result.rejection_reason.as_deref(), Some("spectral_gate"));
            assert!(!result.modulation_committed);
        }
        let steady = layer
            .step(
                &state,
                BTreeMap::new(),
                BTreeMap::new(),
                &RuleEffect::default(),
            )
            .unwrap();
        assert_eq!(steady.rejection_reason.as_deref(), Some("spectral_gate"));
        assert!(!steady.modulation_committed);
        assert!(!layer.pending_policy.effective().committed);
    }

    #[test]
    fn repeated_surprise_warm_starts_recovered_expert() {
        let mut layer = L2MetaLayer::new();
        layer.enabled = true;
        layer.commit_threshold = 0.0;
        layer.controller.calm_required = 1;
        let mut state = SystemState {
            highest_attractor: "maintain coherent self-model omega dayan".into(),
            generative_base: Some("auxiliary_base".into()),
            avg_prediction_error: 0.1,
            total_steps: 12,
            ..SystemState::default()
        };
        state
            .active_code
            .insert("cognitive_rules".into(), "self bias damp".into());
        for _ in 0..5 {
            layer.controller.feedback_settled = false;
            layer.controller.observe(
                control::ControlFeedback {
                    error: 0.1,
                    reward: 1.0,
                    rollback: false,
                    consequence: 0.1,
                    kl_policy: [0.8, 0.2],
                },
                L2Policy::default(),
            );
        }
        layer.controller.feedback_settled = false;
        layer.controller.observe(
            control::ControlFeedback {
                error: 0.9,
                reward: 1.0,
                rollback: false,
                consequence: 0.0,
                kl_policy: [0.8, 0.2],
            },
            L2Policy::default(),
        );
        assert!(layer.controller.surprise_started);
        let _ = layer.step(
            &state,
            BTreeMap::new(),
            BTreeMap::new(),
            &RuleEffect::default(),
        );
        for _ in 0..5 {
            layer.controller.residual = 0.1;
            layer.controller.feedback_settled = false;
            layer.controller.observe(
                control::ControlFeedback {
                    error: 0.1,
                    reward: 1.0,
                    rollback: false,
                    consequence: 0.1,
                    kl_policy: [0.8, 0.2],
                },
                L2Policy::default(),
            );
        }
        assert!(
            layer.controller.cache_prepared,
            "gate={:?} cooldown={} surprise={} residual={} start={}",
            layer.controller.gate_state,
            layer.controller.trust.cooldown_remaining,
            layer.controller.surprise_started,
            layer.controller.residual,
            layer.controller.episode_start_residual,
        );
        assert!(
            !layer.controller.cache.entries.is_empty(),
            "gate={:?} prepared={} residual={} start={} calm={} cached={}",
            layer.controller.gate_state,
            layer.controller.cache_prepared,
            layer.controller.residual,
            layer.controller.episode_start_residual,
            layer.controller.calm_streak,
            layer.controller.cached_this_episode,
        );
        let saved_fingerprint = layer.controller.cache.entries[0].fingerprint;
        layer.controller.finish_cycle();
        layer.controller.errors.clear();
        layer.controller.rewards.clear();
        layer.controller.window_rollbacks = 0;
        layer.controller.window_total = 0;
        layer.controller.entropy_sum = 0.0;
        layer.controller.gate_state = control::L2GateState::Dormant;
        for _ in 0..5 {
            layer.controller.feedback_settled = false;
            layer.controller.observe(
                control::ControlFeedback {
                    error: 0.1,
                    reward: 1.0,
                    rollback: false,
                    consequence: 0.1,
                    kl_policy: [0.8, 0.2],
                },
                L2Policy::default(),
            );
        }
        layer.controller.feedback_settled = false;
        layer.controller.observe(
            control::ControlFeedback {
                error: 0.9,
                reward: 1.0,
                rollback: false,
                consequence: 0.0,
                kl_policy: [0.8, 0.2],
            },
            L2Policy::default(),
        );
        assert_eq!(layer.controller.fingerprint(), saved_fingerprint);
        assert!(
            layer.controller.surprise_started,
            "gate={:?} ema_error={} baseline_error={} ema_reward={} baseline_reward={}",
            layer.controller.gate_state,
            layer.controller.ema_error,
            layer.controller.baseline_error,
            layer.controller.ema_reward,
            layer.controller.baseline_reward,
        );
        let result = layer
            .step(
                &state,
                BTreeMap::new(),
                BTreeMap::new(),
                &RuleEffect::default(),
            )
            .unwrap();
        assert!(result.meta_cache_hit);
        assert!(result.alpha > 0.0);
        assert_ne!(result.selected_expert, "KEEP_L0");
    }

    #[test]
    fn defensive_mode_recovers_after_strong_positive_consequence() {
        let mut l2 = L2MetaLayer::new();
        l2.enabled = true; // test requires L2 active for consequence path
        l2.defensive_mode = true;
        l2.negative_consequence_streak = 2;
        l2.awaiting_consequence = true;

        // Positive reward and slightly improving error produce a consequence
        // score above the recovery threshold while representing a real
        // post-commit observation.
        l2.observe_consequence(0.5, -0.01, 0.0);

        assert!(l2.last_consequence_score > 0.15);
        assert!(!l2.defensive_mode);
        assert_eq!(l2.negative_consequence_streak, 0);
        assert!(!l2.awaiting_consequence);
    }

    #[test]
    fn aligned_but_below_commit_threshold_does_not_nudge() {
        let mut l2 = L2MetaLayer::new();
        l2.enabled = true; // test requires L2 active
        l2.detector.window = 2;
        l2.detector.pred_threshold = 0.2;
        l2.detector.self_ref_threshold = 0.2;
        l2.detector.cooldown_steps = 0;
        l2.commit_threshold = 0.90;

        let mut active_code = BTreeMap::new();
        active_code.insert(
            "cognitive_rules".to_string(),
            "self-model bias damp rule".to_string(),
        );
        let state = SystemState {
            active_code,
            highest_attractor: "maintain coherent self-model omega dayan".to_string(),
            generative_base: Some("dayan_generative_base".to_string()),
            last_trajectory_summary: Some("coherent fixed-point candidate".to_string()),
            avg_prediction_error: 0.2,
            total_steps: 20,
        };

        let mut entered = None;
        for _ in 0..3 {
            let result = l2
                .step(
                    &state,
                    BTreeMap::new(),
                    BTreeMap::new(),
                    &RuleEffect::default(),
                )
                .expect("L2 step");
            if result.entered_fixed_point {
                entered = Some(result);
                break;
            }
        }

        let result = entered.expect("expected raw alignment to enter fixed-point");
        assert!(result.candidate_alignment_score > 0.82);
        assert!(result.candidate_score < l2.commit_threshold);
        assert!(result.in_fixed_point);
        assert!(result.dwell_steps >= 1);
        assert!(!result.modulation_committed);
        assert!(result.effect_nudge.is_none());
    }

    #[test]
    fn spectral_regime_does_not_bypass_combined_commit_safety_gates() {
        let mut layer = L2MetaLayer::new();
        layer.enabled = true;
        layer.commit_threshold = 0.90;

        let mut config = L2Config::with_window(8);
        config.history_discount_enabled = true;
        config.control_enabled = true;
        layer.spectral_gate = L2CognitiveGate::new(config);
        layer.spectral_reflector = L1SpectralReflector::new(8, 1e-4, 1);
        layer.configure_spectral_control(true);
        let _ = layer
            .spectral_gate
            .step(&layer.spectral_reflector, &[0.0; 8]);
        // The step adds one more 1.0 sample, yielding the same four-point
        // upward regime shift used by the spectral-gate regression test.
        layer.spectral_history = vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0];

        layer.controller.gate_state = control::L2GateState::Active;
        layer.controller.trust.alpha = 0.5;
        layer.controller.model_confidence = 0.0;
        layer.controller.residual_control_gain = 10.0;
        layer.controller.ema_error = 0.0;
        layer.commit_cooldown_remaining = 2;

        let state = SystemState {
            avg_prediction_error: 0.0,
            ..SystemState::default()
        };
        let result = layer
            .step(
                &state,
                BTreeMap::new(),
                BTreeMap::new(),
                &RuleEffect::default(),
            )
            .expect("L2 step");

        assert!(
            result
                .spectral_output
                .as_ref()
                .is_some_and(|output| output.regime_detected),
            "test must exercise the regime-detected path"
        );
        assert!(result.lyapunov_veto, "the predicted instability must veto");
        assert!(!result.modulation_committed);
        assert!(!layer.pending_policy.committed);
        assert_eq!(layer.commit_cooldown_remaining, 1);
    }
}