hope_agents 0.3.8

HOPE Agents: Hierarchical Optimizing Policy Engine for AIngle AI agents
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
//! Agent State Persistence.
//!
//! Provides mechanisms for serializing and deserializing agent state to enable:
//! - Saving an agent's state (including its learned knowledge) to disk.
//! - Loading an agent's state to resume operation.
//! - Transferring agents between different systems.
//! - Creating periodic checkpoints during long training sessions.
//!
//! ## Example
//!
//! ```rust,ignore
//! use hope_agents::{HopeAgent, AgentPersistence};
//! use std::path::Path;
//!
//! let mut agent = HopeAgent::with_default_config();
//!
//! // ... train the agent ...
//!
//! // Save to a file
//! agent.save_to_file(Path::new("agent_state.json")).unwrap();
//!
//! // Later, load from the file
//! let loaded_agent = HopeAgent::load_from_file(Path::new("agent_state.json")).unwrap();
//! ```

use crate::{HopeAgent, LearningConfig, LearningEngine};
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{Read, Write};
use std::path::Path;

/// Defines errors that can occur during agent state persistence operations.
#[derive(Debug)]
pub enum PersistenceError {
    /// An error occurred during file I/O.
    Io(std::io::Error),
    /// An error occurred while serializing the agent's state.
    Serialization(String),
    /// An error occurred while deserializing the agent's state.
    Deserialization(String),
    /// The persistence format is invalid or unsupported.
    InvalidFormat(String),
    /// An error occurred during compression or decompression.
    Compression(String),
}

impl std::fmt::Display for PersistenceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PersistenceError::Io(e) => write!(f, "IO error: {}", e),
            PersistenceError::Serialization(e) => write!(f, "Serialization error: {}", e),
            PersistenceError::Deserialization(e) => write!(f, "Deserialization error: {}", e),
            PersistenceError::InvalidFormat(e) => write!(f, "Invalid format: {}", e),
            PersistenceError::Compression(e) => write!(f, "Compression error: {}", e),
        }
    }
}

impl std::error::Error for PersistenceError {}

impl From<std::io::Error> for PersistenceError {
    fn from(e: std::io::Error) -> Self {
        PersistenceError::Io(e)
    }
}

impl From<serde_json::Error> for PersistenceError {
    fn from(e: serde_json::Error) -> Self {
        PersistenceError::Serialization(e.to_string())
    }
}

/// The serialization format for persisting agent state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PersistenceFormat {
    /// JSON format, which is human-readable.
    #[default]
    Json,
    /// A compact binary format. (Note: Currently falls back to JSON).
    Binary,
    /// The MessagePack format, which is efficient and compact. (Note: Currently falls back to JSON).
    MessagePack,
}

/// Options for configuring persistence operations.
#[derive(Debug, Clone)]
pub struct PersistenceOptions {
    /// The `PersistenceFormat` to use for serialization.
    pub format: PersistenceFormat,
    /// If `true`, pretty-prints JSON output to be more human-readable.
    pub pretty: bool,
    /// If `true`, compresses the output data.
    pub compress: bool,
}

impl Default for PersistenceOptions {
    fn default() -> Self {
        Self {
            format: PersistenceFormat::Json,
            pretty: true,
            compress: false,
        }
    }
}

impl PersistenceOptions {
    /// Returns options optimized for compact storage (binary, compressed).
    pub fn compact() -> Self {
        Self {
            format: PersistenceFormat::Binary,
            pretty: false,
            compress: true,
        }
    }

    /// Returns options optimized for human-readability (pretty-printed JSON).
    pub fn readable() -> Self {
        Self {
            format: PersistenceFormat::Json,
            pretty: true,
            compress: false,
        }
    }
}

/// A trait that provides methods for saving and loading an agent's state.
pub trait AgentPersistence: Sized {
    /// Saves the agent's state to a file using default options.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// agent.save_to_file(Path::new("agent.json"))?;
    /// ```
    fn save_to_file(&self, path: &Path) -> Result<(), PersistenceError>;

    /// Saves the agent's state to a file with custom `PersistenceOptions`.
    fn save_to_file_with_options(
        &self,
        path: &Path,
        options: &PersistenceOptions,
    ) -> Result<(), PersistenceError>;

