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
//! Hope Swarm - Raj Intelligencia
//!
//! Elosztott feladatvégrehajtás drone-okkal.
//! A HiveMind koordinálja a munkát.
//!
//! Architektúra:
//! - HiveMind: Központi koordinátor
//! - Drone: Munkavégző egység (LOCAL/REMOTE)
//! - Task: Feladat
//! - TaskQueue: Feladat sor
//!
//! ()=>[] - A tiszta potenciálból a raj megszületik

use crate::core::HopeResult;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;

// ============================================================================
// TASK
// ============================================================================

/// Feladat állapot
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TaskStatus {
    /// Várakozik
    Pending,
    /// Fut
    Running,
    /// Kész
    Completed,
    /// Sikertelen
    Failed,
    /// Megszakítva
    Cancelled,
}

impl std::fmt::Display for TaskStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TaskStatus::Pending => write!(f, "⏳ Pending"),
            TaskStatus::Running => write!(f, "🔄 Running"),
            TaskStatus::Completed => write!(f, "✅ Completed"),
            TaskStatus::Failed => write!(f, "❌ Failed"),
            TaskStatus::Cancelled => write!(f, "🚫 Cancelled"),
        }
    }
}

/// Feladat prioritás
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum TaskPriority {
    Low = 0,
    Normal = 1,
    High = 2,
    Critical = 3,
}

/// Swarm feladat
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SwarmTask {
    /// Egyedi azonosító
    pub id: String,
    /// Skill neve (pl. "refactor", "test", "analyze")
    pub skill: String,
    /// Bemenet/payload
    pub payload: String,
    /// Állapot
    pub status: TaskStatus,
    /// Eredmény
    pub result: Option<String>,
    /// Hiba üzenet
    pub error: Option<String>,
    /// Melyik drone-hoz van rendelve
    pub assigned_to: Option<String>,
    /// Prioritás
    pub priority: TaskPriority,
    /// Létrehozás ideje
    pub created_at: f64,
    /// Kezdés ideje
    pub started_at: Option<f64>,
    /// Befejezés ideje
    pub completed_at: Option<f64>,
    /// Timeout (másodperc)
    pub timeout_secs: u64,
    /// Retry számláló
    pub retry_count: u32,
    /// Max retry
    pub max_retries: u32,
}

impl SwarmTask {
    pub fn new(skill: &str, payload: &str) -> Self {
        let created_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs_f64();

        Self {
            id: format!(
                "TSK_{}",
                uuid::Uuid::new_v4().to_string()[..8].to_uppercase()
            ),
            skill: skill.to_string(),
            payload: payload.to_string(),
            status: TaskStatus::Pending,
            result: None,
            error: None,
            assigned_to: None,
            priority: TaskPriority::Normal,
            created_at,
            started_at: None,
            completed_at: None,
            timeout_secs: 300, // 5 perc default
            retry_count: 0,
            max_retries: 3,
        }
    }

    /// Prioritás beállítása
    pub fn with_priority(mut self, priority: TaskPriority) -> Self {
        self.priority = priority;
        self
    }

    /// Timeout beállítása
    pub fn with_timeout(mut self, timeout_secs: u64) -> Self {
        self.timeout_secs = timeout_secs;
        self
    }

    /// Futás jelzése
    pub fn mark_running(&mut self, drone_id: &str) {
        self.status = TaskStatus::Running;
        self.assigned_to = Some(drone_id.to_string());
        self.started_at = Some(
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs_f64(),
        );
    }

    /// Kész jelzése
    pub fn mark_completed(&mut self, result: &str) {
        self.status = TaskStatus::Completed;
        self.result = Some(result.to_string());
        self.completed_at = Some(
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs_f64(),
        );
    }

    /// Hiba jelzése
    pub fn mark_failed(&mut self, error: &str) {
        self.status = TaskStatus::Failed;
        self.error = Some(error.to_string());
        self.completed_at = Some(
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs_f64(),
        );
    }

