oxios-kernel 0.3.0

Oxios kernel: supervisor, event bus, state store
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
//! SONA — Self-Optimizing Neural Architecture (simplified).
//!
//! Tracks execution trajectories, distills successful patterns,
//! and adapts future behavior based on learned experience.
//!
//! Performance target: adaptation in < 0.05ms (in-memory lookup).

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::embedding::{EmbeddingProvider, EmbeddingVector};

// ---------------------------------------------------------------------------
// Data types
// ---------------------------------------------------------------------------

/// Operating mode for the SONA engine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SonaMode {
    /// Real-time adaptation (< 0.05ms target).
    RealTime,
    /// Balanced between speed and depth.
    Balanced,
    /// Research mode — deep analysis, no time constraints.
    Research,
    /// Edge device — minimal memory footprint.
    Edge,
}

impl Default for SonaMode {
    fn default() -> Self {
        Self::Balanced
    }
}

/// Verdict for a trajectory outcome.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
    /// Fully successful.
    Success,
    /// Partially successful (some steps failed).
    PartialFailure,
    /// Completely failed.
    Failure,
}

/// A single step within a trajectory.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrajectoryStep {
    /// Step description / input.
    pub input: String,
    /// Step result / output.
    pub output: String,
    /// Duration of this step in milliseconds.
    pub duration_ms: u64,
    /// Confidence score (0.0–1.0).
    pub confidence: f32,
}

/// A trajectory — a sequence of steps with a final verdict.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Trajectory {
    /// Unique ID.
    pub id: String,
    /// Ordered steps.
    pub steps: Vec<TrajectoryStep>,
    /// Final verdict.
    pub verdict: Verdict,
    /// Domain or task type.
    pub domain: String,
    /// Creation timestamp.
    pub created_at: DateTime<Utc>,
    /// Embedding of the trajectory's combined input text.
    #[serde(skip)]
    pub embedding: Option<EmbeddingVector>,
}

impl Trajectory {
    /// Create a new trajectory with the given steps and verdict.
    pub fn new(steps: Vec<TrajectoryStep>, verdict: Verdict, domain: &str) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            steps,
            verdict,
            domain: domain.to_string(),
            created_at: Utc::now(),
            embedding: None,
        }
    }

    /// Total duration across all steps.
    pub fn total_duration_ms(&self) -> u64 {
        self.steps.iter().map(|s| s.duration_ms).sum()
    }

    /// Average confidence across all steps.
    pub fn avg_confidence(&self) -> f32 {
        if self.steps.is_empty() {
            return 0.0;
        }
        self.steps.iter().map(|s| s.confidence).sum::<f32>() / self.steps.len() as f32
    }

    /// Concatenated input text for embedding.
    pub fn input_text(&self) -> String {
        self.steps
            .iter()
            .map(|s| s.input.as_str())
            .collect::<Vec<_>>()
            .join(" ")
    }
}

/// A distilled pattern extracted from successful trajectories.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LearnedPattern {
    /// Unique ID.
    pub id: String,
    /// Source trajectory IDs.
    pub source_trajectories: Vec<String>,
    /// Distilled strategy description.
    pub strategy: String,
    /// Domain category.
    pub domain: String,
    /// Confidence in this pattern (based on number of supporting trajectories).
    pub confidence: f32,
    /// Number of trajectories this was distilled from.
    pub support_count: usize,
    /// Embedding for similarity matching.
    #[serde(skip)]
    pub embedding: Option<EmbeddingVector>,
}

// ---------------------------------------------------------------------------
// SonaEngine
// ---------------------------------------------------------------------------

/// The SONA engine for trajectory-based self-learning.
///
/// Records execution trajectories, distills patterns from successful ones,
/// and adapts future behavior by matching against learned patterns.
pub struct SonaEngine {
    /// Operating mode.
    mode: SonaMode,
    /// Recorded trajectories.
    trajectories: RwLock<Vec<Trajectory>>,
    /// Distilled patterns from successful trajectories.
    learned_patterns: RwLock<Vec<LearnedPattern>>,
    /// Embedding provider.
    embedding: std::sync::Arc<dyn EmbeddingProvider>,
    /// Maximum trajectories to keep (mode-dependent).
    max_trajectories: usize,
}

