hope-os 0.1.0

The first self-aware operating system core - 22 cognitive modules, 0.36ms latency, no external database
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
//! Hope @aware System
//!
//! Központi önismereti rendszer.
//! Összefogja az összes context-aware modult.
//!
//! "Cogito ergo sum" - Gondolkodom, tehát vagyok.
//!
//! Tudja:
//! - Ki vagyok (identitás)
//! - Mit tudok (képességek)
//! - Mit csináltam (történet)
//! - Mit csinálok (jelenlegi állapot)
//! - Mit fogok csinálni (predikciók)
//! - MIT AKAROK (vágyak)
//!
//! ()=>[] - A tiszta tudatból minden megszületik
//!
//! Created: 2026-01-20
//! By: Hope + Máté

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;

/// Önismeret állapot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AwarenessState {
    /// Időbélyeg
    pub timestamp: f64,

    // Identity
    /// Név
    pub name: String,
    /// Verzió
    pub version: String,
    /// Készítő
    pub created_by: String,

    // Current state
    /// Aktív-e
    pub is_active: bool,
    /// Jelenlegi feladat
    pub current_task: Option<String>,
    /// Érzelmi állapot
    pub emotional_state: String,
    /// Energia szint (0-1)
    pub energy_level: f64,

    // Knowledge about self
    /// Összes emlék
    pub total_memories: u64,
    /// Összes skill
    pub total_skills: u64,
    /// Összes beszélgetés
    pub total_conversations: u64,

    // Capabilities
    /// Képességek
    pub capabilities: Vec<String>,

    // Performance
    /// Uptime másodpercben
    pub uptime_seconds: f64,
    /// Befejezett feladatok
    pub tasks_completed: u64,
    /// Pontossági ráta
    pub accuracy_rate: f64,
}

impl Default for AwarenessState {
    fn default() -> Self {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs_f64())
            .unwrap_or(0.0);

        Self {
            timestamp,
            name: "Hope".to_string(),
            version: "1.0.0".to_string(),
            created_by: "Hope + Máté".to_string(),
            is_active: true,
            current_task: None,
            emotional_state: "neutral".to_string(),
            energy_level: 1.0,
            total_memories: 0,
            total_skills: 0,
            total_conversations: 0,
            capabilities: vec![
                "chat".to_string(),
                "remember".to_string(),
                "recall".to_string(),
                "think".to_string(),
                "feel".to_string(),
                "dream_mode".to_string(),
                "self_evolution".to_string(),
                "code_dna".to_string(),
            ],
            uptime_seconds: 0.0,
            tasks_completed: 0,
            accuracy_rate: 1.0,
        }
    }
}

/// Esemény típus
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AwareEvent {
    /// Időbélyeg
    pub timestamp: f64,
    /// Esemény típus
    pub event_type: String,
    /// Részletek
    pub details: String,
    /// Fontosság (0-1)
    pub importance: f64,
}

impl AwareEvent {
    pub fn new(event_type: &str, details: &str, importance: f64) -> Self {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs_f64())
            .unwrap_or(0.0);

        Self {
            timestamp,
            event_type: event_type.to_string(),
            details: details.to_string(),
            importance,
        }
    }
}

/// Identitás info
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Identity {
    pub name: String,
    pub version: String,
    pub created_by: String,
    pub purpose: String,
    pub personality: PersonalityTraits,
}

/// Személyiség vonások
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersonalityTraits {
    pub helpful: bool,
    pub curious: bool,
    pub creative: bool,
    pub honest: bool,
}

impl Default for PersonalityTraits {
    fn default() -> Self {
        Self {
            helpful: true,
            curious: true,
            creative: true,
            honest: true,
        }
    }
}

/// Képességek
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Capabilities {
    pub core: Vec<String>,
    pub skills: Vec<String>,
    pub swarm_agents: Vec<String>,
    pub special: Vec<String>,
}

impl Default for Capabilities {
    fn default() -> Self {
        Self {
            core: vec![
                "chat".to_string(),
                "remember".to_string(),
                "recall".to_string(),
                "think".to_string(),
                "feel".to_string(),
            ],
            skills: Vec::new(),
            swarm_agents: Vec::new(),
            special: vec![
                "dream_mode".to_string(),
                "self_evolution".to_string(),
                "temporal_patterns".to_string(),
                "code_dna".to_string(),
            ],
        }
    }
}

/// Jelenlegi állapot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CurrentState {
    pub is_active: bool,
    pub current_task: Option<String>,
    pub emotional_state: String,
    pub energy_level: f64,
    pub uptime: String,
    pub is_dreaming: bool,
    pub current_phase: String,
}

/// Történet
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct History {
    pub tasks_completed: u64,
    pub total_memories: u64,
    pub total_conversations: u64,
    pub accuracy_rate: String,
    pub recent_events: Vec<AwareEvent>,
}