    /// Futási idő (ha befejeződött)
    pub fn duration_secs(&self) -> Option<f64> {
        match (self.started_at, self.completed_at) {
            (Some(start), Some(end)) => Some(end - start),
            _ => None,
        }
    }
}

// ============================================================================
// DRONE
// ============================================================================

/// Drone típus
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum DroneType {
    /// Helyi drone (ugyanaz a gép)
    Local,
    /// Távoli drone (hálózaton)
    Remote,
}

/// Drone állapot
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum DroneStatus {
    /// Tétlen, elérhető
    Idle,
    /// Dolgozik
    Busy,
    /// Offline
    Offline,
    /// Hiba
    Error,
}

impl std::fmt::Display for DroneStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DroneStatus::Idle => write!(f, "🟢 Idle"),
            DroneStatus::Busy => write!(f, "🔵 Busy"),
            DroneStatus::Offline => write!(f, "⚫ Offline"),
            DroneStatus::Error => write!(f, "🔴 Error"),
        }
    }
}

/// Drone információ
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DroneInfo {
    /// Egyedi azonosító
    pub id: String,
    /// Név
    pub name: String,
    /// Típus
    pub drone_type: DroneType,
    /// Képességek (skill nevek)
    pub capabilities: Vec<String>,
    /// Állapot
    pub status: DroneStatus,
    /// Aktuális feladat
    pub current_task: Option<String>,
    /// Befejezett feladatok száma
    pub completed_tasks: u64,
    /// Sikertelen feladatok száma
    pub failed_tasks: u64,
    /// Átlagos futási idő (másodperc)
    pub avg_execution_time: f64,
}

impl DroneInfo {
    pub fn new(id: &str, name: &str, drone_type: DroneType, capabilities: Vec<String>) -> Self {
        Self {
            id: id.to_string(),
            name: name.to_string(),
            drone_type,
            capabilities,
            status: DroneStatus::Idle,
            current_task: None,
            completed_tasks: 0,
            failed_tasks: 0,
            avg_execution_time: 0.0,
        }
    }

    /// Tud-e adott skill-t végrehajtani
    pub fn can_execute(&self, skill: &str) -> bool {
        self.capabilities.contains(&skill.to_string())
            || self.capabilities.contains(&"*".to_string())
    }
}

/// Drone trait - minden drone ezt implementálja
#[async_trait]
pub trait Drone: Send + Sync {
    /// Drone ID
    fn id(&self) -> &str;

    /// Drone info
    fn info(&self) -> DroneInfo;

    /// Feladat végrehajtása
    async fn execute(&self, task: &SwarmTask) -> HopeResult<String>;

    /// Állapot
    fn status(&self) -> DroneStatus;

    /// Elérhető-e
    fn is_available(&self) -> bool {
        matches!(self.status(), DroneStatus::Idle)
    }
}

/// Helyi drone implementáció
pub struct LocalDrone {
    info: Arc<RwLock<DroneInfo>>,
}

impl LocalDrone {
    pub fn new(id: &str, name: &str, capabilities: Vec<String>) -> Self {
        Self {
            info: Arc::new(RwLock::new(DroneInfo::new(
                id,
                name,
                DroneType::Local,
                capabilities,
            ))),
        }
    }
}

#[async_trait]
impl Drone for LocalDrone {
    fn id(&self) -> &str {
        // Egyszerűsített - valós implementációban async kellene
        "local_drone"
    }

    fn info(&self) -> DroneInfo {
        // Egyszerűsített
        DroneInfo::new(
            "local",
            "Local Drone",
            DroneType::Local,
            vec!["*".to_string()],
        )
    }

