omega-cognitive-kernel 1.0.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
#[allow(unused_imports)]
use crate::prelude::*;

use alloc::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
/// UTC timestamp with stable RFC 3339 serialization and a no_std epoch fallback.
///
/// `now()` reads the system clock with the `std` feature and returns [`Self::UNIX_EPOCH`] in a
/// `no_std` build, where no clock source is available.
///
/// # Examples
///
/// ```
/// use omega_cognitive_kernel::UtcTimestamp;
///
/// let epoch = match UtcTimestamp::from_rfc3339("1970-01-01T00:00:00Z") {
///     Ok(epoch) => epoch,
///     Err(error) => panic!("valid RFC 3339 timestamp should parse: {error}"),
/// };
/// assert_eq!(epoch, UtcTimestamp::UNIX_EPOCH);
/// assert_eq!(epoch.timestamp(), 0);
/// assert_eq!(epoch.timestamp_millis(), 0);
/// ```
pub struct UtcTimestamp(chrono::DateTime<chrono::Utc>);

impl UtcTimestamp {
    /// Timestamp at the Unix epoch (`1970-01-01T00:00:00Z`).
    pub const UNIX_EPOCH: Self = Self(chrono::DateTime::<chrono::Utc>::UNIX_EPOCH);

    /// Returns the current UTC time.
    #[cfg(feature = "std")]
    pub fn now() -> Self {
        Self(chrono::Utc::now())
    }

    /// Returns [`Self::UNIX_EPOCH`] because a `no_std` build has no clock source.
    #[cfg(not(feature = "std"))]
    pub fn now() -> Self {
        Self::UNIX_EPOCH
    }

    /// Formats the timestamp as an RFC 3339 string.
    pub fn to_rfc3339(&self) -> alloc::string::String {
        self.0.to_rfc3339()
    }

    /// Parses an RFC 3339 string and normalizes the result to UTC.
    pub fn from_rfc3339(s: &str) -> Result<Self, alloc::string::String> {
        chrono::DateTime::parse_from_rfc3339(s)
            .map(|dt| Self(dt.with_timezone(&chrono::Utc)))
            .map_err(|e| alloc::format!("{}", e))
    }

    /// Returns whole seconds since the Unix epoch.
    pub fn timestamp(&self) -> i64 {
        self.0.timestamp()
    }

    /// Returns whole milliseconds since the Unix epoch.
    pub fn timestamp_millis(&self) -> i64 {
        self.0.timestamp_millis()
    }
}
impl Default for UtcTimestamp {
    fn default() -> Self {
        Self::UNIX_EPOCH
    }
}

impl core::fmt::Debug for UtcTimestamp {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("UtcTimestamp")
            .field(&self.to_rfc3339())
            .finish()
    }
}