    /// Loads an agent's state from a file using default options.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let agent = HopeAgent::load_from_file(Path::new("agent.json"))?;
    /// ```
    fn load_from_file(path: &Path) -> Result<Self, PersistenceError>;

    /// Loads an agent's state from a file with custom `PersistenceOptions`.
    fn load_from_file_with_options(
        path: &Path,
        options: &PersistenceOptions,
    ) -> Result<Self, PersistenceError>;

    /// Serializes the agent's state to a byte vector using default options.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let bytes = agent.to_bytes();
    /// ```
    fn to_bytes(&self) -> Vec<u8>;

    /// Serializes the agent's state to a byte vector with custom `PersistenceOptions`.
    fn to_bytes_with_options(
        &self,
        options: &PersistenceOptions,
    ) -> Result<Vec<u8>, PersistenceError>;

    /// Deserializes an agent's state from a byte slice using default options.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let agent = HopeAgent::from_bytes(&bytes)?;
    /// ```
    fn from_bytes(bytes: &[u8]) -> Result<Self, PersistenceError>;

    /// Deserializes an agent's state from a byte slice with custom `PersistenceOptions`.
    fn from_bytes_with_options(
        bytes: &[u8],
        options: &PersistenceOptions,
    ) -> Result<Self, PersistenceError>;
}

impl AgentPersistence for HopeAgent {
    fn save_to_file(&self, path: &Path) -> Result<(), PersistenceError> {
        self.save_to_file_with_options(path, &PersistenceOptions::default())
    }

    fn save_to_file_with_options(
        &self,
        path: &Path,
        options: &PersistenceOptions,
    ) -> Result<(), PersistenceError> {
        let state = self.save_state();
        let bytes = serialize_with_options(&state, options)?;

        let mut file = fs::File::create(path)?;
        file.write_all(&bytes)?;

        log::info!("Saved agent state to {:?}", path);
        Ok(())
    }

    fn load_from_file(path: &Path) -> Result<Self, PersistenceError> {
        Self::load_from_file_with_options(path, &PersistenceOptions::default())
    }

    fn load_from_file_with_options(
        path: &Path,
        options: &PersistenceOptions,
    ) -> Result<Self, PersistenceError> {
        let mut file = fs::File::open(path)?;
        let mut bytes = Vec::new();
        file.read_to_end(&mut bytes)?;

        let state: crate::hope_agent::SerializedState = deserialize_with_options(&bytes, options)?;

        let mut agent = HopeAgent::new(state.config.clone());
        agent.load_state(state);

        log::info!("Loaded agent state from {:?}", path);
        Ok(agent)
    }

    fn to_bytes(&self) -> Vec<u8> {
        self.to_bytes_with_options(&PersistenceOptions::default())
            .unwrap_or_default()
    }

    fn to_bytes_with_options(
        &self,
        options: &PersistenceOptions,
    ) -> Result<Vec<u8>, PersistenceError> {
        let state = self.save_state();
        serialize_with_options(&state, options)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, PersistenceError> {
        Self::from_bytes_with_options(bytes, &PersistenceOptions::default())
    }

    fn from_bytes_with_options(
        bytes: &[u8],
        options: &PersistenceOptions,
    ) -> Result<Self, PersistenceError> {
        let state: crate::hope_agent::SerializedState = deserialize_with_options(bytes, options)?;

        let mut agent = HopeAgent::new(state.config.clone());
        agent.load_state(state);

        Ok(agent)
    }
}

impl AgentPersistence for LearningEngine {
    fn save_to_file(&self, path: &Path) -> Result<(), PersistenceError> {
        self.save_to_file_with_options(path, &PersistenceOptions::default())
    }

    fn save_to_file_with_options(
        &self,
        path: &Path,
        options: &PersistenceOptions,
    ) -> Result<(), PersistenceError> {
        let bytes = serialize_with_options(self, options)?;

        let mut file = fs::File::create(path)?;
        file.write_all(&bytes)?;

        log::info!("Saved learning engine to {:?}", path);
        Ok(())
    }

