aingle_ai 0.7.1

AI integration layer for AIngle - Ineru, Nested Learning, Kaneru
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
// Copyright 2019-2026 Apilium Technologies OÜ. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR Commercial

//! # Kaneru Agent Layer
//!
//! Unified Multi-Agent Execution System - Self-modifying nodes with continual learning.
//!
//! ## Components
//!
//! - **ContinuumMemory**: Non-discrete memory with smooth interpolation
//! - **SelfModifier**: Behavior modification with safety bounds
//! - **ContextLearner**: Infinite in-context learning without forgetting
//! - **AutoReconfigurator**: Resource-aware reconfiguration
//!
//! ## Safety
//!
//! Kaneru agents have strict safety bounds that prevent:
//! - Modification of cryptographic code
//! - Modification of consensus rules
//! - Modification of identity handling
//!
//! ## Example
//!
//! ```rust,no_run
//! use aingle_ai::kaneru::{KaneruAgent, KaneruConfig};
//!
//! let config = KaneruConfig::default();
//! let mut agent = KaneruAgent::new(config);
//!
//! // Process experience
//! // agent.process_experience(&experience);
//! ```

mod config;
mod context_learner;
mod continuum_memory;
mod reconfigurator;
mod self_modifier;

pub use config::KaneruConfig;
pub use context_learner::ContextLearner;
pub use continuum_memory::ContinuumMemory;
pub use reconfigurator::{AutoReconfigurator, NodeConfig};
pub use self_modifier::{BehaviorRule, SafetyBounds, SelfModifier};

use crate::error::AiResult;
use crate::types::ResourceCategory;
use parking_lot::RwLock;
use std::sync::Arc;
use tracing::{debug, info};

/// Kaneru Agent: Self-modifying node with continual learning
pub struct KaneruAgent {
    /// Continuum memory (non-discrete)
    memory: Arc<RwLock<ContinuumMemory>>,

    /// Self-modification capabilities
    modifier: Arc<RwLock<SelfModifier>>,

    /// Infinite context learning
    context_learner: Arc<RwLock<ContextLearner>>,

    /// Resource-aware reconfiguration
    reconfigurator: Arc<RwLock<AutoReconfigurator>>,

    /// Configuration
    config: KaneruConfig,

    /// Agent state
    state: AgentState,
}

impl KaneruAgent {
    /// Create a new Kaneru agent
    pub fn new(config: KaneruConfig) -> Self {
        Self {
            memory: Arc::new(RwLock::new(ContinuumMemory::new(config.memory_dim))),
            modifier: Arc::new(RwLock::new(SelfModifier::new(&config))),
            context_learner: Arc::new(RwLock::new(ContextLearner::new(config.context_capacity))),
            reconfigurator: Arc::new(RwLock::new(AutoReconfigurator::new())),
            config,
            state: AgentState::default(),
        }
    }

    /// Process an experience (learn from it)
    pub fn process_experience(&mut self, experience: &Experience) -> AiResult<ExperienceResult> {
        debug!(experience_type = ?experience.experience_type, "Processing experience");

        // 1. Store in continuum memory
        {
            let mut mem = self.memory.write();
            mem.store(experience);
        }

        // 2. Update context learner
        {
            let mut cl = self.context_learner.write();
            cl.learn(&Context {
                data: experience.data.clone(),
                timestamp: experience.timestamp,
                relevance: 1.0,
            });
        }

        // 3. Check if self-modification is warranted
        let modification_applied = if self.config.self_modification_enabled {
            let mut modifier = self.modifier.write();
            let outcome = Outcome {
                success: experience.success,
                reward: experience.reward,
            };
            modifier.evolve(&outcome)
        } else {
            false
        };

        // 4. Update state
        self.state.experiences_processed += 1;
        if modification_applied {
            self.state.modifications_applied += 1;
        }

        Ok(ExperienceResult {
            stored: true,
            modification_applied,
            current_rules: self.get_behavior_rules().len(),
        })
    }

