Skip to main content

omega_cognitive_kernel/
types.rs

1#[allow(unused_imports)]
2use crate::prelude::*;
3
4use alloc::collections::BTreeMap;
5use serde::{Deserialize, Serialize};
6use uuid::Uuid;
7
8#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
9#[serde(transparent)]
10/// UTC timestamp with stable RFC 3339 serialization and a no_std epoch fallback.
11///
12/// `now()` reads the system clock with the `std` feature and returns [`Self::UNIX_EPOCH`] in a
13/// `no_std` build, where no clock source is available.
14///
15/// # Examples
16///
17/// ```
18/// use omega_cognitive_kernel::UtcTimestamp;
19///
20/// let epoch = match UtcTimestamp::from_rfc3339("1970-01-01T00:00:00Z") {
21///     Ok(epoch) => epoch,
22///     Err(error) => panic!("valid RFC 3339 timestamp should parse: {error}"),
23/// };
24/// assert_eq!(epoch, UtcTimestamp::UNIX_EPOCH);
25/// assert_eq!(epoch.timestamp(), 0);
26/// assert_eq!(epoch.timestamp_millis(), 0);
27/// ```
28pub struct UtcTimestamp(chrono::DateTime<chrono::Utc>);
29
30impl UtcTimestamp {
31    /// Timestamp at the Unix epoch (`1970-01-01T00:00:00Z`).
32    pub const UNIX_EPOCH: Self = Self(chrono::DateTime::<chrono::Utc>::UNIX_EPOCH);
33
34    /// Returns the current UTC time.
35    #[cfg(feature = "std")]
36    pub fn now() -> Self {
37        Self(chrono::Utc::now())
38    }
39
40    /// Returns [`Self::UNIX_EPOCH`] because a `no_std` build has no clock source.
41    #[cfg(not(feature = "std"))]
42    pub fn now() -> Self {
43        Self::UNIX_EPOCH
44    }
45
46    /// Formats the timestamp as an RFC 3339 string.
47    pub fn to_rfc3339(&self) -> alloc::string::String {
48        self.0.to_rfc3339()
49    }
50
51    /// Parses an RFC 3339 string and normalizes the result to UTC.
52    pub fn from_rfc3339(s: &str) -> Result<Self, alloc::string::String> {
53        chrono::DateTime::parse_from_rfc3339(s)
54            .map(|dt| Self(dt.with_timezone(&chrono::Utc)))
55            .map_err(|e| alloc::format!("{}", e))
56    }
57
58    /// Returns whole seconds since the Unix epoch.
59    pub fn timestamp(&self) -> i64 {
60        self.0.timestamp()
61    }
62
63    /// Returns whole milliseconds since the Unix epoch.
64    pub fn timestamp_millis(&self) -> i64 {
65        self.0.timestamp_millis()
66    }
67}
68impl Default for UtcTimestamp {
69    fn default() -> Self {
70        Self::UNIX_EPOCH
71    }
72}
73
74impl core::fmt::Debug for UtcTimestamp {
75    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
76        f.debug_tuple("UtcTimestamp")
77            .field(&self.to_rfc3339())
78            .finish()
79    }
80}
81
82impl core::fmt::Display for UtcTimestamp {
83    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
84        write!(f, "{}", self.to_rfc3339())
85    }
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
89/// Kind of input represented by an observation.
90pub enum Modality {
91    /// Textual input.
92    Text,
93    /// Image input.
94    Image,
95    /// Audio input.
96    Audio,
97    /// Structured data input.
98    Structured,
99    /// Internal kernel-generated input.
100    Internal,
101}
102
103#[derive(Debug, Clone, Serialize, Deserialize)]
104/// Input captured by an observer, with its modality, confidence, and source.
105pub struct Observation {
106    /// UTC time when the observation was captured.
107    pub timestamp: UtcTimestamp,
108    /// Kind of input contained in `content`.
109    pub modality: Modality,
110    /// Observed content encoded as a JSON value.
111    pub content: serde_json::Value,
112    /// Observer-assigned confidence in the observation.
113    pub confidence: f64,
114    /// Name or identifier of the observation source.
115    pub source: String,
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize)]
119/// Predicted value together with its uncertainty and forecast horizon.
120pub struct Prediction {
121    /// Predicted value expected at the requested horizon.
122    pub expected: serde_json::Value,
123    /// Uncertainty associated with the prediction.
124    pub uncertainty: f64,
125    /// Forecast horizon in seconds.
126    pub horizon_secs: f64,
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
130/// Goal and priority supplied to the decision layer, including memory-derived biases.
131pub struct Intent {
132    /// High-level goal to pursue.
133    pub goal: String,
134    /// Relative priority assigned to the goal.
135    pub priority: f64,
136    /// Mapping of bias from memory.
137    pub bias_from_memory: BTreeMap<String, f64>,
138}
139
140#[derive(Debug, Clone, Serialize, Deserialize)]
141/// Action proposed by the decision layer, with parameters and constraint-check status.
142pub struct Action {
143    /// Name used to identify this parameter or action.
144    pub name: String,
145    /// Named parameters supplied to the action.
146    pub params: BTreeMap<String, serde_json::Value>,
147    /// Whether configured constraint checks were performed for this action.
148    pub constraints_checked: bool,
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
152#[serde(default)]
153/// Configuration for bandit.
154pub struct BanditConfig {
155    /// Minimum decisions to keep an arm before considering a switch.
156    pub min_dwell_steps: u64,
157    /// Required UCB advantage over the incumbent arm.
158    pub switch_margin: f64,
159    /// Multiplier for rollback/safety-degradation signals in the UCB reward.
160    pub rollback_penalty: f64,
161    /// Cost charged to the destination arm when changing arms.
162    pub switch_cost: f64,
163}
164
165impl Default for BanditConfig {
166    fn default() -> Self {
167        Self {
168            min_dwell_steps: 3,
169            switch_margin: 0.05,
170            rollback_penalty: 0.35,
171            switch_cost: 0.02,
172        }
173    }
174}
175
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(rename_all = "snake_case")]
178/// Reason recorded when the L2 bandit controller selects or retains an arm.
179pub enum L2DecisionReason {
180    /// Initial exploration before an arm has an established reward estimate.
181    InitialExplore,
182    /// The arm with the strongest current estimate was selected.
183    Exploit,
184    /// An arm was selected to explore an alternative.
185    Explore,
186    /// Selection changed from the incumbent arm to another arm.
187    Switched,
188    /// The incumbent arm was retained because its minimum dwell period has not elapsed.
189    DwellHold,
190    /// The incumbent arm was retained because the candidate did not clear the switch margin.
191    MarginHold,
192    /// A safety-related condition overrode the ordinary bandit choice.
193    SafetyOverride,
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize)]
197/// Record of the L2 bandit's selected arm, candidate, scores, and switching constraints.
198pub struct L2DecisionRecord {
199    /// Index of the arm ultimately selected.
200    pub selected_arm: usize,
201    /// Name of the bias or action associated with the selected arm.
202    pub selected_bias: String,
203    /// Index of the arm proposed by the candidate-selection policy.
204    pub candidate_arm: usize,
205    /// Estimated mean reward for the selected arm.
206    pub mean_reward: f64,
207    /// Multiplicative exploration term of the selected arm.
208    pub exploration_bonus: f64,
209    /// UCB score of the selected arm; null while that arm is still unexplored.
210    pub ucb_score: Option<f64>,
211    /// UCB score of the candidate arm, when available.
212    pub candidate_ucb_score: Option<f64>,
213    /// UCB score of the incumbent arm, when available.
214    pub current_ucb_score: Option<f64>,
215    /// Reason the selected arm was chosen or retained.
216    pub reason: L2DecisionReason,
217    /// Number of steps spent in the current regime or arm.
218    pub dwell_steps: u64,
219    /// Whether the minimum-dwell rule prevented a switch.
220    pub dwell_suppressed: bool,
221    /// Whether the switch-margin rule prevented a switch.
222    pub margin_suppressed: bool,
223    /// The committed L2 policy changed the original UCB candidate and its
224    /// candidate was the action actually selected. Missing legacy records
225    /// cannot claim a policy intervention.
226    #[serde(default)]
227    pub l2_policy_applied: bool,
228    /// Whether the selected arm differs from the incumbent arm.
229    pub switched: bool,
230    /// Whether a safety-related condition overrode the ordinary choice.
231    pub safety_override: bool,
232    /// Reward after configured safety or rollback adjustments, when available.
233    pub adjusted_reward: Option<f64>,
234    /// Number of rollbacks included in the decision context.
235    pub rollback_count: u64,
236    /// Cost charged for switching to the selected arm.
237    pub switch_cost_applied: f64,
238}
239
240#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
241#[serde(default)]
242/// Current L2 policy parameters, expert mixture, gate state, and confidence.
243pub struct L2Policy {
244    /// Prior probabilities for the two bandit arms.
245    pub prior: [f64; 2],
246    /// Strength of KL regularization applied to the policy.
247    pub beta: f64,
248    /// Current L2 adaptation rate.
249    pub alpha: f64,
250    /// Whether this policy has been committed for use.
251    pub committed: bool,
252    /// Index of the selected L2 expert.
253    pub expert: usize,
254    /// Current mixture probabilities for the L2 experts.
255    pub expert_probabilities: [f64; 4],
256    /// State of the L2 update gate.
257    pub gate_state: crate::l2::control::L2GateState,
258    /// Confidence assigned to the current policy estimate.
259    pub confidence: f64,
260    /// Experimental spectral KL weighting. Disabled for legacy controllers.
261    #[serde(default)]
262    pub spectral_weighting: bool,
263}
264impl Default for L2Policy {
265    fn default() -> Self {
266        Self {
267            prior: [0.5, 0.5],
268            beta: 0.0,
269            alpha: 0.0,
270            committed: false,
271            expert: 0,
272            expert_probabilities: [0.25; 4],
273            gate_state: crate::l2::control::L2GateState::Dormant,
274            confidence: 0.0,
275            spectral_weighting: false,
276        }
277    }
278}
279impl L2Policy {
280    /// Performs keep L0 for this type.
281    pub fn keep_l0() -> Self {
282        Self::default()
283    }
284
285    /// The only value that may cross the L2 -> L0 commit boundary.
286    ///
287    /// This is deliberately a second validation at the consumer as well as at
288    /// the producer. A proposal, an L0 dwell/margin hold, a dormant controller,
289    /// KEEP_L0, a veto, and a malformed snapshot all collapse to exactly the
290    /// same zero policy. Keeping this check here prevents a future producer
291    /// from accidentally turning a diagnostic field into an intervention.
292    pub fn effective(self) -> Self {
293        let probabilities_sum = self.expert_probabilities.iter().sum::<f64>();
294        let prior_sum = self.prior.iter().sum::<f64>();
295        let valid = self.committed
296            && self.gate_state == crate::l2::control::L2GateState::Active
297            && self.expert > 0
298            && self.expert < 4
299            && self.alpha > 0.0
300            && self.alpha <= 0.35
301            && self.alpha.is_finite()
302            && self.beta > 0.0
303            && self.beta.is_finite()
304            && self.confidence.is_finite()
305            && (0.0..=1.0).contains(&self.confidence)
306            && self.prior.iter().all(|p| p.is_finite() && *p > 0.0)
307            && libm::fabs(prior_sum - 1.0) < 1.0e-6
308            && self
309                .expert_probabilities
310                .iter()
311                .all(|p| p.is_finite() && *p > 0.0)
312            && libm::fabs(probabilities_sum - 1.0) < 1.0e-6;
313        if valid {
314            self
315        } else {
316            Self::default()
317        }
318    }
319}
320
321#[derive(Debug, Clone, Copy, Default)]
322/// Data structure representing decision feedback.
323pub struct DecisionFeedback {
324    /// Whether L1 rollback is enabled or active.
325    pub l1_rollback: bool,
326    /// Whether safety degradation is enabled or active.
327    pub safety_degradation: bool,
328    /// Error improvement is a positive reward contribution.
329    pub error_delta: f64,
330}
331
332#[derive(Debug, Clone, Serialize, Deserialize)]
333/// Data structure representing trajectory.
334pub struct Trajectory {
335    /// Collection of observations.
336    pub observations: Vec<Observation>,
337    /// Collection of predictions.
338    pub predictions: Vec<Prediction>,
339    /// Collection of actions.
340    pub actions: Vec<Action>,
341    /// Collection of outcomes.
342    pub outcomes: Vec<serde_json::Value>,
343    /// Collection of prediction errors.
344    pub prediction_errors: Vec<f64>,
345    /// Mapping of meta.
346    pub meta: BTreeMap<String, serde_json::Value>,
347}
348
349/// Structured, safely-applied effect of a cognitive patch.
350/// This is what actually changes L0 behavior — not the `code` string.
351#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
352pub struct RuleEffect {
353    /// Multiplies prediction error / uncertainty (1.0 = no change, lower = better).
354    pub error_damping: f64,
355    /// Additive preference scores for action names.
356    pub action_preference: BTreeMap<String, f64>,
357    /// Floor for reported uncertainty after damping.
358    pub min_uncertainty: f64,
359    /// Additive score bias toward "explore" (negative favors exploit/stabilize).
360    #[serde(default)]
361    pub explore_bonus: f64,
362    /// Soft threshold for treating uncertainty as "high" (higher = more tolerant).
363    #[serde(default = "default_risk_tolerance")]
364    pub risk_tolerance: f64,
365}
366
367fn default_risk_tolerance() -> f64 {
368    0.45
369}
370
371impl Default for RuleEffect {
372    fn default() -> Self {
373        Self {
374            error_damping: 1.0,
375            action_preference: BTreeMap::new(),
376            min_uncertainty: 0.05,
377            explore_bonus: 0.0,
378            risk_tolerance: 0.45,
379        }
380    }
381}
382
383impl RuleEffect {
384    /// Constant defining allowed actions.
385    pub const ALLOWED_ACTIONS: &'static [&'static str] =
386        &["noop", "observe", "explore", "exploit", "stabilize"];
387
388    /// Performs sanitize for this type.
389    pub fn sanitize(mut self) -> Self {
390        self.error_damping = if self.error_damping.is_finite() {
391            self.error_damping.clamp(0.2, 1.5)
392        } else {
393            1.0
394        };
395        self.min_uncertainty = if self.min_uncertainty.is_finite() {
396            self.min_uncertainty.clamp(0.01, 0.5)
397        } else {
398            0.05
399        };
400        self.explore_bonus = if self.explore_bonus.is_finite() {
401            self.explore_bonus.clamp(-1.5, 1.5)
402        } else {
403            0.0
404        };
405        self.risk_tolerance = if self.risk_tolerance.is_finite() {
406            self.risk_tolerance.clamp(0.15, 0.85)
407        } else {
408            0.45
409        };
410        self.action_preference.retain(|k, v| {
411            if !Self::ALLOWED_ACTIONS.contains(&k.as_str()) || !v.is_finite() {
412                return false;
413            }
414            *v = v.clamp(-5.0, 5.0);
415            true
416        });
417        self
418    }
419
420    /// Validates this value and reports any violated constraints.
421    pub fn validate_bounds(&self) -> Option<String> {
422        if !(0.15..=2.0).contains(&self.error_damping) {
423            return Some(format!(
424                "error_damping {:.3} outside [0.15, 2.0]",
425                self.error_damping
426            ));
427        }
428        if !(0.0..=1.0).contains(&self.min_uncertainty) {
429            return Some(format!(
430                "min_uncertainty {:.3} outside [0.0, 1.0]",
431                self.min_uncertainty
432            ));
433        }
434        if !(-2.0..=2.0).contains(&self.explore_bonus) {
435            return Some(format!(
436                "explore_bonus {:.3} outside [-2.0, 2.0]",
437                self.explore_bonus
438            ));
439        }
440        if !(0.1..=0.9).contains(&self.risk_tolerance) {
441            return Some(format!(
442                "risk_tolerance {:.3} outside [0.1, 0.9]",
443                self.risk_tolerance
444            ));
445        }
446        for (k, v) in &self.action_preference {
447            if !Self::ALLOWED_ACTIONS.contains(&k.as_str()) {
448                return Some(format!("unknown action preference key: {k}"));
449            }
450            if !(-10.0..=10.0).contains(v) {
451                return Some(format!("action preference {k}={v} outside [-10, 10]"));
452            }
453        }
454        None
455    }
456}
457
458#[derive(Debug, Clone, Serialize, Deserialize)]
459/// Data structure representing cognitive patch.
460pub struct CognitivePatch {
461    /// Identifier for the patch.
462    pub patch_id: Uuid,
463    /// Description for this value.
464    pub description: String,
465    /// Code for this value.
466    pub code: String,
467    /// Target module for this value.
468    pub target_module: String,
469    /// Expected effect for this value.
470    pub expected_effect: String,
471    /// Risk level for this value.
472    pub risk_level: f64,
473    /// UTC timestamp when the checkpoint was created.
474    pub created_at: UtcTimestamp,
475    /// Effect for this value.
476    pub effect: RuleEffect,
477}
478
479#[derive(Debug, Clone, Serialize, Deserialize)]
480/// Data structure representing meta metrics.
481pub struct MetaMetrics {
482    /// Complexity for this value.
483    pub complexity: f64,
484    /// Consistency for this value.
485    pub consistency: f64,
486    /// Predictive power for this value.
487    pub predictive_power: f64,
488    /// Self ref stability for this value.
489    pub self_ref_stability: f64,
490    /// Time at which the timestamp occurred.
491    pub timestamp: UtcTimestamp,
492}
493
494#[derive(Debug, Clone, Default)]
495/// Data structure representing system state.
496pub struct SystemState {
497    /// Mapping of active code.
498    pub active_code: BTreeMap<String, String>,
499    /// Highest attractor for this value.
500    pub highest_attractor: String,
501    /// Optional generative base.
502    pub generative_base: Option<String>,
503    /// Most recent trajectory summary.
504    pub last_trajectory_summary: Option<String>,
505    /// Average prediction error recorded by the kernel.
506    pub avg_prediction_error: f64,
507    /// Total number of kernel steps completed.
508    pub total_steps: u64,
509}