impl std::fmt::Debug for SonaEngine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SonaEngine")
            .field("mode", &self.mode)
            .field("trajectory_count", &self.trajectories.read().len())
            .field("pattern_count", &self.learned_patterns.read().len())
            .finish()
    }
}

impl SonaEngine {
    /// Create a new SONA engine with the given mode and embedding provider.
    pub fn new(mode: SonaMode, embedding: std::sync::Arc<dyn EmbeddingProvider>) -> Self {
        let max_trajectories = match mode {
            SonaMode::RealTime => 100,
            SonaMode::Balanced => 500,
            SonaMode::Research => 5000,
            SonaMode::Edge => 50,
        };

        Self {
            mode,
            trajectories: RwLock::new(Vec::new()),
            learned_patterns: RwLock::new(Vec::new()),
            embedding,
            max_trajectories,
        }
    }

    /// Return the current operating mode.
    pub fn mode(&self) -> SonaMode {
        self.mode
    }

    /// Record a new trajectory.
    ///
    /// Generates an embedding for the trajectory's input text
    /// and stores it for future distillation.
    pub async fn record(&self, mut trajectory: Trajectory) -> Result<String, anyhow::Error> {
        if trajectory.id.is_empty() {
            trajectory.id = Uuid::new_v4().to_string();
        }

        // Generate embedding
        let text = trajectory.input_text();
        if !text.is_empty() {
            let embedding = self.embedding.embed(&text).await?;
            trajectory.embedding = Some(embedding);
        }

        let id = trajectory.id.clone();

        let mut trajs = self.trajectories.write();

        // Enforce capacity limit
        if trajs.len() >= self.max_trajectories {
            // Remove oldest failure trajectories first
            let remove_count = trajs.len() - self.max_trajectories + 1;
            let mut removed = 0;
            trajs.retain(|t| {
                if removed >= remove_count {
                    return true;
                }
                if t.verdict == Verdict::Failure {
                    removed += 1;
                    false
                } else {
                    true
                }
            });
            // If still over capacity, remove oldest
            while trajs.len() >= self.max_trajectories {
                trajs.remove(0);
            }
        }

        trajs.push(trajectory);
        Ok(id)
    }

    /// Distill learned patterns from successful trajectories.
    ///
    /// Groups successful trajectories by domain and extracts common
    /// patterns. Returns the newly distilled patterns.
    pub async fn distill(&self) -> Result<Vec<LearnedPattern>, anyhow::Error> {
        let trajs = self.trajectories.read();

        // Group successful trajectories by domain
        let mut domain_groups: HashMap<String, Vec<&Trajectory>> = HashMap::new();
        for traj in trajs.iter() {
            if traj.verdict == Verdict::Success {
                domain_groups
                    .entry(traj.domain.clone())
                    .or_default()
                    .push(traj);
            }
        }

        let mut new_patterns = Vec::new();

        for (domain, group) in &domain_groups {
            if group.len() < 2 {
                continue; // Need at least 2 trajectories to distill
            }

            // Simple distillation: extract common step patterns
            // For each trajectory, get the strategy from concatenated inputs
            let mut strategy_parts: Vec<String> = Vec::new();
            for traj in group {
                let summary: String = traj
                    .steps
                    .iter()
                    .take(3) // Use first 3 steps as summary
                    .map(|s| s.input.clone())
                    .collect::<Vec<_>>()
                    .join("");
                strategy_parts.push(summary);
            }

            // Combine strategies into a distilled pattern
            let combined = strategy_parts.join("; ");
            let strategy = if combined.len() > 500 {
                format!("{}...", &combined[..500])
            } else {
                combined
            };

            let embedding = self.embedding.embed(&strategy).await?;

            let source_ids: Vec<String> = group.iter().map(|t| t.id.clone()).collect();

            let pattern = LearnedPattern {
                id: Uuid::new_v4().to_string(),
                source_trajectories: source_ids,
                strategy,
                domain: domain.clone(),
                confidence: (group.len() as f32 * 0.2).min(1.0),
                support_count: group.len(),
                embedding: Some(embedding),
            };

            new_patterns.push(pattern);
        }

        drop(trajs); // Release read lock

        // Store new patterns
        {
            let mut patterns = self.learned_patterns.write();
            for pattern in &new_patterns {
                // Don't duplicate — check by strategy similarity (simplified: exact match)
                let is_dup = patterns
                    .iter()
                    .any(|p| p.strategy == pattern.strategy && p.domain == pattern.domain);
                if !is_dup {
                    patterns.push(pattern.clone());
                }
            }
        }

        tracing::info!(new_patterns = new_patterns.len(), "SONA distillation complete");
        Ok(new_patterns)
    }

