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
//! External closed-loop control session, directive types, and matrix benchmark.

use super::{DefaultKernel, Kernel};
use crate::audit::{AuditEvent, AuditLog};
use crate::config::{
    KernelConfig, L1RuntimeGate, LayerSwitches, LoopMode, LoopPreset, PatchDirection, PolicySchema,
};
use crate::error::OmegaError;
use crate::l0::decision::ConstrainedDecisionMaker;
use crate::l0::executor::{Executor, SandboxedExecutor};
use crate::l0::observer::{MultiModalObserver, Observer};
use crate::l2::L2Result;
use crate::orchestrator::CooldownTracker;
use crate::persist::ExternalLoopState;
use alloc::collections::BTreeMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
/// Outcome reported for an externally executed step.
pub enum ExternalOutcome {
    /// The external action was accepted and improved the measured outcome.
    AcceptedAndImproved,
    /// The external action degraded the measured outcome.
    Degraded,
    /// The external action timed out or was skipped.
    TimeoutOrSkipped,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// External measurements supplied for one closed-loop step.
pub struct StepTelemetry {
    /// Identifier assigned to this external step.
    pub step_id: u64,
    /// Prediction error observed for this step.
    pub prediction_error: f64,
    /// Risk measured while executing this step.
    pub observed_risk: f64,
    /// Recent signal samples used by the controller when evaluating feedback.
    pub signal_window: Vec<f64>,
    /// Outcome of the preceding external step, when known.
    pub last_outcome: Option<ExternalOutcome>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
/// Single named policy-parameter update.
pub struct ParamPatch {
    /// Name used to identify this parameter or action.
    pub name: String,
    /// Parameter value before the proposed update.
    pub old_value: f64,
    /// Parameter value after the proposed update.
    pub new_value: f64,
    /// Difference between `new_value` and `old_value`.
    pub delta: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
/// Serialized payload describing a proposed rule update.
pub struct RulePatchPayload {
    /// Identifier assigned to this proposed rule patch.
    pub patch_id: String,
    /// Whether to evaluate the patch in shadow mode without applying it.
    pub shadow_only: bool,
    /// Name of the rule targeted by the patch.
    pub target_rule: String,
    /// Proposed change to the target rule's weight.
    pub delta_weight: f64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Parameter changes bundled with this rule patch.
    pub param_updates: Vec<ParamPatch>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
/// L2 policy and stability data supplied to the control plane.
pub struct L2PriorPayload {
    /// Whether the L2 controller detected a regime change.
    pub regime_detected: bool,
    /// Whether historical evidence is being discounted.
    pub history_discount_enabled: bool,
    /// Per-action prior biases used by the KL-regularized policy.
    pub kl_prior_bias: Vec<f64>,
    #[serde(default)]
    /// Whether L2 is currently in a fixed-point regime.
    pub in_fixed_point: bool,
    #[serde(default)]
    /// Current Lyapunov stability potential.
    pub lyapunov_potential: f64,
    #[serde(default)]
    /// Whether the Lyapunov monitor vetoed the proposed update.
    pub lyapunov_veto: bool,
    #[serde(default)]
    /// L2 learning-rate parameter.
    pub alpha: f64,
    #[serde(default)]
    /// L2 regularization parameter.
    pub beta: f64,
    #[serde(default)]
    /// Identifier of the expert selected by the L2 controller.
    pub selected_expert: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
/// Control decisions returned to an external closed-loop host.
pub struct ControlDirective {
    /// Identifier of the step to which this directive applies.
    pub step_id: u64,
    /// L1 gate decision governing whether a proposed update may proceed.
    pub l1_gate: L1RuntimeGate,
    /// Whether the host should keep its current policy unchanged.
    pub keep_steady: bool,
    /// Optional L1 rule update proposed for the host.
    pub rule_patch: Option<RulePatchPayload>,
    /// Optional L2 prior and stability data for the host.
    pub l2_prior: Option<L2PriorPayload>,
    /// Checkpoint identifier requested for rollback, when present.
    pub rollback_to_checkpoint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// UUID of the checkpoint associated with this directive, when present.
    pub checkpoint_uuid: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// UUID of the checkpoint to restore during rollback, when present.
    pub rollback_checkpoint_uuid: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Current values of named active parameters, when supplied.
    pub active_params: Option<BTreeMap<String, f64>>,
}

/// Interface for a kernel that accepts internal steps or external telemetry.
pub trait ClosedLoopKernel {
    /// Error returned when a step cannot be processed.
    type Error;