    fn load_from_file(path: &Path) -> Result<Self, PersistenceError> {
        Self::load_from_file_with_options(path, &PersistenceOptions::default())
    }

    fn load_from_file_with_options(
        path: &Path,
        options: &PersistenceOptions,
    ) -> Result<Self, PersistenceError> {
        let mut file = fs::File::open(path)?;
        let mut bytes = Vec::new();
        file.read_to_end(&mut bytes)?;

        let engine = deserialize_with_options(&bytes, options)?;

        log::info!("Loaded learning engine from {:?}", path);
        Ok(engine)
    }

    fn to_bytes(&self) -> Vec<u8> {
        self.to_bytes_with_options(&PersistenceOptions::default())
            .unwrap_or_default()
    }

    fn to_bytes_with_options(
        &self,
        options: &PersistenceOptions,
    ) -> Result<Vec<u8>, PersistenceError> {
        serialize_with_options(self, options)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, PersistenceError> {
        Self::from_bytes_with_options(bytes, &PersistenceOptions::default())
    }

    fn from_bytes_with_options(
        bytes: &[u8],
        options: &PersistenceOptions,
    ) -> Result<Self, PersistenceError> {
        deserialize_with_options(bytes, options)
    }
}

/// A serializable snapshot of a `LearningEngine`'s state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LearningSnapshot {
    /// The configuration of the learning engine.
    pub config: LearningConfig,
    /// The total number of learning updates performed.
    pub total_updates: u64,
    /// The Q-values of the state-action pairs.
    pub q_values: Vec<(String, String, f64)>,
    /// The total number of episodes completed.
    pub episode_count: u64,
}

impl From<&LearningEngine> for LearningSnapshot {
    fn from(engine: &LearningEngine) -> Self {
        Self {
            config: engine.config().clone(),
            total_updates: engine.total_updates(),
            q_values: Vec::new(), // Would need to export from engine
            episode_count: engine.total_episodes(),
        }
    }
}

// Helper functions for serialization with different formats

fn serialize_with_options<T: Serialize>(
    value: &T,
    options: &PersistenceOptions,
) -> Result<Vec<u8>, PersistenceError> {
    let bytes = match options.format {
        PersistenceFormat::Json => {
            if options.pretty {
                serde_json::to_vec_pretty(value)?
            } else {
                serde_json::to_vec(value)?
            }
        }
        PersistenceFormat::Binary => {
            // For binary format, use JSON as fallback (in production, use bincode or similar)
            serde_json::to_vec(value)?
        }
        PersistenceFormat::MessagePack => {
            // For MessagePack, use JSON as fallback (in production, use rmp-serde)
            serde_json::to_vec(value)?
        }
    };

    if options.compress {
        compress_bytes(&bytes)
    } else {
        Ok(bytes)
    }
}

fn deserialize_with_options<T: for<'de> Deserialize<'de>>(
    bytes: &[u8],
    options: &PersistenceOptions,
) -> Result<T, PersistenceError> {
    let bytes = if options.compress {
        decompress_bytes(bytes)?
    } else {
        bytes.to_vec()
    };

    match options.format {
        PersistenceFormat::Json | PersistenceFormat::Binary | PersistenceFormat::MessagePack => {
            serde_json::from_slice(&bytes)
                .map_err(|e| PersistenceError::Deserialization(e.to_string()))
        }
    }
}

// Simple compression/decompression (in production, use a real compression library)
fn compress_bytes(bytes: &[u8]) -> Result<Vec<u8>, PersistenceError> {
    // Placeholder: in production, use flate2, zstd, or similar
    // For now, just return the bytes with a compression header
    let mut result = vec![0x1F, 0x8B]; // Gzip magic number placeholder
    result.extend_from_slice(bytes);
    Ok(result)
}

fn decompress_bytes(bytes: &[u8]) -> Result<Vec<u8>, PersistenceError> {
    // Placeholder: in production, use flate2, zstd, or similar
    // For now, just strip the compression header if present
    if bytes.len() >= 2 && bytes[0] == 0x1F && bytes[1] == 0x8B {
        Ok(bytes[2..].to_vec())
    } else {
        Ok(bytes.to_vec())
    }
}

/// Manages the periodic saving of an agent's state to checkpoints.
pub struct CheckpointManager {
    /// The directory where checkpoint files are stored.
    checkpoint_dir: std::path::PathBuf,
    /// The maximum number of checkpoint files to keep. Older ones are deleted.
    max_checkpoints: usize,
    /// The number of agent steps between each checkpoint.
    checkpoint_interval: u64,
    /// The step number of the last saved checkpoint.
    last_checkpoint: u64,
}

impl CheckpointManager {
    /// Creates a new `CheckpointManager`.
    ///
    /// # Arguments
    ///
    /// * `checkpoint_dir` - The path to the directory where checkpoints will be saved.
    /// * `max_checkpoints` - The maximum number of checkpoint files to retain.
    pub fn new(checkpoint_dir: &Path, max_checkpoints: usize) -> Self {
        Self {
            checkpoint_dir: checkpoint_dir.to_path_buf(),
            max_checkpoints,
            checkpoint_interval: 1000,
            last_checkpoint: 0,
        }
    }