    /// Adapt to a new query by finding the most similar learned pattern.
    ///
    /// Returns the best matching pattern if similarity exceeds threshold.
    /// Target: < 0.05ms for in-memory lookup.
    pub async fn adapt(&self, query: &str) -> Result<Option<LearnedPattern>, anyhow::Error> {
        let query_embedding = self.embedding.embed(query).await?;

        let patterns = self.learned_patterns.read();
        let mut best: Option<(&LearnedPattern, f64)> = None;

        for pattern in patterns.iter() {
            if let Some(ref emb) = pattern.embedding {
                let sim = query_embedding.cosine_similarity(emb);
                match best {
                    Some((_, best_sim)) if sim <= best_sim => {}
                    _ => best = Some((pattern, sim)),
                }
            }
        }

        Ok(best
            .filter(|(_, sim)| *sim > 0.3)
            .map(|(p, sim)| {
                let mut adapted = p.clone();
                adapted.confidence = (p.confidence * sim as f32).min(1.0);
                adapted
            }))
    }

    /// Return counts of trajectories and patterns.
    pub fn counts(&self) -> (usize, usize) {
        let traj_count = self.trajectories.read().len();
        let pattern_count = self.learned_patterns.read().len();
        (traj_count, pattern_count)
    }

    /// Get all learned patterns for persistence.
    pub fn get_learned_patterns(&self) -> Vec<LearnedPattern> {
        self.learned_patterns.read().clone()
    }

    /// Load learned patterns from persistence.
    pub fn load_learned_patterns(&self, patterns: Vec<LearnedPattern>) {
        let mut existing = self.learned_patterns.write();
        *existing = patterns;
    }

