Skip to main content

omega_cognitive_kernel/api/
closed_loop.rs

1//! External closed-loop control session, directive types, and matrix benchmark.
2
3use super::{DefaultKernel, Kernel};
4use crate::audit::{AuditEvent, AuditLog};
5use crate::config::{
6    KernelConfig, L1RuntimeGate, LayerSwitches, LoopMode, LoopPreset, PatchDirection, PolicySchema,
7};
8use crate::error::OmegaError;
9use crate::l0::decision::ConstrainedDecisionMaker;
10use crate::l0::executor::{Executor, SandboxedExecutor};
11use crate::l0::observer::{MultiModalObserver, Observer};
12use crate::l2::L2Result;
13use crate::orchestrator::CooldownTracker;
14use crate::persist::ExternalLoopState;
15use alloc::collections::BTreeMap;
16use serde::{Deserialize, Serialize};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20/// Outcome reported for an externally executed step.
21pub enum ExternalOutcome {
22    /// The external action was accepted and improved the measured outcome.
23    AcceptedAndImproved,
24    /// The external action degraded the measured outcome.
25    Degraded,
26    /// The external action timed out or was skipped.
27    TimeoutOrSkipped,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
31/// External measurements supplied for one closed-loop step.
32pub struct StepTelemetry {
33    /// Identifier assigned to this external step.
34    pub step_id: u64,
35    /// Prediction error observed for this step.
36    pub prediction_error: f64,
37    /// Risk measured while executing this step.
38    pub observed_risk: f64,
39    /// Recent signal samples used by the controller when evaluating feedback.
40    pub signal_window: Vec<f64>,
41    /// Outcome of the preceding external step, when known.
42    pub last_outcome: Option<ExternalOutcome>,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46#[non_exhaustive]
47/// Single named policy-parameter update.
48pub struct ParamPatch {
49    /// Name used to identify this parameter or action.
50    pub name: String,
51    /// Parameter value before the proposed update.
52    pub old_value: f64,
53    /// Parameter value after the proposed update.
54    pub new_value: f64,
55    /// Difference between `new_value` and `old_value`.
56    pub delta: f64,
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize)]
60#[non_exhaustive]
61/// Serialized payload describing a proposed rule update.
62pub struct RulePatchPayload {
63    /// Identifier assigned to this proposed rule patch.
64    pub patch_id: String,
65    /// Whether to evaluate the patch in shadow mode without applying it.
66    pub shadow_only: bool,
67    /// Name of the rule targeted by the patch.
68    pub target_rule: String,
69    /// Proposed change to the target rule's weight.
70    pub delta_weight: f64,
71    #[serde(default, skip_serializing_if = "Vec::is_empty")]
72    /// Parameter changes bundled with this rule patch.
73    pub param_updates: Vec<ParamPatch>,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
77#[non_exhaustive]
78/// L2 policy and stability data supplied to the control plane.
79pub struct L2PriorPayload {
80    /// Whether the L2 controller detected a regime change.
81    pub regime_detected: bool,
82    /// Whether historical evidence is being discounted.
83    pub history_discount_enabled: bool,
84    /// Per-action prior biases used by the KL-regularized policy.
85    pub kl_prior_bias: Vec<f64>,
86    #[serde(default)]
87    /// Whether L2 is currently in a fixed-point regime.
88    pub in_fixed_point: bool,
89    #[serde(default)]
90    /// Current Lyapunov stability potential.
91    pub lyapunov_potential: f64,
92    #[serde(default)]
93    /// Whether the Lyapunov monitor vetoed the proposed update.
94    pub lyapunov_veto: bool,
95    #[serde(default)]
96    /// L2 learning-rate parameter.
97    pub alpha: f64,
98    #[serde(default)]
99    /// L2 regularization parameter.
100    pub beta: f64,
101    #[serde(default)]
102    /// Identifier of the expert selected by the L2 controller.
103    pub selected_expert: String,
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
107#[non_exhaustive]
108/// Control decisions returned to an external closed-loop host.
109pub struct ControlDirective {
110    /// Identifier of the step to which this directive applies.
111    pub step_id: u64,
112    /// L1 gate decision governing whether a proposed update may proceed.
113    pub l1_gate: L1RuntimeGate,
114    /// Whether the host should keep its current policy unchanged.
115    pub keep_steady: bool,
116    /// Optional L1 rule update proposed for the host.
117    pub rule_patch: Option<RulePatchPayload>,
118    /// Optional L2 prior and stability data for the host.
119    pub l2_prior: Option<L2PriorPayload>,
120    /// Checkpoint identifier requested for rollback, when present.
121    pub rollback_to_checkpoint: Option<String>,
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    /// UUID of the checkpoint associated with this directive, when present.
124    pub checkpoint_uuid: Option<String>,
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    /// UUID of the checkpoint to restore during rollback, when present.
127    pub rollback_checkpoint_uuid: Option<String>,
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    /// Current values of named active parameters, when supplied.
130    pub active_params: Option<BTreeMap<String, f64>>,
131}
132
133/// Interface for a kernel that accepts internal steps or external telemetry.
134pub trait ClosedLoopKernel {
135    /// Error returned when a step cannot be processed.
136    type Error;
137
138    /// Returns the layer switches currently used by the kernel.
139    fn switches(&self) -> LayerSwitches;
140
141    /// Runs one step using the kernel's internal world adapters.
142    fn step_internal(&mut self) -> std::result::Result<ControlDirective, Self::Error>;
143
144    /// Processes one externally measured step and returns the resulting control directive.
145    fn step_external(
146        &mut self,
147        telemetry: StepTelemetry,
148    ) -> std::result::Result<ControlDirective, Self::Error>;
149}
150/// Resolves the effective value from the supplied inputs.
151pub fn resolve_l1_gate(
152    switches: LayerSwitches,
153    blocked_by_l2: bool,
154    shadow_mode: bool,
155) -> L1RuntimeGate {
156    if !switches.l1 {
157        L1RuntimeGate::Disabled
158    } else if blocked_by_l2 {
159        L1RuntimeGate::BlockedByL2
160    } else if shadow_mode {
161        L1RuntimeGate::ShadowOnly
162    } else {
163        L1RuntimeGate::Active
164    }
165}
166
167fn build_l2_prior(
168    l2_result: &L2Result,
169    regime_detected: bool,
170    history_discount_enabled: bool,
171) -> L2PriorPayload {
172    L2PriorPayload {
173        regime_detected,
174        history_discount_enabled,
175        kl_prior_bias: l2_result.l2_policy.expert_probabilities.to_vec(),
176        in_fixed_point: l2_result.in_fixed_point,
177        lyapunov_potential: l2_result.lyapunov_potential,
178        lyapunov_veto: l2_result.lyapunov_veto,
179        alpha: l2_result.alpha,
180        beta: l2_result.beta,
181        selected_expert: l2_result.selected_expert.clone(),
182    }
183}
184/// Compute a bounded `[0.25, 1.0]` step-size damping factor from L2 stability
185/// metrics (`lyapunov_potential` and `alpha`). Higher potential dampens
186/// multi-parameter L1 steps to prevent overshoot; returns `1.0` when L2 is off.
187pub fn l2_step_damping(l2_prior: Option<&L2PriorPayload>) -> f64 {
188    match l2_prior {
189        Some(prior) => {
190            let pot = if prior.lyapunov_potential.is_finite() && prior.lyapunov_potential > 0.0 {
191                prior.lyapunov_potential
192            } else {
193                0.0
194            };
195            let alpha = if prior.alpha.is_finite() && prior.alpha > 0.0 {
196                prior.alpha
197            } else {
198                0.0
199            };
200            (1.0 / (1.0 + pot + 0.5 * alpha)).clamp(0.25, 1.0)
201        }
202        None => 1.0,
203    }
204}
205/// Stateful coordinator for running the kernel with internal or external telemetry.
206///
207/// The session retains layer switches, cooldown state, and external-step bookkeeping between
208/// calls. Create it from a kernel and a [`KernelConfig`], then invoke one of the
209/// [`ClosedLoopKernel`] step methods.
210///
211/// # Examples
212///
213/// ```
214/// use omega_cognitive_kernel::{
215///     api::{ClosedLoopKernel, ClosedLoopSession},
216///     persist::MemoryStateStore,
217///     Kernel, KernelConfig,
218/// };
219///
220/// fn main() -> omega_cognitive_kernel::Result<()> {
221///     let config = KernelConfig::default();
222///     let kernel = Kernel::open_with_store(Box::new(MemoryStateStore::new()))?;
223///     let mut session = ClosedLoopSession::from_kernel(kernel, &config);
224///     assert!(session.switches().l0);
225///
226///     let directive = session.step_internal().expect("internal step succeeds");
227///     assert!(directive.step_id > 0);
228///     assert!(directive.keep_steady);
229///     Ok(())
230/// }
231/// ```
232pub struct ClosedLoopSession<
233    O = MultiModalObserver,
234    D = ConstrainedDecisionMaker,
235    E = SandboxedExecutor,
236> where
237    O: Observer,
238    D: crate::l0::decision::DecisionMaker,
239    E: Executor,
240{
241    /// Kernel instance managed by this session.
242    pub kernel: Kernel<O, D, E>,
243    switches: LayerSwitches,
244    cooldown: CooldownTracker,
245    shadow_mode: bool,
246    error_threshold: f64,
247    max_risk: f64,
248    default_goal: String,
249    last_external_step_id: Option<u64>,
250    last_checkpoint_id: Option<String>,
251    last_checkpoint_uuid: Option<String>,
252    policy_schema: Option<PolicySchema>,
253    current_params: Option<BTreeMap<String, f64>>,
254    last_checkpoint_params: Option<BTreeMap<String, f64>>,
255}
256
257impl<O, D, E> ClosedLoopSession<O, D, E>
258where
259    O: Observer,
260    D: crate::l0::decision::DecisionMaker,
261    E: Executor,
262{
263    /// Creates a session from a kernel and configuration, restoring saved loop state when present.
264    pub fn from_kernel(kernel: Kernel<O, D, E>, config: &KernelConfig) -> Self {
265        let (
266            cooldown,
267            last_external_step_id,
268            last_checkpoint_id,
269            last_checkpoint_uuid,
270            mut current_params,
271            last_checkpoint_params,
272        ) = if let Some(ref ext) = kernel.external_loop_state {
273            (
274                ext.cooldown.clone(),
275                ext.last_external_step_id,
276                ext.last_checkpoint_id.clone(),
277                ext.last_checkpoint_uuid.clone(),
278                ext.current_params.clone(),
279                ext.last_checkpoint_params.clone(),
280            )
281        } else {
282            (
283                CooldownTracker::new(config.min_steps_between_patches),
284                None,
285                None,
286                None,
287                None,
288                None,
289            )
290        };
291        if current_params.is_none() {
292            if let Some(ref schema) = config.policy_schema {
293                current_params = Some(schema.initial_values());
294            }
295        }
296        Self {
297            kernel,
298            switches: config.effective_switches(),
299            cooldown,
300            shadow_mode: config.l1_shadow_mode,
301            error_threshold: config.error_threshold,
302            max_risk: config.max_risk,
303            default_goal: config
304                .default_goal
305                .clone()
306                .unwrap_or_else(|| String::from("closed_loop_step")),
307            last_external_step_id,
308            last_checkpoint_id,
309            last_checkpoint_uuid,
310            policy_schema: config.policy_schema.clone(),
311            current_params,
312            last_checkpoint_params,
313        }
314    }
315
316    /// Returns the cooldown tracker used to limit consecutive policy updates.
317    pub fn cooldown(&self) -> &CooldownTracker {
318        &self.cooldown
319    }
320}
321
322impl<O, D, E> ClosedLoopKernel for ClosedLoopSession<O, D, E>
323where
324    O: Observer,
325    D: crate::l0::decision::DecisionMaker,
326    E: Executor,
327{
328    type Error = OmegaError;
329
330    fn switches(&self) -> LayerSwitches {
331        self.switches
332    }
333
334    fn step_internal(&mut self) -> std::result::Result<ControlDirective, Self::Error> {
335        let mode = self
336            .switches
337            .validate()
338            .map_err(|e| OmegaError::Config(String::from(e)))?;
339        if mode != LoopMode::InternalWorld {
340            return Err(OmegaError::Config(String::from(
341                "step_internal requires L0 to be enabled in LayerSwitches",
342            )));
343        }
344
345        let res = self.kernel.inner.run_once(&self.default_goal)?;
346        let l1_gate = resolve_l1_gate(self.switches, res.l1_blocked_by_l2, self.shadow_mode);
347        let l2_prior = if self.switches.l2 {
348            Some(build_l2_prior(
349                &res.l2,
350                res.l1_blocked_by_l2,
351                self.kernel.inner.l2.enabled,
352            ))
353        } else {
354            None
355        };
356
357        Ok(ControlDirective {
358            step_id: self.kernel.inner.total_steps,
359            l1_gate,
360            keep_steady: l1_gate != L1RuntimeGate::Active,
361            rule_patch: None,
362            l2_prior,
363            rollback_to_checkpoint: None,
364            checkpoint_uuid: None,
365            rollback_checkpoint_uuid: None,
366            active_params: self.current_params.clone(),
367        })
368    }
369
370    fn step_external(
371        &mut self,
372        telemetry: StepTelemetry,
373    ) -> std::result::Result<ControlDirective, Self::Error> {
374        let mode = self
375            .switches
376            .validate()
377            .map_err(|e| OmegaError::Config(String::from(e)))?;
378        if mode != LoopMode::ExternalTelemetry {
379            return Err(OmegaError::Config(String::from(
380                "step_external requires L0 to be disabled in LayerSwitches",
381            )));
382        }
383
384        // Custom StateStore implementations persist snapshots only; they do not
385        // provide durable audit/checkpoint storage. Fail before mutating the loop.
386        if self.kernel.has_custom_state_store() {
387            return Err(OmegaError::Config(String::from(
388                "external telemetry requires file-backed audit and checkpoint storage; custom StateStore is unsupported",
389            )));
390        }
391
392        if let Some(prev) = self.last_external_step_id {
393            if telemetry.step_id <= prev {
394                let audit = AuditLog::beside_state(&self.kernel.state_path);
395                audit.append_with_privacy_and_max_bytes(
396                    AuditEvent::ExternalStepDuplicate {
397                        step_id: telemetry.step_id,
398                        last_step_id: prev,
399                    },
400                    self.kernel.redact_user_content,
401                    self.kernel.audit_max_bytes,
402                )?;
403                return Ok(ControlDirective {
404                    step_id: telemetry.step_id,
405                    l1_gate: resolve_l1_gate(self.switches, false, self.shadow_mode),
406                    keep_steady: true,
407                    rule_patch: None,
408                    l2_prior: None,
409                    rollback_to_checkpoint: None,
410                    checkpoint_uuid: None,
411                    rollback_checkpoint_uuid: None,
412                    active_params: self.current_params.clone(),
413                });
414            }
415        }
416        self.last_external_step_id = Some(telemetry.step_id);
417        self.cooldown.tick();
418
419        let mut rollback_to_checkpoint = None;
420        let mut rollback_checkpoint_uuid = None;
421        match telemetry.last_outcome {
422            Some(ExternalOutcome::AcceptedAndImproved) => {
423                self.cooldown.record_improved();
424                if self.switches.l2 {
425                    let reward = (1.0 - telemetry.prediction_error).clamp(0.0, 1.0);
426                    self.kernel.observe_l2_feedback(
427                        reward,
428                        telemetry.prediction_error,
429                        false,
430                        0.2,
431                        [0.5, 0.5],
432                    );
433                }
434            }
435            Some(ExternalOutcome::Degraded) => {
436                self.cooldown.record_rollback();
437                rollback_to_checkpoint = self.last_checkpoint_id.clone();
438                if let Some(ref prev_params) = self.last_checkpoint_params {
439                    self.current_params = Some(prev_params.clone());
440                }
441                rollback_checkpoint_uuid = self.last_checkpoint_uuid.clone();
442                if self.switches.l2 {
443                    self.kernel.observe_l2_feedback(
444                        0.0,
445                        telemetry.prediction_error,
446                        true,
447                        -0.35,
448                        [0.5, 0.5],
449                    );
450                }
451            }
452            Some(ExternalOutcome::TimeoutOrSkipped) | None => {}
453        }
454
455        let (blocked_by_l2, l2_prior) = if self.switches.l2 {
456            let l2_res = self.kernel.inner.step_l2_from_telemetry(
457                telemetry.step_id,
458                telemetry.prediction_error,
459                &self.default_goal,
460            )?;
461            let spectral_regime = l2_res
462                .spectral_output
463                .is_some_and(|output| output.regime_detected);
464            let blocked = l2_res.in_fixed_point
465                || l2_res.lyapunov_veto
466                || spectral_regime
467                || telemetry.prediction_error < self.error_threshold;
468            let prior = build_l2_prior(&l2_res, blocked, blocked);
469            (blocked, Some(prior))
470        } else {
471            (false, None)
472        };
473        let l1_gate = resolve_l1_gate(self.switches, blocked_by_l2, self.shadow_mode);
474
475        let can_emit_patch = matches!(l1_gate, L1RuntimeGate::Active | L1RuntimeGate::ShadowOnly)
476            && self.cooldown.can_patch(
477                telemetry.prediction_error,
478                self.error_threshold,
479                telemetry.observed_risk,
480                self.max_risk,
481            );
482        let mut created_checkpoint_uuid = None;
483        let rule_patch = if can_emit_patch {
484            if l1_gate == L1RuntimeGate::Active {
485                self.cooldown.mark_patched();
486                self.last_checkpoint_id = Some(format!("ckpt-{}", telemetry.step_id));
487                if self.kernel.autosave && self.kernel.auto_checkpoint_on_patch {
488                    let meta = self
489                        .kernel
490                        .checkpoint(&format!("external-step-{}", telemetry.step_id))?;
491                    let id_str = meta.id.to_string();
492                    created_checkpoint_uuid = Some(id_str.clone());
493                    self.last_checkpoint_uuid = Some(id_str);
494                }
495            }
496            let param_updates = if let Some(ref schema) = self.policy_schema {
497                if schema.validate().is_ok() {
498                    let excess = ((telemetry.prediction_error - self.error_threshold)
499                        / (1.0 - self.error_threshold).max(1e-6))
500                    .clamp(0.1, 1.0);
501                    let damping = l2_step_damping(l2_prior.as_ref());
502                    let base_params = self
503                        .current_params
504                        .clone()
505                        .unwrap_or_else(|| schema.initial_values());
506                    let mut next_params = base_params.clone();
507                    let mut updates = Vec::with_capacity(schema.params.len());
508                    for spec in &schema.params {
509                        let old_val = base_params.get(&spec.name).copied().unwrap_or(spec.initial);
510                        let sign = match spec.direction {
511                            PatchDirection::IncreaseOnError => 1.0,
512                            PatchDirection::DecreaseOnError => -1.0,
513                        };
514                        let new_val = (old_val + sign * spec.max_step * excess * damping)
515                            .clamp(spec.min, spec.max);
516                        next_params.insert(spec.name.clone(), new_val);
517                        updates.push(ParamPatch {
518                            name: spec.name.clone(),
519                            old_value: old_val,
520                            new_value: new_val,
521                            delta: new_val - old_val,
522                        });
523                    }
524                    if l1_gate == L1RuntimeGate::Active {
525                        self.last_checkpoint_params = Some(base_params);
526                        self.current_params = Some(next_params);
527                    }
528                    updates
529                } else {
530                    Vec::new()
531                }
532            } else {
533                Vec::new()
534            };
535            Some(RulePatchPayload {
536                patch_id: format!("patch-{}", telemetry.step_id),
537                shadow_only: l1_gate == L1RuntimeGate::ShadowOnly,
538                target_rule: String::from("external_policy_weight"),
539                delta_weight: -telemetry.prediction_error * 0.1,
540                param_updates,
541            })
542        } else {
543            None
544        };
545        let audit = AuditLog::beside_state(&self.kernel.state_path);
546        if let Some(ref ckpt_id) = rollback_to_checkpoint {
547            audit.append_with_privacy_and_max_bytes(
548                AuditEvent::ExternalRollback {
549                    step_id: telemetry.step_id,
550                    checkpoint_id: ckpt_id.clone(),
551                    consecutive_rollbacks: self.cooldown.consecutive_rollbacks(),
552                    next_cooldown: self.cooldown.current_cooldown(),
553                },
554                self.kernel.redact_user_content,
555                self.kernel.audit_max_bytes,
556            )?;
557        }
558        audit.append_with_privacy_and_max_bytes(
559            AuditEvent::ExternalStep {
560                step_id: telemetry.step_id,
561                prediction_error: telemetry.prediction_error,
562                observed_risk: telemetry.observed_risk,
563                l1_gate: format!("{l1_gate:?}"),
564                keep_steady: rule_patch.is_none(),
565                patch_id: rule_patch.as_ref().map(|p| p.patch_id.clone()),
566            },
567            self.kernel.redact_user_content,
568            self.kernel.audit_max_bytes,
569        )?;
570        self.kernel.external_loop_state = Some(ExternalLoopState {
571            last_external_step_id: self.last_external_step_id,
572            cooldown: self.cooldown.clone(),
573            last_checkpoint_id: self.last_checkpoint_id.clone(),
574            last_checkpoint_uuid: self.last_checkpoint_uuid.clone(),
575            current_params: self.current_params.clone(),
576            last_checkpoint_params: self.last_checkpoint_params.clone(),
577        });
578        if self.kernel.autosave {
579            self.kernel.save()?;
580        }
581
582        Ok(ControlDirective {
583            step_id: telemetry.step_id,
584            l1_gate,
585            keep_steady: rule_patch.is_none(),
586            rule_patch,
587            l2_prior,
588            rollback_to_checkpoint,
589            checkpoint_uuid: created_checkpoint_uuid,
590            rollback_checkpoint_uuid,
591            active_params: self.current_params.clone(),
592        })
593    }
594}
595
596#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
597#[serde(rename_all = "snake_case")]
598#[non_exhaustive]
599/// Identifies a supported loop benchmark scenario.
600pub enum LoopBenchmarkScenario {
601    /// Variant representing steady.
602    Steady,
603    /// Variant representing shift.
604    Shift,
605    /// Variant representing noisy.
606    Noisy,
607}
608
609#[derive(Debug, Clone, Serialize, Deserialize)]
610#[non_exhaustive]
611/// Data structure representing loop preset benchmark row.
612pub struct LoopPresetBenchmarkRow {
613    /// Preset for this value.
614    pub preset: String,
615    /// Mode for this value.
616    pub mode: String,
617    /// Number of steps completed by the run.
618    pub steps: u32,
619    /// Mean error for this value.
620    pub mean_error: f64,
621    /// Patches emitted for this value.
622    pub patches_emitted: u32,
623    /// Rollbacks for this value.
624    pub rollbacks: u32,
625    /// Number of steady.
626    pub steady_steps: u32,
627    /// Average step us.
628    pub avg_step_us: f64,
629}
630
631#[derive(Debug, Clone, Serialize, Deserialize)]
632#[non_exhaustive]
633/// Report of loop matrix benchmark.
634pub struct LoopMatrixBenchmarkReport {
635    /// Scenario for this value.
636    pub scenario: LoopBenchmarkScenario,
637    /// Steps per preset for this value.
638    pub steps_per_preset: u32,
639    /// Collection of rows.
640    pub rows: Vec<LoopPresetBenchmarkRow>,
641}
642
643fn scenario_telemetry(scenario: LoopBenchmarkScenario, step: u32, total: u32) -> StepTelemetry {
644    let idx = step as f64;
645    let third = (total / 3).max(1);
646    let (err, risk, outcome) = match scenario {
647        LoopBenchmarkScenario::Steady => (0.06 + 0.02 * (idx * 0.5).sin().abs(), 0.10, None),
648        LoopBenchmarkScenario::Shift => {
649            if step <= third {
650                (0.08, 0.10, None)
651            } else if step <= third.saturating_mul(2) {
652                let out = match step.cmp(&(third + 2)) {
653                    std::cmp::Ordering::Less => None,
654                    std::cmp::Ordering::Equal => Some(ExternalOutcome::Degraded),
655                    std::cmp::Ordering::Greater => Some(ExternalOutcome::AcceptedAndImproved),
656                };
657                (0.62, 0.22, out)
658            } else {
659                (0.12, 0.12, Some(ExternalOutcome::AcceptedAndImproved))
660            }
661        }
662        LoopBenchmarkScenario::Noisy => {
663            let err = if step.is_multiple_of(2) { 0.68 } else { 0.24 };
664            let risk = if step.is_multiple_of(5) { 0.80 } else { 0.25 };
665            let out = if step > 1 && step.is_multiple_of(3) {
666                Some(ExternalOutcome::Degraded)
667            } else {
668                None
669            };
670            (err, risk, out)
671        }
672    };
673    StepTelemetry {
674        step_id: u64::from(step),
675        prediction_error: err,
676        observed_risk: risk,
677        signal_window: vec![err],
678        last_outcome: outcome,
679    }
680}
681
682/// Runs run closed loop matrix benchmark and returns its result.
683pub fn run_closed_loop_matrix_benchmark(
684    scenario: LoopBenchmarkScenario,
685    steps: u32,
686) -> LoopMatrixBenchmarkReport {
687    let steps_clamped = steps.max(1);
688    let presets = [
689        ("deterministic", LoopPreset::Deterministic),
690        ("hot_patcher", LoopPreset::HotPatcher),
691        ("meta_guard", LoopPreset::MetaGuard),
692        ("fast_adapt", LoopPreset::FastAdapt),
693        ("steady_prior", LoopPreset::SteadyPrior),
694        ("control_plane", LoopPreset::ControlPlane),
695        ("full_kernel", LoopPreset::FullKernel),
696    ];
697
698    let base_dir = std::env::temp_dir().join(format!(
699        "omega-bench-loops-{}-{}",
700        std::process::id(),
701        std::time::SystemTime::now()
702            .duration_since(std::time::UNIX_EPOCH)
703            .map(|d| d.as_nanos())
704            .unwrap_or(0)
705    ));
706    let _ = std::fs::create_dir_all(&base_dir);
707
708    let mut rows = Vec::with_capacity(presets.len());
709    for (name, preset) in presets {
710        let cfg = KernelConfig::default().with_loop_preset(preset);
711        let mode = cfg
712            .effective_switches()
713            .validate()
714            .unwrap_or(LoopMode::InternalWorld);
715        let state_path = base_dir.join(format!("{name}.json"));
716        let mut kernel = DefaultKernel::with_state_path(state_path);
717        kernel.autosave = false;
718        kernel.dump_trajectory = false;
719        let mut session = ClosedLoopSession::from_kernel(kernel, &cfg);
720
721        let start = std::time::Instant::now();
722        let mut err_sum = 0.0;
723        let mut patches_emitted = 0u32;
724        let mut rollbacks = 0u32;
725        let mut steady_steps = 0u32;
726
727        for step in 1..=steps_clamped {
728            let directive = match mode {
729                LoopMode::InternalWorld => {
730                    let res = session.step_internal();
731                    err_sum += session.kernel.inner.l0.memory.cas.avg_prediction_error;
732                    res.ok()
733                }
734                LoopMode::ExternalTelemetry => {
735                    let tel = scenario_telemetry(scenario, step, steps_clamped);
736                    err_sum += tel.prediction_error;
737                    session.step_external(tel).ok()
738                }
739            };
740            if let Some(d) = directive {
741                if d.rule_patch.is_some() {
742                    patches_emitted += 1;
743                }
744                if d.rollback_to_checkpoint.is_some() {
745                    rollbacks += 1;
746                }
747                if d.keep_steady {
748                    steady_steps += 1;
749                }
750            }
751        }
752
753        let elapsed_us = start.elapsed().as_secs_f64() * 1_000_000.0;
754        rows.push(LoopPresetBenchmarkRow {
755            preset: String::from(name),
756            mode: match mode {
757                LoopMode::InternalWorld => String::from("internal"),
758                LoopMode::ExternalTelemetry => String::from("external"),
759            },
760            steps: steps_clamped,
761            mean_error: err_sum / f64::from(steps_clamped),
762            patches_emitted,
763            rollbacks,
764            steady_steps,
765            avg_step_us: elapsed_us / f64::from(steps_clamped),
766        });
767    }
768
769    let _ = std::fs::remove_dir_all(&base_dir);
770    LoopMatrixBenchmarkReport {
771        scenario,
772        steps_per_preset: steps_clamped,
773        rows,
774    }
775}