osvm 0.8.3

OpenSVM CLI tool for managing SVM nodes and deployments
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
//! Repair execution strategies and transaction management
//!
//! This module provides atomic repair operations with rollback capabilities
//! and comprehensive transaction management for system repairs.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error::Error as StdError;
use std::fmt;
use std::process::Command;
use tokio::time::Duration;

use super::system_deps::{SystemDependencyManager, SystemDepsError};
use super::user_deps::{UserDependencyManager, UserDepsError};
use super::{RepairError, RepairResult};
// use super::snapshots::{SnapshotManager, SnapshotError};  // REMOVED

/// Repair operation types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RepairOperation {
    // System-level operations
    UpdateSystemPackages,
    UpdateRustToolchain,
    InstallSystemDependencies(Vec<String>),
    TuneSystemParameters,

    // User-level operations
    InstallSolanaCli,
    CreateConfigDirectory,
    GenerateKeypair(String),
    ConfigureNetwork(String),

    // Validation operations
    ValidateSystemHealth,
    ValidateUserConfig,
}

/// Checkpoint information for rollback
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Checkpoint {
    pub id: String,
    pub timestamp: DateTime<Utc>,
    pub operation: RepairOperation,
    pub snapshot_id: Option<String>,
    pub state_data: HashMap<String, String>,
}

/// Transaction state
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TransactionState {
    NotStarted,
    InProgress,
    Committed,
    RolledBack,
    Failed,
}

/// Repair transaction with atomic operations and rollback
#[derive(Debug)]
pub struct RepairTransaction {
    pub id: String,
    pub operations: Vec<RepairOperation>,
    pub checkpoints: Vec<Checkpoint>,
    pub state: TransactionState,
    pub start_time: Option<DateTime<Utc>>,
    pub timeout: Duration,
    // snapshot_manager: SnapshotManager,  // REMOVED
    system_manager: SystemDependencyManager,
    user_manager: UserDependencyManager,
}

/// Repair strategy error
#[derive(Debug)]
pub enum RepairStrategyError {
    TransactionFailed(String),
    CheckpointFailed(String),
    RollbackFailed(String),
    ValidationFailed(String),
    TimeoutError(String),
    SystemError(SystemDepsError),
    UserError(UserDepsError),
    // SnapshotError(SnapshotError),  // REMOVED
}

impl fmt::Display for RepairStrategyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RepairStrategyError::TransactionFailed(msg) => write!(f, "Transaction failed: {}", msg),
            RepairStrategyError::CheckpointFailed(msg) => write!(f, "Checkpoint failed: {}", msg),
            RepairStrategyError::RollbackFailed(msg) => write!(f, "Rollback failed: {}", msg),
            RepairStrategyError::ValidationFailed(msg) => write!(f, "Validation failed: {}", msg),
            RepairStrategyError::TimeoutError(msg) => write!(f, "Timeout error: {}", msg),
            RepairStrategyError::SystemError(e) => write!(f, "System error: {}", e),
            RepairStrategyError::UserError(e) => write!(f, "User error: {}", e),
            // RepairStrategyError::SnapshotError(e) => write!(f, "Snapshot error: {}", e),  // REMOVED
        }
    }
}

impl StdError for RepairStrategyError {}

impl From<SystemDepsError> for RepairStrategyError {
    fn from(err: SystemDepsError) -> Self {
        RepairStrategyError::SystemError(err)
    }
}

impl From<UserDepsError> for RepairStrategyError {
    fn from(err: UserDepsError) -> Self {
        RepairStrategyError::UserError(err)
    }
}

// REMOVED: SnapshotError conversion
// impl From<SnapshotError> for RepairStrategyError {
//     fn from(err: SnapshotError) -> Self {
//         RepairStrategyError::SnapshotError(err)
//     }
// }

impl RepairTransaction {
    /// Create a new repair transaction
    pub fn new() -> Result<Self, RepairStrategyError> {
        let id = format!("repair_tx_{}", chrono::Utc::now().timestamp());
        let system_manager =
            SystemDependencyManager::new().map_err(RepairStrategyError::SystemError)?;
        let user_manager = UserDependencyManager::new();
        // let snapshot_manager = SnapshotManager::new();  // REMOVED

        Ok(Self {
            id,
            operations: Vec::new(),
            checkpoints: Vec::new(),
            state: TransactionState::NotStarted,
            start_time: None,
            timeout: Duration::from_secs(600), // 10 minutes default
            // snapshot_manager,  // REMOVED
            system_manager,
            user_manager,
        })
    }

