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
//! Operational metrics snapshot and Prometheus text format export.
use serde::Serialize;
/// Read-only, in-memory operational metrics for export to monitoring systems.
///
/// The snapshot contains only counts, scalar gauges, and gate state. It does
/// not include user goals, state paths, or other persisted content, and taking
/// it performs no I/O or memory sampling. Counts named `retained_*` describe
/// bounded in-memory history rather than lifetime totals.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct KernelMetricsSnapshot {
/// Total number of kernel steps completed in the current persisted state.
pub steps_total: u64,
/// Number of cases currently resident in case memory.
pub cases_in_memory: usize,
/// Configured capacity of case memory.
pub case_memory_capacity: usize,
/// Number of strategies currently resident in strategy memory.
pub strategies_in_memory: usize,
/// Number of active cognitive modules.
pub active_modules: usize,
/// Number of patches retained in the bounded L1 patch history.
pub retained_patch_history: usize,
/// Current average prediction error.
pub average_prediction_error: f64,
/// Current adaptation score.
pub adaptation_score: f64,
/// Current error-damping factor.
pub error_damping: f64,
/// Current exploration bonus.
pub explore_bonus: f64,
/// Current risk tolerance.
pub risk_tolerance: f64,
/// Maximum risk permitted by the active policy.
pub max_risk: f64,
/// Whether L1 self-modification is enabled.
pub self_modify_enabled: bool,
/// Whether the L2 meta-controller is enabled.
pub l2_enabled: bool,
/// Whether L2 is currently in a fixed-point regime.
pub l2_in_fixed_point: bool,
/// Whether L2 is operating in defensive mode.
pub l2_defensive_mode: bool,
/// Current L2 gate state.
pub l2_gate_state: crate::l2::control::L2GateState,
/// Number of steps spent in the current L2 regime or arm.
pub l2_dwell_steps: u64,
/// Most recent L2 alignment score.
pub l2_alignment_score: f64,
/// L2 policy learning-rate parameter.
pub l2_alpha: f64,
/// L2 policy regularization parameter.
pub l2_beta: f64,
/// Current Lyapunov stability potential.
pub l2_lyapunov_potential: f64,
/// Residual used by the L2 Dayan stability calculation.
pub l2_dayan_residual: f64,
/// Whether the stability monitor vetoed an L2 change.
pub l2_lyapunov_veto: bool,
/// Whether the most recent L2 lookup hit the meta-cache.
pub l2_meta_cache_hit: bool,
/// Number of entries currently held by the L2 meta-cache.
pub l2_meta_cache_entries: usize,
/// Steps remaining before another L2 policy commit is allowed.
pub l2_commit_cooldown_remaining: u64,
/// Number of consecutive negative consequences observed by L2.
pub l2_negative_consequence_streak: u32,
/// Most recent consequence score observed by L2.
pub l2_last_consequence_score: f64,
}
#[cfg(feature = "std")]
impl KernelMetricsSnapshot {
/// Formats every field in this snapshot as Prometheus text exposition.
///
/// The output is a single, unlabeled sample per field. `steps_total` is a
/// counter; all other values are gauges because they describe current
/// state, bounded resident counts, or the most recently observed scores.
/// Boolean fields are encoded as `0` or `1`. The L2 gate state is encoded
/// as `0` for dormant and `1` for active. Non-finite floating-point values
/// are exported as `0` so that the exposition never contains `NaN` or an
/// infinity token. HELP strings are escaped according to the Prometheus
/// text format. This exporter adds no metrics beyond fields already held
/// by the snapshot and performs no I/O.
///
/// This method is available only with the crate's `std` feature, like the
/// product-facing `Kernel` API. It does not change the `no_std` build or
/// add an allocation requirement to that path.
///
/// # Examples
///
/// ```
/// use omega_cognitive_kernel::{persist::MemoryStateStore, Kernel};
///
/// fn main() -> omega_cognitive_kernel::Result<()> {
/// let kernel = Kernel::open_with_store(Box::new(MemoryStateStore::new()))?;
/// let text = kernel.metrics_snapshot().to_prometheus_text();
/// assert!(text.contains("# TYPE omega_kernel_steps_total counter\n"));
/// assert!(text.contains("omega_kernel_steps_total 0\n"));
/// assert!(!text.contains("NaN"));
/// assert!(!text.contains("Inf"));
/// Ok(())
/// }
/// ```
pub fn to_prometheus_text(&self) -> String {
use crate::l2::control::L2GateState;
let mut output = String::new();
write_prometheus_metric(
&mut output,
"omega_kernel_steps_total",
"counter",
"Total number of kernel steps completed in the current persisted state.",
self.steps_total,
);
write_prometheus_metric(
&mut output,
"omega_kernel_cases_in_memory",
"gauge",
"Number of cases currently resident in case memory.",
self.cases_in_memory,
);
write_prometheus_metric(
&mut output,
"omega_kernel_case_memory_capacity",
"gauge",
"Configured capacity of case memory, in cases.",
self.case_memory_capacity,
);
write_prometheus_metric(
&mut output,
"omega_kernel_strategies_in_memory",
"gauge",
"Number of strategies currently resident in strategy memory.",
self.strategies_in_memory,
);
write_prometheus_metric(
&mut output,
"omega_kernel_active_modules",
"gauge",
"Number of active cognitive modules.",
self.active_modules,
);
write_prometheus_metric(
&mut output,
"omega_kernel_retained_patch_history",
"gauge",
"Number of patches retained in the bounded L1 patch history.",
self.retained_patch_history,
);
write_prometheus_metric(
&mut output,
"omega_kernel_average_prediction_error",
"gauge",
"Current average prediction error.",
finite_prometheus_value(self.average_prediction_error),
);
write_prometheus_metric(
&mut output,
"omega_kernel_adaptation_score",
"gauge",
"Current adaptation score.",
finite_prometheus_value(self.adaptation_score),
);
write_prometheus_metric(
&mut output,
"omega_kernel_error_damping",
"gauge",
"Current error-damping factor.",
finite_prometheus_value(self.error_damping),
);
write_prometheus_metric(
&mut output,
"omega_kernel_explore_bonus",
"gauge",
"Current exploration bonus.",
finite_prometheus_value(self.explore_bonus),
);
write_prometheus_metric(
&mut output,
"omega_kernel_risk_tolerance",
"gauge",
"Current risk tolerance.",
finite_prometheus_value(self.risk_tolerance),
);
write_prometheus_metric(
&mut output,
"omega_kernel_max_risk",
"gauge",
"Maximum risk permitted by the active policy.",
finite_prometheus_value(self.max_risk),
);
write_prometheus_metric(
&mut output,
"omega_kernel_self_modify_enabled",
"gauge",
"Whether L1 self-modification is enabled, encoded as 0 or 1.",
u8::from(self.self_modify_enabled),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_enabled",
"gauge",
"Whether the L2 meta-controller is enabled, encoded as 0 or 1.",
u8::from(self.l2_enabled),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_in_fixed_point",
"gauge",
"Whether L2 is in a fixed-point regime, encoded as 0 or 1.",
u8::from(self.l2_in_fixed_point),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_defensive_mode",
"gauge",
"Whether L2 is in defensive mode, encoded as 0 or 1.",
u8::from(self.l2_defensive_mode),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_gate_state",
"gauge",
"L2 gate state: 0 is dormant and 1 is active.",
match self.l2_gate_state {
L2GateState::Dormant => 0,
L2GateState::Active => 1,
},
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_dwell_steps",
"gauge",
"Number of steps spent in the current L2 regime or arm.",
self.l2_dwell_steps,
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_alignment_score",
"gauge",
"Most recent L2 alignment score.",
finite_prometheus_value(self.l2_alignment_score),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_alpha",
"gauge",
"L2 policy learning-rate parameter.",
finite_prometheus_value(self.l2_alpha),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_beta",
"gauge",
"L2 policy regularization parameter.",
finite_prometheus_value(self.l2_beta),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_lyapunov_potential",
"gauge",
"Current Lyapunov stability potential.",
finite_prometheus_value(self.l2_lyapunov_potential),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_dayan_residual",
"gauge",
"Residual used by the L2 Dayan stability calculation.",
finite_prometheus_value(self.l2_dayan_residual),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_lyapunov_veto",
"gauge",
"Whether the stability monitor vetoed an L2 change, encoded as 0 or 1.",
u8::from(self.l2_lyapunov_veto),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_meta_cache_hit",
"gauge",
"Whether the most recent L2 lookup hit the meta-cache, encoded as 0 or 1.",
u8::from(self.l2_meta_cache_hit),
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_meta_cache_entries",
"gauge",
"Number of entries currently held by the L2 meta-cache.",
self.l2_meta_cache_entries,
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_commit_cooldown_remaining",
"gauge",
"Steps remaining before another L2 policy commit is allowed.",
self.l2_commit_cooldown_remaining,
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_negative_consequence_streak",
"gauge",
"Number of consecutive negative consequences observed by L2.",
self.l2_negative_consequence_streak,
);
write_prometheus_metric(
&mut output,
"omega_kernel_l2_last_consequence_score",
"gauge",
"Most recent consequence score observed by L2.",
finite_prometheus_value(self.l2_last_consequence_score),
);
output
}
}
#[cfg(feature = "std")]
fn finite_prometheus_value(value: f64) -> f64 {
if value.is_finite() {
value
} else {
0.0
}
}
#[cfg(feature = "std")]
fn write_prometheus_metric(
output: &mut String,
name: &str,
metric_type: &str,
help: &str,
value: impl core::fmt::Display,
) {
use core::fmt::Write as _;
let _ = write!(output, "# HELP {name} ");
for character in help.chars() {
match character {
'\\' => output.push_str("\\\\"),
'\n' => output.push_str("\\n"),
character => output.push(character),
}
}
output.push('\n');
let _ = writeln!(output, "# TYPE {name} {metric_type}");
let _ = writeln!(output, "{name} {value}");
}
#[cfg(test)]
mod prometheus_export_tests {
use super::{finite_prometheus_value, write_prometheus_metric};
#[test]
fn non_finite_samples_are_replaced_with_zero() {
assert_eq!(finite_prometheus_value(f64::NAN), 0.0);
assert_eq!(finite_prometheus_value(f64::INFINITY), 0.0);
assert_eq!(finite_prometheus_value(f64::NEG_INFINITY), 0.0);
assert_eq!(finite_prometheus_value(1.25), 1.25);
}
#[test]
fn help_text_escapes_backslashes_and_newlines() {
let mut output = String::new();
write_prometheus_metric(
&mut output,
"test_metric",
"gauge",
"slash\\backslash\nline",
7,
);
assert_eq!(
output,
"# HELP test_metric slash\\\\backslash\\nline\n# TYPE test_metric gauge\ntest_metric 7\n"
);
}
}