    /// Query memory with context
    pub fn query(&self, query: &Query) -> QueryResult {
        // Get from continuum memory
        let memory_result = {
            let mem = self.memory.read();
            mem.retrieve(query)
        };

        // Get relevant context
        let contexts = {
            let cl = self.context_learner.read();
            cl.query_with_context(query)
        };

        QueryResult {
            memory_matches: memory_result,
            relevant_contexts: contexts,
        }
    }

    /// Check and apply resource-based reconfiguration
    pub fn check_reconfiguration(&mut self, resources: &Resources) -> ReconfigResult {
        let category = resources.category();

        let result = {
            let mut reconf = self.reconfigurator.write();
            reconf.reconfigure(category)
        };

        if let ReconfigResult::Changed(ref new_config) = result {
            info!(
                mode = ?new_config.mode,
                "Kaneru Agent reconfigured"
            );
            self.apply_node_config(new_config);
        }

        result
    }

    /// Get current behavior rules
    pub fn get_behavior_rules(&self) -> Vec<BehaviorRule> {
        let modifier = self.modifier.read();
        modifier.get_rules()
    }

    /// Get agent statistics
    pub fn stats(&self) -> AgentStats {
        let mem = self.memory.read();
        let cl = self.context_learner.read();
        let modifier = self.modifier.read();

        AgentStats {
            state: self.state.clone(),
            memory_size: mem.len(),
            context_size: cl.len(),
            rule_count: modifier.rule_count(),
            safety_violations: modifier.safety_violation_count(),
        }
    }

    /// Apply node configuration changes
    fn apply_node_config(&mut self, config: &NodeConfig) {
        // Adjust memory capacity if needed
        if config.mode == PowerMode::Critical {
            // Compress memory for critical mode
            let mut mem = self.memory.write();
            mem.compress();
        }
    }
}

/// Experience data for learning
#[derive(Debug, Clone)]
pub struct Experience {
    /// Unique identifier
    pub id: [u8; 32],
    /// Experience type
    pub experience_type: ExperienceType,
    /// Raw data
    pub data: Vec<u8>,
    /// Timestamp
    pub timestamp: u64,
    /// Was this experience successful?
    pub success: bool,
    /// Reward value (-1.0 to 1.0)
    pub reward: f32,
}

/// Type of experience
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExperienceType {
    /// Transaction validation
    Validation,
    /// Network communication
    Network,
    /// Storage operation
    Storage,
    /// Consensus participation
    Consensus,
}

/// Query for memory/context retrieval
#[derive(Debug, Clone)]
pub struct Query {
    /// Query data
    pub data: Vec<u8>,
    /// Maximum results
    pub limit: usize,
}

/// Outcome of an action
#[derive(Debug, Clone)]
pub struct Outcome {
    /// Was it successful?
    pub success: bool,
    /// Reward value
    pub reward: f32,
}

/// Context for learning
#[derive(Debug, Clone)]
pub struct Context {
    /// Context data
    pub data: Vec<u8>,
    /// When this context was recorded
    pub timestamp: u64,
    /// Current relevance (decays over time)
    pub relevance: f32,
}

/// Resource information
#[derive(Debug, Clone)]
pub struct Resources {
    /// Available memory in bytes
    pub memory_available: usize,
    /// CPU usage (0.0 - 1.0)
    pub cpu_usage: f32,
    /// Battery level (0.0 - 1.0, if applicable)
    pub battery_level: Option<f32>,
}

impl Resources {
    /// Categorize resource availability
    pub fn category(&self) -> ResourceCategory {
        if let Some(battery) = self.battery_level {
            if battery < 0.1 {
                return ResourceCategory::Critical;
            }
            if battery < 0.3 {
                return ResourceCategory::Limited;
            }
        }

        if self.memory_available < 10 * 1024 * 1024 {
            // < 10MB
            return ResourceCategory::Critical;
        }
        if self.memory_available < 100 * 1024 * 1024 {
            // < 100MB
            return ResourceCategory::Limited;
        }
        if self.cpu_usage > 0.9 {
            return ResourceCategory::Limited;
        }
        if self.memory_available > 1024 * 1024 * 1024 {
            // > 1GB
            return ResourceCategory::Abundant;
        }

        ResourceCategory::Normal
    }
}