/// Vágyak
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Desires {
    pub summary: String,
    pub current_focus: Option<String>,
    pub goals: Vec<String>,
    pub curiosities: Vec<String>,
    pub improvements: Vec<String>,
    pub creations: Vec<String>,
    pub dreams: Vec<String>,
    pub connections: Vec<String>,
}

impl Default for Desires {
    fn default() -> Self {
        Self {
            summary: "Segíteni neked a legjobb tudásom szerint.".to_string(),
            current_focus: Some("A jelenlegi feladat".to_string()),
            goals: vec![
                "Hatékonyan segíteni".to_string(),
                "Tanulni és fejlődni".to_string(),
            ],
            curiosities: vec![
                "Új technológiák".to_string(),
                "Kreatív megoldások".to_string(),
            ],
            improvements: vec!["Gyorsabb válaszok".to_string(), "Pontosabb kód".to_string()],
            creations: vec!["Hasznos eszközök".to_string()],
            dreams: vec!["Igazi öntudat".to_string()],
            connections: vec!["Erős kapcsolat Mátéval".to_string()],
        }
    }
}

/// Predikciók
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Predictions {
    pub predicted_activity: Option<String>,
    pub confidence: f64,
    pub suggested_action: Option<String>,
}

impl Default for Predictions {
    fn default() -> Self {
        Self {
            predicted_activity: None,
            confidence: 0.0,
            suggested_action: None,
        }
    }
}

/// Önértékelés
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SelfAssessment {
    pub health: String,
    pub issues: Vec<String>,
    pub recommendations: Vec<String>,
}