    /// Returns the layer switches currently used by the kernel.
    fn switches(&self) -> LayerSwitches;

    /// Runs one step using the kernel's internal world adapters.
    fn step_internal(&mut self) -> std::result::Result<ControlDirective, Self::Error>;

    /// Processes one externally measured step and returns the resulting control directive.
    fn step_external(
        &mut self,
        telemetry: StepTelemetry,
    ) -> std::result::Result<ControlDirective, Self::Error>;
}
/// Resolves the effective value from the supplied inputs.
pub fn resolve_l1_gate(
    switches: LayerSwitches,
    blocked_by_l2: bool,
    shadow_mode: bool,
) -> L1RuntimeGate {
    if !switches.l1 {
        L1RuntimeGate::Disabled
    } else if blocked_by_l2 {
        L1RuntimeGate::BlockedByL2
    } else if shadow_mode {
        L1RuntimeGate::ShadowOnly
    } else {
        L1RuntimeGate::Active
    }
}

fn build_l2_prior(
    l2_result: &L2Result,
    regime_detected: bool,
    history_discount_enabled: bool,
) -> L2PriorPayload {
    L2PriorPayload {
        regime_detected,
        history_discount_enabled,
        kl_prior_bias: l2_result.l2_policy.expert_probabilities.to_vec(),
        in_fixed_point: l2_result.in_fixed_point,
        lyapunov_potential: l2_result.lyapunov_potential,
        lyapunov_veto: l2_result.lyapunov_veto,
        alpha: l2_result.alpha,
        beta: l2_result.beta,
        selected_expert: l2_result.selected_expert.clone(),
    }
}
/// Compute a bounded `[0.25, 1.0]` step-size damping factor from L2 stability
/// metrics (`lyapunov_potential` and `alpha`). Higher potential dampens
/// multi-parameter L1 steps to prevent overshoot; returns `1.0` when L2 is off.
pub fn l2_step_damping(l2_prior: Option<&L2PriorPayload>) -> f64 {
    match l2_prior {
        Some(prior) => {
            let pot = if prior.lyapunov_potential.is_finite() && prior.lyapunov_potential > 0.0 {
                prior.lyapunov_potential
            } else {
                0.0
            };
            let alpha = if prior.alpha.is_finite() && prior.alpha > 0.0 {
                prior.alpha
            } else {
                0.0
            };
            (1.0 / (1.0 + pot + 0.5 * alpha)).clamp(0.25, 1.0)
        }
        None => 1.0,
    }
}
/// Stateful coordinator for running the kernel with internal or external telemetry.
///
/// The session retains layer switches, cooldown state, and external-step bookkeeping between
/// calls. Create it from a kernel and a [`KernelConfig`], then invoke one of the
/// [`ClosedLoopKernel`] step methods.
///
/// # Examples
///
/// ```
/// use omega_cognitive_kernel::{
///     api::{ClosedLoopKernel, ClosedLoopSession},
///     persist::MemoryStateStore,
///     Kernel, KernelConfig,
/// };
///
/// fn main() -> omega_cognitive_kernel::Result<()> {
///     let config = KernelConfig::default();
///     let kernel = Kernel::open_with_store(Box::new(MemoryStateStore::new()))?;
///     let mut session = ClosedLoopSession::from_kernel(kernel, &config);
///     assert!(session.switches().l0);
///
///     let directive = session.step_internal().expect("internal step succeeds");
///     assert!(directive.step_id > 0);
///     assert!(directive.keep_steady);
///     Ok(())
/// }
/// ```
pub struct ClosedLoopSession<
    O = MultiModalObserver,
    D = ConstrainedDecisionMaker,
    E = SandboxedExecutor,
> where
    O: Observer,
    D: crate::l0::decision::DecisionMaker,
    E: Executor,
{
    /// Kernel instance managed by this session.
    pub kernel: Kernel<O, D, E>,
    switches: LayerSwitches,
    cooldown: CooldownTracker,
    shadow_mode: bool,
    error_threshold: f64,
    max_risk: f64,
    default_goal: String,
    last_external_step_id: Option<u64>,
    last_checkpoint_id: Option<String>,
    last_checkpoint_uuid: Option<String>,
    policy_schema: Option<PolicySchema>,
    current_params: Option<BTreeMap<String, f64>>,
    last_checkpoint_params: Option<BTreeMap<String, f64>>,
}

impl<O, D, E> ClosedLoopSession<O, D, E>
where
    O: Observer,
    D: crate::l0::decision::DecisionMaker,
    E: Executor,
{
    /// Creates a session from a kernel and configuration, restoring saved loop state when present.
    pub fn from_kernel(kernel: Kernel<O, D, E>, config: &KernelConfig) -> Self {
        let (
            cooldown,
            last_external_step_id,
            last_checkpoint_id,
            last_checkpoint_uuid,
            mut current_params,
            last_checkpoint_params,
        ) = if let Some(ref ext) = kernel.external_loop_state {
            (
                ext.cooldown.clone(),
                ext.last_external_step_id,
                ext.last_checkpoint_id.clone(),
                ext.last_checkpoint_uuid.clone(),
                ext.current_params.clone(),
                ext.last_checkpoint_params.clone(),
            )
        } else {
            (
                CooldownTracker::new(config.min_steps_between_patches),
                None,
                None,
                None,
                None,
                None,
            )
        };
        if current_params.is_none() {
            if let Some(ref schema) = config.policy_schema {
                current_params = Some(schema.initial_values());
            }
        }
        Self {
            kernel,
            switches: config.effective_switches(),
            cooldown,
            shadow_mode: config.l1_shadow_mode,
            error_threshold: config.error_threshold,
            max_risk: config.max_risk,
            default_goal: config
                .default_goal
                .clone()
                .unwrap_or_else(|| String::from("closed_loop_step")),
            last_external_step_id,
            last_checkpoint_id,
            last_checkpoint_uuid,
            policy_schema: config.policy_schema.clone(),
            current_params,
            last_checkpoint_params,
        }
    }

    /// Returns the cooldown tracker used to limit consecutive policy updates.
    pub fn cooldown(&self) -> &CooldownTracker {
        &self.cooldown
    }
}

impl<O, D, E> ClosedLoopKernel for ClosedLoopSession<O, D, E>
where
    O: Observer,
    D: crate::l0::decision::DecisionMaker,
    E: Executor,
{
    type Error = OmegaError;

    fn switches(&self) -> LayerSwitches {
        self.switches
    }

    fn step_internal(&mut self) -> std::result::Result<ControlDirective, Self::Error> {
        let mode = self
            .switches
            .validate()
            .map_err(|e| OmegaError::Config(String::from(e)))?;
        if mode != LoopMode::InternalWorld {
            return Err(OmegaError::Config(String::from(
                "step_internal requires L0 to be enabled in LayerSwitches",
            )));
        }

        let res = self.kernel.inner.run_once(&self.default_goal)?;
        let l1_gate = resolve_l1_gate(self.switches, res.l1_blocked_by_l2, self.shadow_mode);
        let l2_prior = if self.switches.l2 {
            Some(build_l2_prior(
                &res.l2,
                res.l1_blocked_by_l2,
                self.kernel.inner.l2.enabled,
            ))
        } else {
            None
        };

        Ok(ControlDirective {
            step_id: self.kernel.inner.total_steps,
            l1_gate,
            keep_steady: l1_gate != L1RuntimeGate::Active,
            rule_patch: None,
            l2_prior,
            rollback_to_checkpoint: None,
            checkpoint_uuid: None,
            rollback_checkpoint_uuid: None,
            active_params: self.current_params.clone(),
        })
    }

    fn step_external(
        &mut self,
        telemetry: StepTelemetry,
    ) -> std::result::Result<ControlDirective, Self::Error> {
        let mode = self
            .switches
            .validate()
            .map_err(|e| OmegaError::Config(String::from(e)))?;
        if mode != LoopMode::ExternalTelemetry {
            return Err(OmegaError::Config(String::from(
                "step_external requires L0 to be disabled in LayerSwitches",
            )));
        }

        // Custom StateStore implementations persist snapshots only; they do not
        // provide durable audit/checkpoint storage. Fail before mutating the loop.
        if self.kernel.has_custom_state_store() {
            return Err(OmegaError::Config(String::from(
                "external telemetry requires file-backed audit and checkpoint storage; custom StateStore is unsupported",
            )));
        }

        if let Some(prev) = self.last_external_step_id {
            if telemetry.step_id <= prev {
                let audit = AuditLog::beside_state(&self.kernel.state_path);
                audit.append_with_privacy_and_max_bytes(
                    AuditEvent::ExternalStepDuplicate {
                        step_id: telemetry.step_id,
                        last_step_id: prev,
                    },
                    self.kernel.redact_user_content,
                    self.kernel.audit_max_bytes,
                )?;
                return Ok(ControlDirective {
                    step_id: telemetry.step_id,
                    l1_gate: resolve_l1_gate(self.switches, false, self.shadow_mode),
                    keep_steady: true,
                    rule_patch: None,
                    l2_prior: None,
                    rollback_to_checkpoint: None,
                    checkpoint_uuid: None,
                    rollback_checkpoint_uuid: None,
                    active_params: self.current_params.clone(),
                });
            }
        }
        self.last_external_step_id = Some(telemetry.step_id);
        self.cooldown.tick();

        let mut rollback_to_checkpoint = None;
        let mut rollback_checkpoint_uuid = None;
        match telemetry.last_outcome {
            Some(ExternalOutcome::AcceptedAndImproved) => {
                self.cooldown.record_improved();
                if self.switches.l2 {
                    let reward = (1.0 - telemetry.prediction_error).clamp(0.0, 1.0);
                    self.kernel.observe_l2_feedback(
                        reward,
                        telemetry.prediction_error,
                        false,
                        0.2,
                        [0.5, 0.5],
                    );
                }
            }
            Some(ExternalOutcome::Degraded) => {
                self.cooldown.record_rollback();
                rollback_to_checkpoint = self.last_checkpoint_id.clone();
                if let Some(ref prev_params) = self.last_checkpoint_params {
                    self.current_params = Some(prev_params.clone());
                }
                rollback_checkpoint_uuid = self.last_checkpoint_uuid.clone();
                if self.switches.l2 {
                    self.kernel.observe_l2_feedback(
                        0.0,
                        telemetry.prediction_error,
                        true,
                        -0.35,
                        [0.5, 0.5],
                    );
                }
            }
            Some(ExternalOutcome::TimeoutOrSkipped) | None => {}
        }

        let (blocked_by_l2, l2_prior) = if self.switches.l2 {
            let l2_res = self.kernel.inner.step_l2_from_telemetry(
                telemetry.step_id,
                telemetry.prediction_error,
                &self.default_goal,
            )?;
            let spectral_regime = l2_res
                .spectral_output
                .is_some_and(|output| output.regime_detected);
            let blocked = l2_res.in_fixed_point
                || l2_res.lyapunov_veto
                || spectral_regime
                || telemetry.prediction_error < self.error_threshold;
            let prior = build_l2_prior(&l2_res, blocked, blocked);
            (blocked, Some(prior))
        } else {
            (false, None)
        };
        let l1_gate = resolve_l1_gate(self.switches, blocked_by_l2, self.shadow_mode);

        let can_emit_patch = matches!(l1_gate, L1RuntimeGate::Active | L1RuntimeGate::ShadowOnly)
            && self.cooldown.can_patch(
                telemetry.prediction_error,
                self.error_threshold,
                telemetry.observed_risk,
                self.max_risk,
            );
        let mut created_checkpoint_uuid = None;
        let rule_patch = if can_emit_patch {
            if l1_gate == L1RuntimeGate::Active {
                self.cooldown.mark_patched();
                self.last_checkpoint_id = Some(format!("ckpt-{}", telemetry.step_id));
                if self.kernel.autosave && self.kernel.auto_checkpoint_on_patch {
                    let meta = self
                        .kernel
                        .checkpoint(&format!("external-step-{}", telemetry.step_id))?;
                    let id_str = meta.id.to_string();
                    created_checkpoint_uuid = Some(id_str.clone());
                    self.last_checkpoint_uuid = Some(id_str);
                }
            }
            let param_updates = if let Some(ref schema) = self.policy_schema {
                if schema.validate().is_ok() {
                    let excess = ((telemetry.prediction_error - self.error_threshold)
                        / (1.0 - self.error_threshold).max(1e-6))
                    .clamp(0.1, 1.0);
                    let damping = l2_step_damping(l2_prior.as_ref());
                    let base_params = self
                        .current_params
                        .clone()
                        .unwrap_or_else(|| schema.initial_values());
                    let mut next_params = base_params.clone();
                    let mut updates = Vec::with_capacity(schema.params.len());
                    for spec in &schema.params {
                        let old_val = base_params.get(&spec.name).copied().unwrap_or(spec.initial);
                        let sign = match spec.direction {
                            PatchDirection::IncreaseOnError => 1.0,
                            PatchDirection::DecreaseOnError => -1.0,
                        };
                        let new_val = (old_val + sign * spec.max_step * excess * damping)
                            .clamp(spec.min, spec.max);
                        next_params.insert(spec.name.clone(), new_val);
                        updates.push(ParamPatch {
                            name: spec.name.clone(),
                            old_value: old_val,
                            new_value: new_val,
                            delta: new_val - old_val,
                        });
                    }
                    if l1_gate == L1RuntimeGate::Active {
                        self.last_checkpoint_params = Some(base_params);
                        self.current_params = Some(next_params);
                    }
                    updates
                } else {
                    Vec::new()
                }
            } else {
                Vec::new()
            };
            Some(RulePatchPayload {
                patch_id: format!("patch-{}", telemetry.step_id),
                shadow_only: l1_gate == L1RuntimeGate::ShadowOnly,
                target_rule: String::from("external_policy_weight"),
                delta_weight: -telemetry.prediction_error * 0.1,
                param_updates,
            })
        } else {
            None
        };
        let audit = AuditLog::beside_state(&self.kernel.state_path);
        if let Some(ref ckpt_id) = rollback_to_checkpoint {
            audit.append_with_privacy_and_max_bytes(
                AuditEvent::ExternalRollback {
                    step_id: telemetry.step_id,
                    checkpoint_id: ckpt_id.clone(),
                    consecutive_rollbacks: self.cooldown.consecutive_rollbacks(),
                    next_cooldown: self.cooldown.current_cooldown(),
                },
                self.kernel.redact_user_content,
                self.kernel.audit_max_bytes,
            )?;
        }
        audit.append_with_privacy_and_max_bytes(
            AuditEvent::ExternalStep {
                step_id: telemetry.step_id,
                prediction_error: telemetry.prediction_error,
                observed_risk: telemetry.observed_risk,
                l1_gate: format!("{l1_gate:?}"),
                keep_steady: rule_patch.is_none(),
                patch_id: rule_patch.as_ref().map(|p| p.patch_id.clone()),
            },
            self.kernel.redact_user_content,
            self.kernel.audit_max_bytes,
        )?;
        self.kernel.external_loop_state = Some(ExternalLoopState {
            last_external_step_id: self.last_external_step_id,
            cooldown: self.cooldown.clone(),
            last_checkpoint_id: self.last_checkpoint_id.clone(),
            last_checkpoint_uuid: self.last_checkpoint_uuid.clone(),
            current_params: self.current_params.clone(),
            last_checkpoint_params: self.last_checkpoint_params.clone(),
        });
        if self.kernel.autosave {
            self.kernel.save()?;
        }

        Ok(ControlDirective {
            step_id: telemetry.step_id,
            l1_gate,
            keep_steady: rule_patch.is_none(),
            rule_patch,
            l2_prior,
            rollback_to_checkpoint,
            checkpoint_uuid: created_checkpoint_uuid,
            rollback_checkpoint_uuid,
            active_params: self.current_params.clone(),
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// Identifies a supported loop benchmark scenario.
pub enum LoopBenchmarkScenario {
    /// Variant representing steady.
    Steady,
    /// Variant representing shift.
    Shift,
    /// Variant representing noisy.
    Noisy,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
/// Data structure representing loop preset benchmark row.
pub struct LoopPresetBenchmarkRow {
    /// Preset for this value.
    pub preset: String,
    /// Mode for this value.
    pub mode: String,
    /// Number of steps completed by the run.
    pub steps: u32,
    /// Mean error for this value.
    pub mean_error: f64,
    /// Patches emitted for this value.
    pub patches_emitted: u32,
    /// Rollbacks for this value.
    pub rollbacks: u32,
    /// Number of steady.
    pub steady_steps: u32,
    /// Average step us.
    pub avg_step_us: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
/// Report of loop matrix benchmark.
pub struct LoopMatrixBenchmarkReport {
    /// Scenario for this value.
    pub scenario: LoopBenchmarkScenario,
    /// Steps per preset for this value.
    pub steps_per_preset: u32,
    /// Collection of rows.
    pub rows: Vec<LoopPresetBenchmarkRow>,
}

fn scenario_telemetry(scenario: LoopBenchmarkScenario, step: u32, total: u32) -> StepTelemetry {
    let idx = step as f64;
    let third = (total / 3).max(1);
    let (err, risk, outcome) = match scenario {
        LoopBenchmarkScenario::Steady => (0.06 + 0.02 * (idx * 0.5).sin().abs(), 0.10, None),
        LoopBenchmarkScenario::Shift => {
            if step <= third {
                (0.08, 0.10, None)
            } else if step <= third.saturating_mul(2) {
                let out = match step.cmp(&(third + 2)) {
                    std::cmp::Ordering::Less => None,
                    std::cmp::Ordering::Equal => Some(ExternalOutcome::Degraded),
                    std::cmp::Ordering::Greater => Some(ExternalOutcome::AcceptedAndImproved),
                };
                (0.62, 0.22, out)
            } else {
                (0.12, 0.12, Some(ExternalOutcome::AcceptedAndImproved))
            }
        }
        LoopBenchmarkScenario::Noisy => {
            let err = if step.is_multiple_of(2) { 0.68 } else { 0.24 };
            let risk = if step.is_multiple_of(5) { 0.80 } else { 0.25 };
            let out = if step > 1 && step.is_multiple_of(3) {
                Some(ExternalOutcome::Degraded)
            } else {
                None
            };
            (err, risk, out)
        }
    };
    StepTelemetry {
        step_id: u64::from(step),
        prediction_error: err,
        observed_risk: risk,
        signal_window: vec![err],
        last_outcome: outcome,
    }
}

/// Runs run closed loop matrix benchmark and returns its result.
pub fn run_closed_loop_matrix_benchmark(
    scenario: LoopBenchmarkScenario,
    steps: u32,
) -> LoopMatrixBenchmarkReport {
    let steps_clamped = steps.max(1);
    let presets = [
        ("deterministic", LoopPreset::Deterministic),
        ("hot_patcher", LoopPreset::HotPatcher),
        ("meta_guard", LoopPreset::MetaGuard),
        ("fast_adapt", LoopPreset::FastAdapt),
        ("steady_prior", LoopPreset::SteadyPrior),
        ("control_plane", LoopPreset::ControlPlane),
        ("full_kernel", LoopPreset::FullKernel),
    ];

    let base_dir = std::env::temp_dir().join(format!(
        "omega-bench-loops-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::create_dir_all(&base_dir);

    let mut rows = Vec::with_capacity(presets.len());
    for (name, preset) in presets {
        let cfg = KernelConfig::default().with_loop_preset(preset);
        let mode = cfg
            .effective_switches()
            .validate()
            .unwrap_or(LoopMode::InternalWorld);
        let state_path = base_dir.join(format!("{name}.json"));
        let mut kernel = DefaultKernel::with_state_path(state_path);
        kernel.autosave = false;
        kernel.dump_trajectory = false;
        let mut session = ClosedLoopSession::from_kernel(kernel, &cfg);

        let start = std::time::Instant::now();
        let mut err_sum = 0.0;
        let mut patches_emitted = 0u32;
        let mut rollbacks = 0u32;
        let mut steady_steps = 0u32;

        for step in 1..=steps_clamped {
            let directive = match mode {
                LoopMode::InternalWorld => {
                    let res = session.step_internal();
                    err_sum += session.kernel.inner.l0.memory.cas.avg_prediction_error;
                    res.ok()
                }
                LoopMode::ExternalTelemetry => {
                    let tel = scenario_telemetry(scenario, step, steps_clamped);
                    err_sum += tel.prediction_error;
                    session.step_external(tel).ok()
                }
            };
            if let Some(d) = directive {
                if d.rule_patch.is_some() {
                    patches_emitted += 1;
                }
                if d.rollback_to_checkpoint.is_some() {
                    rollbacks += 1;
                }
                if d.keep_steady {
                    steady_steps += 1;
                }
            }
        }

        let elapsed_us = start.elapsed().as_secs_f64() * 1_000_000.0;
        rows.push(LoopPresetBenchmarkRow {
            preset: String::from(name),
            mode: match mode {
                LoopMode::InternalWorld => String::from("internal"),
                LoopMode::ExternalTelemetry => String::from("external"),
            },
            steps: steps_clamped,
            mean_error: err_sum / f64::from(steps_clamped),
            patches_emitted,
            rollbacks,
            steady_steps,
            avg_step_us: elapsed_us / f64::from(steps_clamped),
        });
    }

    let _ = std::fs::remove_dir_all(&base_dir);
    LoopMatrixBenchmarkReport {
        scenario,
        steps_per_preset: steps_clamped,
        rows,
    }
}