    /// Add a repair operation to the transaction
    pub fn add_operation(&mut self, operation: RepairOperation) {
        self.operations.push(operation);
    }

    /// Set transaction timeout
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.timeout = timeout;
    }

    /// Execute the transaction with automatic rollback on failure
    pub async fn execute(&mut self) -> Result<RepairResult, RepairError> {
        if self.state != TransactionState::NotStarted {
            return Err(RepairError::ValidationError(
                "Transaction already started".to_string(),
            ));
        }

        self.begin_transaction().await?;

        // Create initial snapshot
        // DISABLED: Commenting out snapshot creation as requested
        // let initial_snapshot = self.create_system_snapshot().await?;
        // println!("📸 Created system snapshot: {}", initial_snapshot);

        let mut completed_operations = 0;
        let total_operations = self.operations.len();

        for (index, operation) in self.operations.clone().iter().enumerate() {
            // Check timeout
            if let Some(start_time) = self.start_time {
                let elapsed = Utc::now() - start_time;
                if elapsed.to_std().unwrap_or(Duration::from_secs(0)) > self.timeout {
                    return self.handle_timeout().await;
                }
            }

            // Create checkpoint before operation
            let checkpoint = self.create_checkpoint(operation.clone()).await?;
            println!(
                "🔄 [{}/{}] Executing: {:?}",
                index + 1,
                total_operations,
                operation
            );

            // Execute the operation
            match self.execute_operation(operation).await {
                Ok(result) => {
                    println!("✅ Operation completed: {}", result);

                    // Validate operation success
                    if let Err(e) = self.validate_operation(operation).await {
                        println!("❌ Operation validation failed: {}", e);
                        return self.rollback_transaction().await;
                    }

                    completed_operations += 1;
                }
                Err(e) => {
                    println!("❌ Operation failed: {}", e);
                    return self.rollback_transaction().await;
                }
            }
        }

        // All operations completed successfully
        self.commit_transaction().await?;

        Ok(RepairResult::Success(format!(
            "All {} repair operations completed successfully",
            completed_operations
        )))
    }

    /// Begin the transaction
    async fn begin_transaction(&mut self) -> Result<(), RepairError> {
        self.state = TransactionState::InProgress;
        self.start_time = Some(Utc::now());
        println!("🚀 Starting repair transaction: {}", self.id);
        Ok(())
    }

    /// Create a checkpoint before an operation
    async fn create_checkpoint(
        &mut self,
        operation: RepairOperation,
    ) -> Result<String, RepairError> {
        let checkpoint_id = format!(
            "checkpoint_{}_{}",
            self.checkpoints.len(),
            chrono::Utc::now().timestamp_millis()
        );

        // Create snapshot for critical operations
        // DISABLED: Commenting out snapshot creation as requested
        // let snapshot_id = match operation {
        //     RepairOperation::UpdateSystemPackages |
        //     RepairOperation::UpdateRustToolchain |
        //     RepairOperation::InstallSystemDependencies(_) => {
        //         Some(self.create_system_snapshot().await?)
        //     }
        //     _ => None,
        // };
        let snapshot_id: Option<String> = None;

        let checkpoint = Checkpoint {
            id: checkpoint_id.clone(),
            timestamp: Utc::now(),
            operation: operation.clone(),
            snapshot_id,
            state_data: self.capture_state_data(&operation).await,
        };

        self.checkpoints.push(checkpoint);
        Ok(checkpoint_id)
    }

    /// Execute a single repair operation
    async fn execute_operation(
        &self,
        operation: &RepairOperation,
    ) -> Result<String, RepairStrategyError> {
        match operation {
            RepairOperation::UpdateSystemPackages => {
                Ok(self.system_manager.update_system_packages().await?)
            }
            RepairOperation::UpdateRustToolchain => {
                Ok(self.system_manager.install_rust_toolchain().await?)
            }
            RepairOperation::InstallSystemDependencies(deps) => Ok(self
                .system_manager
                .install_system_dependencies(deps)
                .await?),
            RepairOperation::InstallSolanaCli => Ok(self.user_manager.install_solana_cli().await?),
            RepairOperation::CreateConfigDirectory => {
                Ok(self.user_manager.create_solana_config_dir().await?)
            }
            RepairOperation::GenerateKeypair(path) => {
                let keypair_path = if path.is_empty() {
                    None
                } else {
                    Some(path.as_str())
                };
                Ok(self.user_manager.generate_keypair(keypair_path).await?)
            }
            RepairOperation::ConfigureNetwork(network) => {
                Ok(self.user_manager.configure_solana_network(network).await?)
            }
            RepairOperation::ValidateSystemHealth => Ok(self.validate_system_health().await?),
            RepairOperation::ValidateUserConfig => Ok(self.validate_user_config().await?),
            RepairOperation::TuneSystemParameters => Ok(self.tune_system_parameters().await?),
        }
    }

    /// Validate an operation was successful
    async fn validate_operation(
        &self,
        operation: &RepairOperation,
    ) -> Result<(), RepairStrategyError> {
        match operation {
            RepairOperation::InstallSolanaCli => {
                if !self.user_manager.is_solana_cli_installed().await? {
                    return Err(RepairStrategyError::ValidationFailed(
                        "Solana CLI installation validation failed".to_string(),
                    ));
                }
            }
            RepairOperation::CreateConfigDirectory => {
                if !self.user_manager.get_solana_config_dir().exists() {
                    return Err(RepairStrategyError::ValidationFailed(
                        "Config directory creation validation failed".to_string(),
                    ));
                }
            }
            RepairOperation::GenerateKeypair(path) => {
                let keypair_path = if path.is_empty() {
                    self.user_manager.get_solana_config_dir().join("id.json")
                } else {
                    std::path::PathBuf::from(path)
                };

                if !keypair_path.exists() {
                    return Err(RepairStrategyError::ValidationFailed(
                        "Keypair generation validation failed".to_string(),
                    ));
                }
            }
            _ => {
                // Default validation - just ensure no critical errors
            }
        }
        Ok(())
    }

    /// Capture state data for rollback
    async fn capture_state_data(&self, operation: &RepairOperation) -> HashMap<String, String> {
        let mut state_data = HashMap::new();

        match operation {
            RepairOperation::UpdateRustToolchain => {
                if let Ok(rust_info) = self.system_manager.check_rust_toolchain().await {
                    if let Some(version) = rust_info.version {
                        state_data.insert("rust_version".to_string(), version);
                    }
                }
            }
            RepairOperation::ConfigureNetwork(_) => {
                if let Ok(config_info) = self.user_manager.check_all_user_dependencies().await {
                    if let Some(network) = config_info.current_network {
                        state_data.insert("current_network".to_string(), network);
                    }
                }
            }
            _ => {}
        }

        state_data
    }

    /// Create a system snapshot
    async fn create_system_snapshot(&self) -> Result<String, RepairError> {
        // DISABLED: Commenting out actual snapshot creation
        // self.snapshot_manager.create_snapshot(None).await
        //     .map_err(|e| RepairError::SnapshotError(e.to_string()))

        // Return a dummy snapshot ID
        Ok("snapshot_disabled".to_string())
    }

    /// Validate system health
    async fn validate_system_health(&self) -> Result<String, RepairStrategyError> {
        let dependencies = self.system_manager.check_all_dependencies().await?;
        let issues: Vec<_> = dependencies.iter().filter(|dep| !dep.installed).collect();

        if issues.is_empty() {
            Ok("System health validation passed".to_string())
        } else {
            Err(RepairStrategyError::ValidationFailed(format!(
                "System health issues found: {:?}",
                issues.iter().map(|d| &d.name).collect::<Vec<_>>()
            )))
        }
    }

    /// Validate user configuration
    async fn validate_user_config(&self) -> Result<String, RepairStrategyError> {
        let issues = self.user_manager.validate_solana_config().await?;

        if issues.is_empty() {
            Ok("User configuration validation passed".to_string())
        } else {
            Err(RepairStrategyError::ValidationFailed(format!(
                "User configuration issues: {:?}",
                issues
            )))
        }
    }

    /// Apply system tuning parameters for Solana
    async fn tune_system_parameters(&self) -> Result<String, RepairStrategyError> {
        println!("🔧 Applying system tuning parameters for Solana...");

        // Define required kernel parameters
        let kernel_params = vec![
            ("net.core.rmem_max", "134217728"),
            ("net.core.rmem_default", "134217728"),
            ("net.core.wmem_max", "134217728"),
            ("net.core.wmem_default", "134217728"),
            ("vm.max_map_count", "2000000"),
            ("vm.swappiness", "30"),
            ("vm.dirty_ratio", "40"),
            ("vm.dirty_background_ratio", "10"),
        ];

        let mut applied_count = 0;
        let mut errors = Vec::new();

        for (param, value) in &kernel_params {
            // Apply with sysctl
            let output = Command::new("sudo")
                .arg("sysctl")
                .arg("-w")
                .arg(format!("{}={}", param, value))
                .output();

            match output {
                Ok(result) => {
                    if result.status.success() {
                        println!("✅ Set {} = {}", param, value);
                        applied_count += 1;
                    } else {
                        let error_msg = String::from_utf8_lossy(&result.stderr);
                        errors.push(format!("{}: {}", param, error_msg.trim()));
                    }
                }
                Err(e) => {
                    errors.push(format!("{}: {}", param, e));
                }
            }
        }

        // Try to persist settings to sysctl.conf
        if applied_count > 0 {
            let sysctl_conf_content = kernel_params
                .iter()
                .map(|(param, value)| format!("{}={}", param, value))
                .collect::<Vec<_>>()
                .join("\n");

            let persist_cmd = Command::new("sh")
                .arg("-c")
                .arg(format!(
                    "echo '# OSVM Solana tuning parameters\n{}' | sudo tee -a /etc/sysctl.conf > /dev/null",
                    sysctl_conf_content
                ))
                .output();

            if let Ok(result) = persist_cmd {
                if result.status.success() {
                    println!("✅ Persisted settings to /etc/sysctl.conf");
                }
            }
        }

        if errors.is_empty() {
            Ok(format!(
                "Applied {} system tuning parameters",
                applied_count
            ))
        } else {
            Err(RepairStrategyError::ValidationFailed(format!(
                "Applied {} parameters, but {} failed: {:?}",
                applied_count,
                errors.len(),
                errors
            )))
        }
    }

    /// Handle transaction timeout
    async fn handle_timeout(&mut self) -> Result<RepairResult, RepairError> {
        println!("⏰ Transaction timeout reached, initiating rollback...");
        self.rollback_transaction().await
    }

    /// Rollback the transaction to the last known good state
    async fn rollback_transaction(&mut self) -> Result<RepairResult, RepairError> {
        self.state = TransactionState::RolledBack;
        println!("🔙 Rolling back transaction: {}", self.id);

        // SNAPSHOTS REMOVED: Now just try manual rollback
        // // Find the most recent checkpoint with a snapshot
        // if let Some(checkpoint) = self.checkpoints.iter()
        //     .rev()
        //     .find(|cp| cp.snapshot_id.is_some()) {
        //
        //     if let Some(snapshot_id) = &checkpoint.snapshot_id {
        //         println!("📸 Restoring from snapshot: {}", snapshot_id);
        //
        //         match self.snapshot_manager.restore_snapshot(snapshot_id).await {
        //             Ok(_) => {
        //                 // Validate rollback success
        //                 match self.validate_rollback_success().await {
        //                     Ok(_) => {
        //                         println!("✅ Rollback completed successfully");
        //                         Ok(RepairResult::Failed(RepairError::RollbackError(
        //                             "Transaction failed but system restored to previous state".to_string()
        //                         )))
        //                     }
        //                     Err(e) => {
        //                         println!("❌ Rollback validation failed: {}", e);
        //                         Ok(RepairResult::RequiresManualIntervention(
        //                             "Automatic rollback failed - manual intervention required".to_string()
        //                         ))
        //                     }
        //                 }
        //             }
        //             Err(e) => {
        //                 println!("❌ Snapshot restore failed: {}", e);
        //                 Ok(RepairResult::RequiresManualIntervention(
        //                     format!("Critical error: rollback failed - {}", e)
        //                 ))
        //             }
        //         }
        //     } else {
        //         // No snapshot available, try manual rollback
        //         self.manual_rollback().await
        //     }
        // } else {
        //     println!("⚠️  No snapshots available for rollback");
        //     Ok(RepairResult::Failed(RepairError::RollbackError(
        //         "No recovery point available".to_string()
        //     )))
        // }

        // Always do manual rollback since snapshots are removed
        self.manual_rollback().await
    }

    /// Manual rollback for operations without snapshots
    async fn manual_rollback(&mut self) -> Result<RepairResult, RepairError> {
        println!("🔧 Attempting manual rollback...");

        // Reverse the operations that were completed
        for checkpoint in self.checkpoints.iter().rev() {
            match self
                .reverse_operation(&checkpoint.operation, &checkpoint.state_data)
                .await
            {
                Ok(msg) => println!("✅ Reversed: {}", msg),
                Err(e) => println!("⚠️  Could not reverse operation: {}", e),
            }
        }

        // Validate the manual rollback
        match self.validate_rollback_success().await {
            Ok(_) => Ok(RepairResult::Partial(
                "Manual rollback completed".to_string(),
                vec![], // TODO: Return remaining issues
            )),
            Err(_) => Ok(RepairResult::RequiresManualIntervention(
                "Manual rollback incomplete - please check system state".to_string(),
            )),
        }
    }

    /// Reverse a specific operation
    async fn reverse_operation(
        &self,
        operation: &RepairOperation,
        state_data: &HashMap<String, String>,
    ) -> Result<String, RepairStrategyError> {
        match operation {
            RepairOperation::ConfigureNetwork(_) => {
                if let Some(previous_network) = state_data.get("current_network") {
                    Ok(self
                        .user_manager
                        .configure_solana_network(previous_network)
                        .await?)
                } else {
                    Ok("Could not restore previous network configuration".to_string())
                }
            }
            RepairOperation::UpdateRustToolchain => {
                if let Some(previous_version) = state_data.get("rust_version") {
                    // Note: Downgrading Rust is complex, so we just note it
                    Ok(format!(
                        "Note: Rust was updated from version {}",
                        previous_version
                    ))
                } else {
                    Ok("Rust toolchain update cannot be easily reversed".to_string())
                }
            }
            _ => Ok(format!(
                "Operation {:?} cannot be automatically reversed",
                operation
            )),
        }
    }

    /// Validate that rollback was successful
    async fn validate_rollback_success(&self) -> Result<(), RepairStrategyError> {
        // Check that critical systems are still functional
        let _system_deps = self.system_manager.check_all_dependencies().await?;
        let _user_config = self.user_manager.check_all_user_dependencies().await?;

        // If we get here without errors, rollback validation passed
        Ok(())
    }

    /// Commit the transaction
    async fn commit_transaction(&mut self) -> Result<(), RepairError> {
        self.state = TransactionState::Committed;

        // SNAPSHOTS REMOVED: No longer cleaning up snapshots
        // // Clean up old snapshots (keep the most recent one)
        // let snapshot_ids: Vec<String> = self.checkpoints.iter()
        //     .filter_map(|cp| cp.snapshot_id.as_ref())
        //     .cloned()
        //     .collect();
        //
        // if snapshot_ids.len() > 1 {
        //     for snapshot_id in &snapshot_ids[..snapshot_ids.len()-1] {
        //         let _ = self.snapshot_manager.cleanup_snapshot(snapshot_id).await;
        //     }
        // }

        println!("✅ Transaction committed successfully: {}", self.id);
        Ok(())
    }
}