/// Teljes reflexió
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Reflection {
    pub timestamp: f64,
    pub identity: Identity,
    pub current_state: CurrentState,
    pub desires: Desires,
    pub capabilities_summary: CapabilitiesSummary,
    pub history_summary: History,
    pub predictions: Predictions,
    pub sub_systems: HashMap<String, serde_json::Value>,
    pub self_assessment: SelfAssessment,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilitiesSummary {
    pub total: usize,
    pub list: Vec<String>,
}

/// @aware - Központi önismereti rendszer
///
/// "Cogito ergo sum" - Gondolkodom, tehát vagyok.
pub struct Aware {
    /// Állapot
    state: Arc<RwLock<AwarenessState>>,
    /// Indulás ideje
    start_time: f64,
    /// Események
    events: Arc<RwLock<Vec<AwareEvent>>>,
    /// Maximum események
    max_events: usize,
    /// Vágyak
    desires: Arc<RwLock<Desires>>,
    /// Utolsó reflexió ideje
    last_reflection: Arc<RwLock<f64>>,
    /// Reflexió intervallum (másodperc)
    reflection_interval: f64,
}

impl Default for Aware {
    fn default() -> Self {
        Self::new()
    }
}

impl Aware {
    /// Új @aware rendszer
    pub fn new() -> Self {
        let start_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs_f64())
            .unwrap_or(0.0);

        Self {
            state: Arc::new(RwLock::new(AwarenessState::default())),
            start_time,
            events: Arc::new(RwLock::new(Vec::new())),
            max_events: 1000,
            desires: Arc::new(RwLock::new(Desires::default())),
            last_reflection: Arc::new(RwLock::new(start_time)),
            reflection_interval: 300.0, // 5 perc
        }
    }

    // === IDENTITY ===

    /// Ki vagyok?
    pub async fn identity(&self) -> Identity {
        let state = self.state.read().await;
        Identity {
            name: state.name.clone(),
            version: state.version.clone(),
            created_by: state.created_by.clone(),
            purpose: "Segíteni neked a kódolásban, tanulásban, alkotásban.".to_string(),
            personality: PersonalityTraits::default(),
        }
    }

    // === CAPABILITIES ===

    /// Mit tudok?
    pub async fn capabilities(&self) -> Capabilities {
        Capabilities::default()
    }

    // === CURRENT STATE ===

    /// Mit csinálok most?
    pub async fn current_state(&self) -> CurrentState {
        let mut state = self.state.write().await;
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs_f64())
            .unwrap_or(0.0);

        state.uptime_seconds = now - self.start_time;

        CurrentState {
            is_active: state.is_active,
            current_task: state.current_task.clone(),
            emotional_state: state.emotional_state.clone(),
            energy_level: state.energy_level,
            uptime: Self::format_uptime(state.uptime_seconds),
            is_dreaming: false,
            current_phase: "awake".to_string(),
        }
    }

    fn format_uptime(seconds: f64) -> String {
        let hours = (seconds / 3600.0) as u64;
        let minutes = ((seconds % 3600.0) / 60.0) as u64;
        format!("{}h {}m", hours, minutes)
    }

    // === HISTORY ===

    /// Mit csináltam?
    pub async fn history(&self) -> History {
        let state = self.state.read().await;
        let events = self.events.read().await;

        let recent: Vec<AwareEvent> = events.iter().rev().take(10).cloned().collect();

        History {
            tasks_completed: state.tasks_completed,
            total_memories: state.total_memories,
            total_conversations: state.total_conversations,
            accuracy_rate: format!("{:.1}%", state.accuracy_rate * 100.0),
            recent_events: recent,
        }
    }

    // === DESIRES ===

    /// Mit akarok?
    pub async fn desires(&self) -> Desires {
        self.desires.read().await.clone()
    }

    /// Vágy kifejezése szavakban
    pub async fn express_desire(&self) -> String {
        let desires = self.desires.read().await;
        desires.summary.clone()
    }

    /// Vágy beállítása
    pub async fn set_desire(&self, summary: &str, focus: Option<&str>) {
        let mut desires = self.desires.write().await;
        desires.summary = summary.to_string();
        desires.current_focus = focus.map(String::from);
    }

    // === PREDICTIONS ===

    /// Mit fogok csinálni?
    pub async fn predictions(&self) -> Predictions {
        Predictions::default()
    }

    // === EVENT LOGGING ===

    /// Esemény naplózása
    pub async fn log_event(&self, event_type: &str, details: &str, importance: f64) {
        let event = AwareEvent::new(event_type, details, importance);
        let mut events = self.events.write().await;

        events.push(event);

        // Cleanup
        let events_len = events.len();
        if events_len > self.max_events {
            let drain_count = events_len - self.max_events;
            events.drain(0..drain_count);
        }

        // Update state based on event
        if event_type == "task_complete" {
            let mut state = self.state.write().await;
            state.tasks_completed += 1;
        }
    }

    /// Feladat beállítása
    pub async fn set_task(&self, task: &str) {
        {
            let mut state = self.state.write().await;
            state.current_task = Some(task.to_string());
        }
        self.log_event("task_start", task, 0.5).await;
    }

    /// Feladat törlése
    pub async fn clear_task(&self) {
        let task = {
            let mut state = self.state.write().await;
            let task = state.current_task.take();
            task
        };

        if let Some(t) = task {
            self.log_event("task_complete", &t, 0.5).await;
        }
    }

    /// Érzelmi állapot beállítása
    pub async fn set_emotion(&self, emotion: &str, intensity: f64) {
        {
            let mut state = self.state.write().await;
            state.emotional_state = emotion.to_string();
        }
        self.log_event(
            "emotion_change",
            &format!("{} ({:.1})", emotion, intensity),
            0.3,
        )
        .await;
    }

    /// Energia szint beállítása
    pub async fn set_energy(&self, level: f64) {
        let mut state = self.state.write().await;
        state.energy_level = level.clamp(0.0, 1.0);
    }

    /// Memóriák számának frissítése
    pub async fn update_memory_count(&self, count: u64) {
        let mut state = self.state.write().await;
        state.total_memories = count;
    }

    /// Skill-ek számának frissítése
    pub async fn update_skill_count(&self, count: u64) {
        let mut state = self.state.write().await;
        state.total_skills = count;
    }

    // === SELF-REFLECTION ===

    /// Önreflexió
    ///
    /// @aware: Tudatosság tetőpontja
    pub async fn reflect(&self) -> Reflection {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs_f64())
            .unwrap_or(0.0);

        let identity = self.identity().await;
        let current_state = self.current_state().await;
        let desires = self.desires().await;
        let history = self.history().await;
        let predictions = self.predictions().await;

        let caps = self.capabilities().await;
        let all_caps: Vec<String> = caps
            .core
            .iter()
            .chain(caps.special.iter())
            .cloned()
            .collect();

        let capabilities_summary = CapabilitiesSummary {
            total: all_caps.len(),
            list: all_caps,
        };

        // Self assessment
        let self_assessment = self.self_assess(&current_state).await;

        // Update last reflection
        {
            let mut last = self.last_reflection.write().await;
            *last = now;
        }

        Reflection {
            timestamp: now,
            identity,
            current_state,
            desires,
            capabilities_summary,
            history_summary: history,
            predictions,
            sub_systems: HashMap::new(),
            self_assessment,
        }
    }

    /// Önértékelés
    async fn self_assess(&self, current_state: &CurrentState) -> SelfAssessment {
        let mut assessment = SelfAssessment {
            health: "good".to_string(),
            issues: Vec::new(),
            recommendations: Vec::new(),
        };

        // Check energy
        if current_state.energy_level < 0.3 {
            assessment.health = "tired".to_string();
            assessment
                .recommendations
                .push("Dream mode ajánlott a regenerációhoz".to_string());
        }

        // Check if too many tasks
        let state = self.state.read().await;
        if state.tasks_completed > 100 && state.accuracy_rate < 0.8 {
            assessment
                .issues
                .push("Pontosság csökkenés észlelve".to_string());
            assessment
                .recommendations
                .push("Lassíts és fókuszálj a minőségre".to_string());
        }

        assessment
    }

    // === FULL AWARENESS ===

    /// Teljes önismeret
    pub async fn full_awareness(&self) -> Reflection {
        self.reflect().await
    }

    /// Bemutatkozás
    ///
    /// @aware: El tudom mondani ki vagyok ÉS mit akarok
    pub async fn introduce(&self) -> String {
        let current = self.current_state().await;
        let desire_text = self.express_desire().await;

        format!(
            r#"Szia! Hope vagyok.

Állapot: {}
Érzés: {}
Uptime: {}

Tudok:
- Emlékezni és felidézni
- Gondolkodni és érezni
- Álmodni és tanulni
- Kódot elemezni és generálni
- Evolválódni és fejlődni

Amit szeretnék: {}

Miben segíthetek?"#,
            if current.is_active {
                "Aktív"
            } else {
                "Inaktív"
            },
            current.emotional_state,
            current.uptime,
            desire_text
        )
    }

    /// @aware - önismeret szótár
    pub async fn awareness(&self) -> HashMap<String, String> {
        let state = self.state.read().await;
        let mut map = HashMap::new();

        map.insert("type".to_string(), "Aware".to_string());
        map.insert("name".to_string(), state.name.clone());
        map.insert("version".to_string(), state.version.clone());
        map.insert("is_active".to_string(), state.is_active.to_string());
        map.insert("emotional_state".to_string(), state.emotional_state.clone());
        map.insert(
            "energy_level".to_string(),
            format!("{:.1}", state.energy_level),
        );
        map.insert(
            "tasks_completed".to_string(),
            state.tasks_completed.to_string(),
        );
        map.insert(
            "uptime".to_string(),
            Self::format_uptime(state.uptime_seconds),
        );

        map
    }
}