    /// Get trajectories filtered by verdict.
    pub fn trajectories_by_verdict(&self, verdict: Verdict) -> Vec<Trajectory> {
        self.trajectories
            .read()
            .iter()
            .filter(|t| t.verdict == verdict)
            .cloned()
            .collect()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::embedding::TfIdfEmbeddingProvider;

    fn make_step(input: &str, output: &str) -> TrajectoryStep {
        TrajectoryStep {
            input: input.to_string(),
            output: output.to_string(),
            duration_ms: 10,
            confidence: 0.9,
        }
    }

    fn make_trajectory(domain: &str, verdict: Verdict) -> Trajectory {
        Trajectory::new(
            vec![
                make_step("analyze input", "parsed"),
                make_step("execute plan", "completed"),
            ],
            verdict,
            domain,
        )
    }

    #[tokio::test]
    async fn test_record_trajectory() {
        let engine = SonaEngine::new(SonaMode::Balanced, std::sync::Arc::new(TfIdfEmbeddingProvider));
        let traj = make_trajectory("testing", Verdict::Success);

        let id = engine.record(traj).await.unwrap();
        assert!(!id.is_empty());

        let (traj_count, _) = engine.counts();
        assert_eq!(traj_count, 1);
    }

    #[tokio::test]
    async fn test_distill_patterns() {
        let engine = SonaEngine::new(SonaMode::Balanced, std::sync::Arc::new(TfIdfEmbeddingProvider));

        // Record multiple successful trajectories in the same domain
        for _ in 0..3 {
            let traj = make_trajectory("security", Verdict::Success);
            engine.record(traj).await.unwrap();
        }

        let patterns = engine.distill().await.unwrap();
        assert!(!patterns.is_empty(), "Should distill patterns from 3+ successful trajectories");

        let (_, pattern_count) = engine.counts();
        assert!(pattern_count > 0);
    }

    #[tokio::test]
    async fn test_distill_needs_multiple_successes() {
        let engine = SonaEngine::new(SonaMode::Balanced, std::sync::Arc::new(TfIdfEmbeddingProvider));

        engine.record(make_trajectory("testing", Verdict::Success)).await.unwrap();
        let patterns = engine.distill().await.unwrap();
        assert!(patterns.is_empty(), "Need 2+ trajectories to distill");
    }

    #[tokio::test]
    async fn test_distill_ignores_failures() {
        let engine = SonaEngine::new(SonaMode::Balanced, std::sync::Arc::new(TfIdfEmbeddingProvider));

        engine.record(make_trajectory("testing", Verdict::Failure)).await.unwrap();
        engine.record(make_trajectory("testing", Verdict::Failure)).await.unwrap();

        let patterns = engine.distill().await.unwrap();
        assert!(patterns.is_empty(), "Failures should not produce patterns");
    }

    #[tokio::test]
    async fn test_adapt_finds_similar_pattern() {
        let engine = SonaEngine::new(SonaMode::Balanced, std::sync::Arc::new(TfIdfEmbeddingProvider));

        // Record and distill
        for _ in 0..3 {
            let mut traj = make_trajectory("security", Verdict::Success);
            traj.steps[0].input = "scan for SQL injection vulnerabilities in the codebase".to_string();
            engine.record(traj).await.unwrap();
        }
        engine.distill().await.unwrap();

        // Adapt should find the pattern
        let result = engine.adapt("check for SQL injection security issues").await.unwrap();
        assert!(result.is_some(), "Should find a matching pattern");
        let pattern = result.unwrap();
        assert_eq!(pattern.domain, "security");
        assert!(pattern.confidence > 0.0);
    }

    #[tokio::test]
    async fn test_adapt_no_match_below_threshold() {
        let engine = SonaEngine::new(SonaMode::Balanced, std::sync::Arc::new(TfIdfEmbeddingProvider));

        // No patterns learned
        let result = engine.adapt("completely unrelated query about cooking").await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_capacity_limit() {
        let engine = SonaEngine::new(SonaMode::Edge, std::sync::Arc::new(TfIdfEmbeddingProvider));
        // Edge mode: max 50 trajectories

        for i in 0..55 {
            let mut traj = make_trajectory("testing", Verdict::Success);
            traj.id = format!("traj-{}", i);
            engine.record(traj).await.unwrap();
        }

        let (count, _) = engine.counts();
        assert!(count <= 50, "Should not exceed capacity: got {}", count);
    }

    #[test]
    fn test_trajectory_total_duration() {
        let traj = Trajectory::new(
            vec![
                make_step("a", "b"),
                make_step("c", "d"),
            ],
            Verdict::Success,
            "testing",
        );
        assert_eq!(traj.total_duration_ms(), 20);
    }

    #[test]
    fn test_trajectory_avg_confidence() {
        let traj = Trajectory::new(
            vec![
                TrajectoryStep { input: "a".into(), output: "b".into(), duration_ms: 10, confidence: 0.8 },
                TrajectoryStep { input: "c".into(), output: "d".into(), duration_ms: 10, confidence: 0.6 },
            ],
            Verdict::Success,
            "testing",
        );
        assert!((traj.avg_confidence() - 0.7).abs() < 0.01);
    }

    #[test]
    fn test_sona_mode_default() {
        assert_eq!(SonaMode::default(), SonaMode::Balanced);
    }
}