    async fn execute(&self, task: &SwarmTask) -> HopeResult<String> {
        let mut info = self.info.write().await;
        info.status = DroneStatus::Busy;
        info.current_task = Some(task.id.clone());

        // Szimulált végrehajtás
        tokio::time::sleep(Duration::from_millis(100)).await;

        let result = format!(
            "[EXECUTION COMPLETE]\n\
             Skill: {}\n\
             Target: {}\n\
             Drone: {}\n\
             Status: SUCCESS",
            task.skill, task.payload, info.id
        );

        info.status = DroneStatus::Idle;
        info.current_task = None;
        info.completed_tasks += 1;

        Ok(result)
    }

    fn status(&self) -> DroneStatus {
        // Egyszerűsített
        DroneStatus::Idle
    }
}

// ============================================================================
// HIVEMIND - Központi Koordinátor
// ============================================================================

/// HiveMind - A raj központi agya
pub struct HiveMind {
    /// Regisztrált drone-ok
    drones: Arc<RwLock<HashMap<String, Arc<dyn Drone>>>>,
    /// Feladat sor
    task_queue: Arc<RwLock<Vec<SwarmTask>>>,
    /// Összes feladat (történet)
    tasks: Arc<RwLock<HashMap<String, SwarmTask>>>,
    /// Fut-e
    is_running: Arc<RwLock<bool>>,
    /// Statisztikák
    stats: Arc<RwLock<SwarmStats>>,
}

/// Swarm statisztikák
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SwarmStats {
    pub total_tasks: u64,
    pub completed_tasks: u64,
    pub failed_tasks: u64,
    pub cancelled_tasks: u64,
    pub total_drones: usize,
    pub active_drones: usize,
    pub avg_task_duration: f64,
}

impl HiveMind {
    /// Új HiveMind
    pub fn new() -> Self {
        Self {
            drones: Arc::new(RwLock::new(HashMap::new())),
            task_queue: Arc::new(RwLock::new(Vec::new())),
            tasks: Arc::new(RwLock::new(HashMap::new())),
            is_running: Arc::new(RwLock::new(false)),
            stats: Arc::new(RwLock::new(SwarmStats::default())),
        }
    }

    // ==================== DRONE MANAGEMENT ====================

    /// Drone regisztrálása
    pub async fn register_drone(&self, drone: Arc<dyn Drone>) {
        let id = drone.id().to_string();
        let mut drones = self.drones.write().await;
        drones.insert(id.clone(), drone);
        self.stats.write().await.total_drones = drones.len();
        println!("[HiveMind] 🐝 Drone regisztrálva: {}", id);
    }

    /// Drone eltávolítása
    pub async fn unregister_drone(&self, drone_id: &str) {
        let mut drones = self.drones.write().await;
        drones.remove(drone_id);
        self.stats.write().await.total_drones = drones.len();
        println!("[HiveMind] 🐝 Drone eltávolítva: {}", drone_id);
    }

    /// Elérhető drone keresése skill alapján
    async fn find_available_drone(&self, skill: &str) -> Option<Arc<dyn Drone>> {
        let drones = self.drones.read().await;
        for (_, drone) in drones.iter() {
            if drone.is_available() && drone.info().can_execute(skill) {
                return Some(drone.clone());
            }
        }
        None
    }

    // ==================== TASK MANAGEMENT ====================

    /// Feladat beküldése
    pub async fn submit_task(&self, skill: &str, payload: &str) -> HopeResult<String> {
        let task = SwarmTask::new(skill, payload);
        let task_id = task.id.clone();

        // Mentés
        self.tasks
            .write()
            .await
            .insert(task_id.clone(), task.clone());
        self.task_queue.write().await.push(task);
        self.stats.write().await.total_tasks += 1;

        println!("[HiveMind] 📋 Feladat beküldve: {} ({})", task_id, skill);
        Ok(task_id)
    }