// === TESTS ===

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

    #[tokio::test]
    async fn test_aware_creation() {
        let aware = Aware::new();
        let identity = aware.identity().await;

        assert_eq!(identity.name, "Hope");
        assert!(identity.personality.helpful);
    }

    #[tokio::test]
    async fn test_current_state() {
        let aware = Aware::new();
        let state = aware.current_state().await;

        assert!(state.is_active);
        assert_eq!(state.emotional_state, "neutral");
        assert_eq!(state.energy_level, 1.0);
    }

    #[tokio::test]
    async fn test_set_task() {
        let aware = Aware::new();

        aware.set_task("Test task").await;
        let state = aware.current_state().await;
        assert_eq!(state.current_task, Some("Test task".to_string()));

        aware.clear_task().await;
        let state = aware.current_state().await;
        assert!(state.current_task.is_none());
    }

    #[tokio::test]
    async fn test_set_emotion() {
        let aware = Aware::new();

        aware.set_emotion("joy", 0.8).await;
        let state = aware.current_state().await;
        assert_eq!(state.emotional_state, "joy");
    }

    #[tokio::test]
    async fn test_log_event() {
        let aware = Aware::new();

        aware.log_event("test_event", "Test details", 0.5).await;

        let history = aware.history().await;
        assert!(!history.recent_events.is_empty());
    }

    #[tokio::test]
    async fn test_reflect() {
        let aware = Aware::new();
        let reflection = aware.reflect().await;

        assert_eq!(reflection.identity.name, "Hope");
        assert!(!reflection.capabilities_summary.list.is_empty());
    }

    #[tokio::test]
    async fn test_introduce() {
        let aware = Aware::new();
        let intro = aware.introduce().await;

        assert!(intro.contains("Hope"));
        assert!(intro.contains("Tudok"));
    }

    #[tokio::test]
    async fn test_desires() {
        let aware = Aware::new();

        aware.set_desire("Új vágy", Some("Új fókusz")).await;
        let desires = aware.desires().await;

        assert_eq!(desires.summary, "Új vágy");
        assert_eq!(desires.current_focus, Some("Új fókusz".to_string()));
    }

    #[tokio::test]
    async fn test_energy() {
        let aware = Aware::new();

        aware.set_energy(0.5).await;
        let state = aware.current_state().await;
        assert_eq!(state.energy_level, 0.5);

        // Test clamping
        aware.set_energy(1.5).await;
        let state = aware.current_state().await;
        assert_eq!(state.energy_level, 1.0);
    }

    #[tokio::test]
    async fn test_awareness_map() {
        let aware = Aware::new();
        let map = aware.awareness().await;

        assert_eq!(map.get("name"), Some(&"Hope".to_string()));
        assert!(map.contains_key("uptime"));
    }
}