    /// Sets the interval (in agent steps) between checkpoints.
    pub fn with_interval(mut self, interval: u64) -> Self {
        self.checkpoint_interval = interval;
        self
    }

    /// Determines if a checkpoint should be saved at the current step.
    pub fn should_checkpoint(&self, current_step: u64) -> bool {
        current_step - self.last_checkpoint >= self.checkpoint_interval
    }

    /// Saves a checkpoint of the agent's state.
    pub fn save_checkpoint(
        &mut self,
        agent: &HopeAgent,
        step: u64,
    ) -> Result<(), PersistenceError> {
        // Create checkpoint directory if it doesn't exist
        fs::create_dir_all(&self.checkpoint_dir)?;

        let checkpoint_path = self
            .checkpoint_dir
            .join(format!("checkpoint_{}.json", step));
        agent.save_to_file(&checkpoint_path)?;

        self.last_checkpoint = step;

        // Clean up old checkpoints
        self.cleanup_old_checkpoints()?;

        log::info!("Saved checkpoint at step {}", step);
        Ok(())
    }

    /// Loads the most recent checkpoint from the checkpoint directory.
    pub fn load_latest_checkpoint(&self) -> Result<HopeAgent, PersistenceError> {
        let checkpoints = self.list_checkpoints()?;

        if checkpoints.is_empty() {
            return Err(PersistenceError::InvalidFormat(
                "No checkpoints found".to_string(),
            ));
        }

        let latest = checkpoints.last().unwrap();
        HopeAgent::load_from_file(latest)
    }

    /// Lists all checkpoint files in the directory, sorted by step number.
    fn list_checkpoints(&self) -> Result<Vec<std::path::PathBuf>, PersistenceError> {
        if !self.checkpoint_dir.exists() {
            return Ok(Vec::new());
        }

        let mut checkpoints = Vec::new();

        for entry in fs::read_dir(&self.checkpoint_dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("json") {
                if let Some(name) = path.file_name().and_then(|s| s.to_str()) {
                    if name.starts_with("checkpoint_") {
                        checkpoints.push(path);
                    }
                }
            }
        }

        // Sort by filename (which includes step number)
        checkpoints.sort();
        Ok(checkpoints)
    }