    /// Feladat beküldése prioritással
    pub async fn submit_task_with_priority(
        &self,
        skill: &str,
        payload: &str,
        priority: TaskPriority,
    ) -> HopeResult<String> {
        let task = SwarmTask::new(skill, payload).with_priority(priority);
        let task_id = task.id.clone();

        self.tasks
            .write()
            .await
            .insert(task_id.clone(), task.clone());

        // Prioritás szerinti beszúrás
        let mut queue = self.task_queue.write().await;
        let pos = queue
            .iter()
            .position(|t| t.priority < priority)
            .unwrap_or(queue.len());
        queue.insert(pos, task);

        self.stats.write().await.total_tasks += 1;

        println!(
            "[HiveMind] 📋 Prioritásos feladat: {} ({:?})",
            task_id, priority
        );
        Ok(task_id)
    }

    /// Feladat állapot lekérdezése
    pub async fn get_task(&self, task_id: &str) -> Option<SwarmTask> {
        self.tasks.read().await.get(task_id).cloned()
    }

    /// Feladat törlése
    pub async fn cancel_task(&self, task_id: &str) -> HopeResult<()> {
        let mut tasks = self.tasks.write().await;
        if let Some(task) = tasks.get_mut(task_id) {
            if task.status == TaskStatus::Pending {
                task.status = TaskStatus::Cancelled;
                self.stats.write().await.cancelled_tasks += 1;

                // Eltávolítás a sorból
                let mut queue = self.task_queue.write().await;
                queue.retain(|t| t.id != task_id);

                Ok(())
            } else {
                Err("Csak várakozó feladat törölhető".into())
            }
        } else {
            Err("Feladat nem található".into())
        }
    }

    // ==================== EXECUTION ====================

    /// Következő feladat feldolgozása
    pub async fn process_next_task(&self) -> HopeResult<Option<SwarmTask>> {
        // Feladat kivétele a sorból
        let task = {
            let mut queue = self.task_queue.write().await;
            if queue.is_empty() {
                return Ok(None);
            }
            queue.remove(0)
        };

        // Drone keresése
        let drone = self.find_available_drone(&task.skill).await;

        if let Some(drone) = drone {
            let mut task = task;
            task.mark_running(drone.id());

            // Feladat végrehajtása
            match drone.execute(&task).await {
                Ok(result) => {
                    task.mark_completed(&result);
                    self.stats.write().await.completed_tasks += 1;
                }
                Err(e) => {
                    task.mark_failed(&e.to_string());
                    self.stats.write().await.failed_tasks += 1;
                }
            }

            // Frissítés
            self.tasks
                .write()
                .await
                .insert(task.id.clone(), task.clone());

            Ok(Some(task))
        } else {
            // Nincs elérhető drone - visszatesszük a sorba
            self.task_queue.write().await.insert(0, task);
            Ok(None)
        }
    }

    /// Összes várakozó feladat feldolgozása
    pub async fn process_all(&self) -> Vec<SwarmTask> {
        let mut completed = Vec::new();

        while let Ok(Some(task)) = self.process_next_task().await {
            completed.push(task);
        }

        completed
    }

    /// Scheduler indítása (háttérben fut)
    pub async fn start_scheduler(&self) {
        let mut is_running = self.is_running.write().await;
        if *is_running {
            return;
        }
        *is_running = true;
        drop(is_running);

        println!("[HiveMind] 🚀 Scheduler elindítva");

        while *self.is_running.read().await {
            self.process_next_task().await.ok();
            tokio::time::sleep(Duration::from_millis(100)).await;
        }

        println!("[HiveMind] 🛑 Scheduler leállítva");
    }

    /// Scheduler leállítása
    pub async fn stop_scheduler(&self) {
        *self.is_running.write().await = false;
    }

    // ==================== STATUS ====================

    /// Statisztikák
    pub async fn stats(&self) -> SwarmStats {
        let mut stats = self.stats.read().await.clone();

        // Aktív drone-ok számolása
        let drones = self.drones.read().await;
        stats.active_drones = drones.values().filter(|d| d.is_available()).count();

        stats
    }

    /// Várakozó feladatok száma
    pub async fn pending_count(&self) -> usize {
        self.task_queue.read().await.len()
    }