impl core::fmt::Display for UtcTimestamp {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.to_rfc3339())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Kind of input represented by an observation.
pub enum Modality {
    /// Textual input.
    Text,
    /// Image input.
    Image,
    /// Audio input.
    Audio,
    /// Structured data input.
    Structured,
    /// Internal kernel-generated input.
    Internal,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Input captured by an observer, with its modality, confidence, and source.
pub struct Observation {
    /// UTC time when the observation was captured.
    pub timestamp: UtcTimestamp,
    /// Kind of input contained in `content`.
    pub modality: Modality,
    /// Observed content encoded as a JSON value.
    pub content: serde_json::Value,
    /// Observer-assigned confidence in the observation.
    pub confidence: f64,
    /// Name or identifier of the observation source.
    pub source: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Predicted value together with its uncertainty and forecast horizon.
pub struct Prediction {
    /// Predicted value expected at the requested horizon.
    pub expected: serde_json::Value,
    /// Uncertainty associated with the prediction.
    pub uncertainty: f64,
    /// Forecast horizon in seconds.
    pub horizon_secs: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Goal and priority supplied to the decision layer, including memory-derived biases.
pub struct Intent {
    /// High-level goal to pursue.
    pub goal: String,
    /// Relative priority assigned to the goal.
    pub priority: f64,
    /// Mapping of bias from memory.
    pub bias_from_memory: BTreeMap<String, f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Action proposed by the decision layer, with parameters and constraint-check status.
pub struct Action {
    /// Name used to identify this parameter or action.
    pub name: String,
    /// Named parameters supplied to the action.
    pub params: BTreeMap<String, serde_json::Value>,
    /// Whether configured constraint checks were performed for this action.
    pub constraints_checked: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
/// Configuration for bandit.
pub struct BanditConfig {
    /// Minimum decisions to keep an arm before considering a switch.
    pub min_dwell_steps: u64,
    /// Required UCB advantage over the incumbent arm.
    pub switch_margin: f64,
    /// Multiplier for rollback/safety-degradation signals in the UCB reward.
    pub rollback_penalty: f64,
    /// Cost charged to the destination arm when changing arms.
    pub switch_cost: f64,
}

impl Default for BanditConfig {
    fn default() -> Self {
        Self {
            min_dwell_steps: 3,
            switch_margin: 0.05,
            rollback_penalty: 0.35,
            switch_cost: 0.02,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
/// Reason recorded when the L2 bandit controller selects or retains an arm.
pub enum L2DecisionReason {
    /// Initial exploration before an arm has an established reward estimate.
    InitialExplore,
    /// The arm with the strongest current estimate was selected.
    Exploit,
    /// An arm was selected to explore an alternative.
    Explore,
    /// Selection changed from the incumbent arm to another arm.
    Switched,
    /// The incumbent arm was retained because its minimum dwell period has not elapsed.
    DwellHold,
    /// The incumbent arm was retained because the candidate did not clear the switch margin.
    MarginHold,
    /// A safety-related condition overrode the ordinary bandit choice.
    SafetyOverride,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Record of the L2 bandit's selected arm, candidate, scores, and switching constraints.
pub struct L2DecisionRecord {
    /// Index of the arm ultimately selected.
    pub selected_arm: usize,
    /// Name of the bias or action associated with the selected arm.
    pub selected_bias: String,
    /// Index of the arm proposed by the candidate-selection policy.
    pub candidate_arm: usize,
    /// Estimated mean reward for the selected arm.
    pub mean_reward: f64,
    /// Multiplicative exploration term of the selected arm.
    pub exploration_bonus: f64,
    /// UCB score of the selected arm; null while that arm is still unexplored.
    pub ucb_score: Option<f64>,
    /// UCB score of the candidate arm, when available.
    pub candidate_ucb_score: Option<f64>,
    /// UCB score of the incumbent arm, when available.
    pub current_ucb_score: Option<f64>,
    /// Reason the selected arm was chosen or retained.
    pub reason: L2DecisionReason,
    /// Number of steps spent in the current regime or arm.
    pub dwell_steps: u64,
    /// Whether the minimum-dwell rule prevented a switch.
    pub dwell_suppressed: bool,
    /// Whether the switch-margin rule prevented a switch.
    pub margin_suppressed: bool,
    /// The committed L2 policy changed the original UCB candidate and its
    /// candidate was the action actually selected. Missing legacy records
    /// cannot claim a policy intervention.
    #[serde(default)]
    pub l2_policy_applied: bool,
    /// Whether the selected arm differs from the incumbent arm.
    pub switched: bool,
    /// Whether a safety-related condition overrode the ordinary choice.
    pub safety_override: bool,
    /// Reward after configured safety or rollback adjustments, when available.
    pub adjusted_reward: Option<f64>,
    /// Number of rollbacks included in the decision context.
    pub rollback_count: u64,
    /// Cost charged for switching to the selected arm.
    pub switch_cost_applied: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(default)]
/// Current L2 policy parameters, expert mixture, gate state, and confidence.
pub struct L2Policy {
    /// Prior probabilities for the two bandit arms.
    pub prior: [f64; 2],
    /// Strength of KL regularization applied to the policy.
    pub beta: f64,
    /// Current L2 adaptation rate.
    pub alpha: f64,
    /// Whether this policy has been committed for use.
    pub committed: bool,
    /// Index of the selected L2 expert.
    pub expert: usize,
    /// Current mixture probabilities for the L2 experts.
    pub expert_probabilities: [f64; 4],
    /// State of the L2 update gate.
    pub gate_state: crate::l2::control::L2GateState,
    /// Confidence assigned to the current policy estimate.
    pub confidence: f64,
    /// Experimental spectral KL weighting. Disabled for legacy controllers.
    #[serde(default)]
    pub spectral_weighting: bool,
}
impl Default for L2Policy {
    fn default() -> Self {
        Self {
            prior: [0.5, 0.5],
            beta: 0.0,
            alpha: 0.0,
            committed: false,
            expert: 0,
            expert_probabilities: [0.25; 4],
            gate_state: crate::l2::control::L2GateState::Dormant,
            confidence: 0.0,
            spectral_weighting: false,
        }
    }
}
impl L2Policy {
    /// Performs keep L0 for this type.
    pub fn keep_l0() -> Self {
        Self::default()
    }

    /// The only value that may cross the L2 -> L0 commit boundary.
    ///
    /// This is deliberately a second validation at the consumer as well as at
    /// the producer. A proposal, an L0 dwell/margin hold, a dormant controller,
    /// KEEP_L0, a veto, and a malformed snapshot all collapse to exactly the
    /// same zero policy. Keeping this check here prevents a future producer
    /// from accidentally turning a diagnostic field into an intervention.
    pub fn effective(self) -> Self {
        let probabilities_sum = self.expert_probabilities.iter().sum::<f64>();
        let prior_sum = self.prior.iter().sum::<f64>();
        let valid = self.committed
            && self.gate_state == crate::l2::control::L2GateState::Active
            && self.expert > 0
            && self.expert < 4
            && self.alpha > 0.0
            && self.alpha <= 0.35
            && self.alpha.is_finite()
            && self.beta > 0.0
            && self.beta.is_finite()
            && self.confidence.is_finite()
            && (0.0..=1.0).contains(&self.confidence)
            && self.prior.iter().all(|p| p.is_finite() && *p > 0.0)
            && libm::fabs(prior_sum - 1.0) < 1.0e-6
            && self
                .expert_probabilities
                .iter()
                .all(|p| p.is_finite() && *p > 0.0)
            && libm::fabs(probabilities_sum - 1.0) < 1.0e-6;
        if valid {
            self
        } else {
            Self::default()
        }
    }
}

#[derive(Debug, Clone, Copy, Default)]
/// Data structure representing decision feedback.
pub struct DecisionFeedback {
    /// Whether L1 rollback is enabled or active.
    pub l1_rollback: bool,
    /// Whether safety degradation is enabled or active.
    pub safety_degradation: bool,
    /// Error improvement is a positive reward contribution.
    pub error_delta: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Data structure representing trajectory.
pub struct Trajectory {
    /// Collection of observations.
    pub observations: Vec<Observation>,
    /// Collection of predictions.
    pub predictions: Vec<Prediction>,
    /// Collection of actions.
    pub actions: Vec<Action>,
    /// Collection of outcomes.
    pub outcomes: Vec<serde_json::Value>,
    /// Collection of prediction errors.
    pub prediction_errors: Vec<f64>,
    /// Mapping of meta.
    pub meta: BTreeMap<String, serde_json::Value>,
}

/// Structured, safely-applied effect of a cognitive patch.
/// This is what actually changes L0 behavior — not the `code` string.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RuleEffect {
    /// Multiplies prediction error / uncertainty (1.0 = no change, lower = better).
    pub error_damping: f64,
    /// Additive preference scores for action names.
    pub action_preference: BTreeMap<String, f64>,
    /// Floor for reported uncertainty after damping.
    pub min_uncertainty: f64,
    /// Additive score bias toward "explore" (negative favors exploit/stabilize).
    #[serde(default)]
    pub explore_bonus: f64,
    /// Soft threshold for treating uncertainty as "high" (higher = more tolerant).
    #[serde(default = "default_risk_tolerance")]
    pub risk_tolerance: f64,
}

fn default_risk_tolerance() -> f64 {
    0.45
}

impl Default for RuleEffect {
    fn default() -> Self {
        Self {
            error_damping: 1.0,
            action_preference: BTreeMap::new(),
            min_uncertainty: 0.05,
            explore_bonus: 0.0,
            risk_tolerance: 0.45,
        }
    }
}

impl RuleEffect {
    /// Constant defining allowed actions.
    pub const ALLOWED_ACTIONS: &'static [&'static str] =
        &["noop", "observe", "explore", "exploit", "stabilize"];

    /// Performs sanitize for this type.
    pub fn sanitize(mut self) -> Self {
        self.error_damping = if self.error_damping.is_finite() {
            self.error_damping.clamp(0.2, 1.5)
        } else {
            1.0
        };
        self.min_uncertainty = if self.min_uncertainty.is_finite() {
            self.min_uncertainty.clamp(0.01, 0.5)
        } else {
            0.05
        };
        self.explore_bonus = if self.explore_bonus.is_finite() {
            self.explore_bonus.clamp(-1.5, 1.5)
        } else {
            0.0
        };
        self.risk_tolerance = if self.risk_tolerance.is_finite() {
            self.risk_tolerance.clamp(0.15, 0.85)
        } else {
            0.45
        };
        self.action_preference.retain(|k, v| {
            if !Self::ALLOWED_ACTIONS.contains(&k.as_str()) || !v.is_finite() {
                return false;
            }
            *v = v.clamp(-5.0, 5.0);
            true
        });
        self
    }

    /// Validates this value and reports any violated constraints.
    pub fn validate_bounds(&self) -> Option<String> {
        if !(0.15..=2.0).contains(&self.error_damping) {
            return Some(format!(
                "error_damping {:.3} outside [0.15, 2.0]",
                self.error_damping
            ));
        }
        if !(0.0..=1.0).contains(&self.min_uncertainty) {
            return Some(format!(
                "min_uncertainty {:.3} outside [0.0, 1.0]",
                self.min_uncertainty
            ));
        }
        if !(-2.0..=2.0).contains(&self.explore_bonus) {
            return Some(format!(
                "explore_bonus {:.3} outside [-2.0, 2.0]",
                self.explore_bonus
            ));
        }
        if !(0.1..=0.9).contains(&self.risk_tolerance) {
            return Some(format!(
                "risk_tolerance {:.3} outside [0.1, 0.9]",
                self.risk_tolerance
            ));
        }
        for (k, v) in &self.action_preference {
            if !Self::ALLOWED_ACTIONS.contains(&k.as_str()) {
                return Some(format!("unknown action preference key: {k}"));
            }
            if !(-10.0..=10.0).contains(v) {
                return Some(format!("action preference {k}={v} outside [-10, 10]"));
            }
        }
        None
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Data structure representing cognitive patch.
pub struct CognitivePatch {
    /// Identifier for the patch.
    pub patch_id: Uuid,
    /// Description for this value.
    pub description: String,
    /// Code for this value.
    pub code: String,
    /// Target module for this value.
    pub target_module: String,
    /// Expected effect for this value.
    pub expected_effect: String,
    /// Risk level for this value.
    pub risk_level: f64,
    /// UTC timestamp when the checkpoint was created.
    pub created_at: UtcTimestamp,
    /// Effect for this value.
    pub effect: RuleEffect,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Data structure representing meta metrics.
pub struct MetaMetrics {
    /// Complexity for this value.
    pub complexity: f64,
    /// Consistency for this value.
    pub consistency: f64,
    /// Predictive power for this value.
    pub predictive_power: f64,
    /// Self ref stability for this value.
    pub self_ref_stability: f64,
    /// Time at which the timestamp occurred.
    pub timestamp: UtcTimestamp,
}

#[derive(Debug, Clone, Default)]
/// Data structure representing system state.
pub struct SystemState {
    /// Mapping of active code.
    pub active_code: BTreeMap<String, String>,
    /// Highest attractor for this value.
    pub highest_attractor: String,
    /// Optional generative base.
    pub generative_base: Option<String>,
    /// Most recent trajectory summary.
    pub last_trajectory_summary: Option<String>,
    /// Average prediction error recorded by the kernel.
    pub avg_prediction_error: f64,
    /// Total number of kernel steps completed.
    pub total_steps: u64,
}