impl Default for RepairTransaction {
    fn default() -> Self {
        Self::new().expect("Failed to create default RepairTransaction")
    }
}

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

    #[tokio::test]
    async fn test_repair_transaction_creation() {
        let transaction = RepairTransaction::new().expect("Failed to create transaction");
        assert_eq!(transaction.state, TransactionState::NotStarted);
        assert!(transaction.operations.is_empty());
        assert!(transaction.checkpoints.is_empty());
    }

    #[test]
    fn test_repair_operation_serialization() {
        let operation = RepairOperation::InstallSolanaCli;
        let serialized = serde_json::to_string(&operation).expect("Failed to serialize");
        let deserialized: RepairOperation =
            serde_json::from_str(&serialized).expect("Failed to deserialize");

        match (operation, deserialized) {
            (RepairOperation::InstallSolanaCli, RepairOperation::InstallSolanaCli) => (),
            _ => panic!("Serialization roundtrip failed"),
        }
    }

    #[tokio::test]
    async fn test_transaction_add_operations() {
        let mut transaction = RepairTransaction::new().expect("Failed to create transaction");

        transaction.add_operation(RepairOperation::InstallSolanaCli);
        transaction.add_operation(RepairOperation::CreateConfigDirectory);

        assert_eq!(transaction.operations.len(), 2);
    }

    #[test]
    fn test_checkpoint_creation() {
        let checkpoint = Checkpoint {
            id: "test_checkpoint".to_string(),
            timestamp: Utc::now(),
            operation: RepairOperation::InstallSolanaCli,
            snapshot_id: Some("test_snapshot".to_string()),
            state_data: HashMap::new(),
        };

        assert_eq!(checkpoint.id, "test_checkpoint");
        assert!(checkpoint.snapshot_id.is_some());
    }
}