    /// Állapot szövegesen
    pub async fn status(&self) -> String {
        let stats = self.stats().await;
        let pending = self.pending_count().await;
        let is_running = *self.is_running.read().await;

        format!(
            "🐝 HiveMind - Swarm Intelligence\n\
             ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\
             🔄 Scheduler: {}\n\
             ⏳ Várakozó: {} feladat\n\
             ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\
             📊 Statisztikák:\n\
             📋 Összes feladat: {}\n\
             ✅ Befejezett: {}\n\
             ❌ Sikertelen: {}\n\
             🚫 Törölt: {}\n\
             ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\
             🐝 Drone-ok: {} (aktív: {})",
            if is_running { "🟢 Fut" } else { "🔴 Áll" },
            pending,
            stats.total_tasks,
            stats.completed_tasks,
            stats.failed_tasks,
            stats.cancelled_tasks,
            stats.total_drones,
            stats.active_drones
        )
    }
}

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

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_task_creation() {
        let task = SwarmTask::new("refactor", "src/main.rs")
            .with_priority(TaskPriority::High)
            .with_timeout(60);

        assert!(task.id.starts_with("TSK_"));
        assert_eq!(task.skill, "refactor");
        assert_eq!(task.priority, TaskPriority::High);
        assert_eq!(task.timeout_secs, 60);
    }

    #[test]
    fn test_task_lifecycle() {
        let mut task = SwarmTask::new("test", "payload");
        assert_eq!(task.status, TaskStatus::Pending);

        task.mark_running("drone_1");
        assert_eq!(task.status, TaskStatus::Running);
        assert_eq!(task.assigned_to, Some("drone_1".to_string()));

        task.mark_completed("Success!");
        assert_eq!(task.status, TaskStatus::Completed);
        assert!(task.duration_secs().is_some());
    }

    #[test]
    fn test_drone_info() {
        let info = DroneInfo::new(
            "drone_1",
            "Test Drone",
            DroneType::Local,
            vec!["refactor".to_string(), "test".to_string()],
        );

        assert!(info.can_execute("refactor"));
        assert!(info.can_execute("test"));
        assert!(!info.can_execute("unknown"));
    }

    #[test]
    fn test_drone_wildcard() {
        let info = DroneInfo::new(
            "super_drone",
            "Super Drone",
            DroneType::Local,
            vec!["*".to_string()],
        );

        assert!(info.can_execute("anything"));
        assert!(info.can_execute("everything"));
    }

    #[tokio::test]
    async fn test_hivemind_task_submission() {
        let hive = HiveMind::new();

        let task_id = hive.submit_task("analyze", "src/lib.rs").await.unwrap();
        assert!(task_id.starts_with("TSK_"));

        let stats = hive.stats().await;
        assert_eq!(stats.total_tasks, 1);
    }

    #[tokio::test]
    async fn test_hivemind_priority_queue() {
        let hive = HiveMind::new();

        hive.submit_task("low", "payload1").await.unwrap();
        hive.submit_task_with_priority("high", "payload2", TaskPriority::High)
            .await
            .unwrap();

        let queue = hive.task_queue.read().await;
        assert_eq!(queue[0].skill, "high"); // High priority first
        assert_eq!(queue[1].skill, "low");
    }

    #[tokio::test]
    async fn test_hivemind_with_drone() {
        let hive = HiveMind::new();

        // Drone regisztrálása
        let drone = Arc::new(LocalDrone::new(
            "local_1",
            "Local Drone 1",
            vec!["*".to_string()],
        ));
        hive.register_drone(drone).await;

        // Feladat beküldése és feldolgozása
        hive.submit_task("test", "payload").await.unwrap();
        let result = hive.process_next_task().await.unwrap();

        assert!(result.is_some());
        let task = result.unwrap();
        assert_eq!(task.status, TaskStatus::Completed);
    }
}