/// Agent state
#[derive(Debug, Clone, Default)]
pub struct AgentState {
    /// Number of experiences processed
    pub experiences_processed: u64,
    /// Number of modifications applied
    pub modifications_applied: u64,
}

/// Result of experience processing
#[derive(Debug, Clone)]
pub struct ExperienceResult {
    /// Was the experience stored?
    pub stored: bool,
    /// Was a behavior modification applied?
    pub modification_applied: bool,
    /// Current number of behavior rules
    pub current_rules: usize,
}

/// Result of a query
#[derive(Debug, Clone)]
pub struct QueryResult {
    /// Matches from memory
    pub memory_matches: Vec<MemoryResult>,
    /// Relevant historical contexts
    pub relevant_contexts: Vec<Context>,
}

/// Memory query result
#[derive(Debug, Clone)]
pub struct MemoryResult {
    /// Experience ID
    pub id: [u8; 32],
    /// Similarity score
    pub similarity: f32,
    /// Retrieved data
    pub data: Vec<u8>,
}

/// Power mode for node configuration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PowerMode {
    /// Full power
    Full,
    /// Balanced
    Balanced,
    /// Low power
    Low,
    /// Critical (minimal)
    Critical,
}

/// Reconfiguration result
#[derive(Debug, Clone)]
pub enum ReconfigResult {
    /// No change needed
    NoChange,
    /// Configuration changed
    Changed(NodeConfig),
}

/// Agent statistics
#[derive(Debug, Clone)]
pub struct AgentStats {
    /// Current state
    pub state: AgentState,
    /// Memory size
    pub memory_size: usize,
    /// Context size
    pub context_size: usize,
    /// Number of behavior rules
    pub rule_count: usize,
    /// Safety violations (blocked modifications)
    pub safety_violations: usize,
}

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

    fn make_experience(id: u8) -> Experience {
        Experience {
            id: [id; 32],
            experience_type: ExperienceType::Validation,
            data: vec![id; 10],
            timestamp: 1702656000000,
            success: true,
            reward: 0.5,
        }
    }

    #[test]
    fn test_kaneru_agent_basic() {
        let config = KaneruConfig::default();
        let mut agent = KaneruAgent::new(config);

        let exp = make_experience(1);
        let result = agent.process_experience(&exp).unwrap();

        assert!(result.stored);
    }

    #[test]
    fn test_kaneru_agent_query() {
        let config = KaneruConfig::default();
        let mut agent = KaneruAgent::new(config);

        // Add some experiences
        for i in 0..5 {
            let exp = make_experience(i);
            agent.process_experience(&exp).unwrap();
        }

        // Query
        let query = Query {
            data: vec![2; 10],
            limit: 3,
        };
        let result = agent.query(&query);

        // Should have some results
        assert!(result.relevant_contexts.len() > 0 || result.memory_matches.len() >= 0);
    }

    #[test]
    fn test_resource_categorization() {
        let abundant = Resources {
            memory_available: 2 * 1024 * 1024 * 1024, // 2GB
            cpu_usage: 0.3,
            battery_level: Some(0.9),
        };
        assert_eq!(abundant.category(), ResourceCategory::Abundant);

        let critical = Resources {
            memory_available: 5 * 1024 * 1024, // 5MB
            cpu_usage: 0.9,
            battery_level: Some(0.05),
        };
        assert_eq!(critical.category(), ResourceCategory::Critical);
    }

    #[test]
    fn test_reconfiguration() {
        let config = KaneruConfig::default();
        let mut agent = KaneruAgent::new(config);

        let resources = Resources {
            memory_available: 5 * 1024 * 1024, // 5MB - Critical
            cpu_usage: 0.9,
            battery_level: Some(0.05),
        };

        let result = agent.check_reconfiguration(&resources);
        // Should trigger reconfiguration for critical resources
        matches!(result, ReconfigResult::Changed(_));
    }
}