    /// Removes the oldest checkpoint files to stay within the `max_checkpoints` limit.
    fn cleanup_old_checkpoints(&self) -> Result<(), PersistenceError> {
        let mut checkpoints = self.list_checkpoints()?;

        while checkpoints.len() > self.max_checkpoints {
            if let Some(old_checkpoint) = checkpoints.first() {
                fs::remove_file(old_checkpoint)?;
                log::debug!("Removed old checkpoint: {:?}", old_checkpoint);
            }
            checkpoints.remove(0);
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{HopeAgent, Observation};
    use std::path::PathBuf;

    fn temp_path(name: &str) -> PathBuf {
        let mut path = std::env::temp_dir();
        path.push(format!("hope_agents_test_{}", name));
        path
    }

    #[test]
    fn test_save_and_load_hope_agent() {
        let mut agent = HopeAgent::with_default_config();

        // Do some steps to create state
        for i in 0..5 {
            let obs = Observation::sensor("temp", 20.0 + i as f64);
            agent.step(obs);
        }

        let path = temp_path("agent_save_load.json");

        // Save
        agent.save_to_file(&path).unwrap();
        assert!(path.exists());

        // Load
        let loaded_agent = HopeAgent::load_from_file(&path).unwrap();
        assert_eq!(
            loaded_agent.get_statistics().total_steps,
            agent.get_statistics().total_steps
        );

        // Cleanup
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn test_save_with_different_options() {
        let agent = HopeAgent::with_default_config();

        // Save with compact options
        let path = temp_path("agent_compact.bin");
        let options = PersistenceOptions::compact();
        agent.save_to_file_with_options(&path, &options).unwrap();
        assert!(path.exists());

        // Load with same options
        let _loaded = HopeAgent::load_from_file_with_options(&path, &options).unwrap();

        // Cleanup
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn test_to_bytes_and_from_bytes() {
        let mut agent = HopeAgent::with_default_config();

        // Do some steps
        let obs = Observation::sensor("temp", 25.0);
        agent.step(obs);

        // Serialize to bytes
        let bytes = agent.to_bytes();
        assert!(!bytes.is_empty());

        // Deserialize from bytes
        let loaded_agent = HopeAgent::from_bytes(&bytes).unwrap();
        assert_eq!(
            loaded_agent.get_statistics().total_steps,
            agent.get_statistics().total_steps
        );
    }

    #[test]
    fn test_learning_engine_persistence() {
        let engine = LearningEngine::new(LearningConfig::default());

        let path = temp_path("learning_engine.json");

        // Save
        engine.save_to_file(&path).unwrap();
        assert!(path.exists());

        // Load
        let _loaded_engine = LearningEngine::load_from_file(&path).unwrap();

        // Cleanup
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn test_checkpoint_manager() {
        let checkpoint_dir = temp_path("checkpoints");
        let mut manager = CheckpointManager::new(&checkpoint_dir, 3).with_interval(10);

        let agent = HopeAgent::with_default_config();

        // Should checkpoint at intervals
        assert!(manager.should_checkpoint(10));
        assert!(!manager.should_checkpoint(5));

        // Save checkpoints
        manager.save_checkpoint(&agent, 10).unwrap();
        manager.save_checkpoint(&agent, 20).unwrap();
        manager.save_checkpoint(&agent, 30).unwrap();

        assert!(checkpoint_dir.exists());

        // Cleanup
        let _ = fs::remove_dir_all(&checkpoint_dir);
    }

    #[test]
    fn test_checkpoint_cleanup() {
        let checkpoint_dir = temp_path("checkpoints_cleanup");
        let mut manager = CheckpointManager::new(&checkpoint_dir, 2).with_interval(1);

        let agent = HopeAgent::with_default_config();

        // Save more checkpoints than max
        manager.save_checkpoint(&agent, 1).unwrap();
        manager.save_checkpoint(&agent, 2).unwrap();
        manager.save_checkpoint(&agent, 3).unwrap();
        manager.save_checkpoint(&agent, 4).unwrap();

        // Should only have 2 checkpoints (max_checkpoints)
        let checkpoints = manager.list_checkpoints().unwrap();
        assert_eq!(checkpoints.len(), 2);

        // Cleanup
        let _ = fs::remove_dir_all(&checkpoint_dir);
    }

    #[test]
    fn test_roundtrip_with_compression() {
        let agent = HopeAgent::with_default_config();

        let options = PersistenceOptions {
            format: PersistenceFormat::Json,
            pretty: false,
            compress: true,
        };

        let bytes = agent.to_bytes_with_options(&options).unwrap();
        let loaded = HopeAgent::from_bytes_with_options(&bytes, &options).unwrap();

        assert_eq!(
            loaded.get_statistics().total_steps,
            agent.get_statistics().total_steps
        );
    }

    #[test]
    fn test_persistence_error_handling() {
        let invalid_path = PathBuf::from("/invalid/path/that/does/not/exist/agent.json");
        let result = HopeAgent::load_from_file(&invalid_path);
        assert!(result.is_err());
    }
}