bevy_debugger_mcp 0.1.8

AI-assisted debugging for Bevy games through Claude Code using Model Context Protocol
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
/// Debug Session Manager for maintaining context across debugging commands
/// 
/// This module provides comprehensive session management including:
/// - Session creation and lifecycle management
/// - Command history with undo/redo support
/// - World state checkpointing
/// - Command replay with timing preservation
/// - Session persistence across reconnections

use crate::brp_messages::{DebugCommand, DebugResponse, SessionState};
use crate::checkpoint::{Checkpoint, CheckpointManager, CheckpointConfig};
use crate::error::{Error, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};
use uuid::Uuid;

/// Configuration constants
pub mod constants {
    /// Default maximum command history entries per session
    pub const DEFAULT_COMMAND_HISTORY_LIMIT: usize = 1000;
    /// Default session cleanup time in hours
    pub const DEFAULT_CLEANUP_HOURS: u32 = 24;
    /// Default maximum concurrent sessions
    pub const DEFAULT_MAX_SESSIONS: usize = 50;
    /// Default cleanup interval in minutes
    pub const DEFAULT_CLEANUP_INTERVAL_MINUTES: u32 = 30;
    /// Maximum session name length
    pub const MAX_SESSION_NAME_LENGTH: usize = 256;
    /// Maximum command history retention
    pub const MAX_COMMAND_HISTORY_RETENTION: usize = 1000;
}

/// Command entry in session history
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandHistoryEntry {
    /// Unique ID for this command
    pub id: String,
    /// Command that was executed
    pub command: DebugCommand,
    /// Response received
    pub response: Option<DebugResponse>,
    /// Timestamp when command was executed
    pub timestamp: DateTime<Utc>,
    /// Execution duration in microseconds
    pub execution_duration_us: u64,
    /// Whether command was successful
    pub success: bool,
    /// Error message if command failed
    pub error_message: Option<String>,
    /// Correlation ID for tracking
    pub correlation_id: String,
}

/// Debug session state and context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DebugSession {
    /// Session ID
    pub id: String,
    /// Session name
    pub name: String,
    /// Session description
    pub description: Option<String>,
    /// Session state
    pub state: SessionState,
    /// Creation timestamp
    pub created_at: DateTime<Utc>,
    /// Last activity timestamp
    pub last_activity: DateTime<Utc>,
    /// Command history
    pub command_history: VecDeque<CommandHistoryEntry>,
    /// Current replay position (None if not replaying)
    pub replay_position: Option<usize>,
    /// Replay speed multiplier
    pub replay_speed: f32,
    /// Session-specific checkpoints
    pub checkpoints: Vec<String>,
    /// Session metadata
    pub metadata: HashMap<String, String>,
    /// Auto-cleanup after inactivity (hours)
    pub auto_cleanup_hours: Option<u32>,
}

impl DebugSession {
    /// Create a new debug session
    pub fn new(name: String, description: Option<String>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            name,
            description,
            state: SessionState::Active,
            created_at: now,
            last_activity: now,
            command_history: VecDeque::with_capacity(constants::DEFAULT_COMMAND_HISTORY_LIMIT),
            replay_position: None,
            replay_speed: 1.0,
            checkpoints: Vec::new(),
            metadata: HashMap::new(),
            auto_cleanup_hours: Some(24),
        }
    }

    /// Add command to history
    pub fn add_command_history(&mut self, entry: CommandHistoryEntry) {
        // Maintain maximum history size
        while self.command_history.len() >= constants::MAX_COMMAND_HISTORY_RETENTION {
            self.command_history.pop_front();
        }
        
        self.command_history.push_back(entry);
        self.last_activity = Utc::now();
    }

    /// Get command history in reverse chronological order
    pub fn get_recent_history(&self, limit: Option<usize>) -> Vec<&CommandHistoryEntry> {
        let max_count = limit.unwrap_or(100);
        self.command_history
            .iter()
            .rev()
            .take(max_count)
            .collect()
    }

    /// Check if session should be cleaned up due to inactivity
    pub fn should_cleanup(&self) -> bool {
        if let Some(hours) = self.auto_cleanup_hours {
            let age = Utc::now()
                .signed_duration_since(self.last_activity)
                .num_hours();
            age >= hours as i64
        } else {
            false
        }
    }

    /// Update last activity timestamp
    pub fn touch(&mut self) {
        self.last_activity = Utc::now();
    }

    /// Start command replay
    pub fn start_replay(&mut self, from_position: Option<usize>) -> Result<()> {
        if self.command_history.is_empty() {
            return Err(Error::Validation("No command history to replay".to_string()));
        }

        let start_pos = from_position.unwrap_or(0);
        if start_pos >= self.command_history.len() {
            return Err(Error::Validation("Invalid replay position".to_string()));
        }

        self.replay_position = Some(start_pos);
        self.state = SessionState::Replaying;
        Ok(())
    }

    /// Get next command for replay
    pub fn next_replay_command(&mut self) -> Option<&CommandHistoryEntry> {
        if let Some(pos) = self.replay_position {
            if pos < self.command_history.len() {
                let entry = &self.command_history[pos];
                self.replay_position = Some(pos + 1);
                Some(entry)
            } else {
                // Replay finished
                self.replay_position = None;
                self.state = SessionState::Active;
                None
            }
        } else {
            None
        }
    }

    /// Stop replay
    pub fn stop_replay(&mut self) {
        self.replay_position = None;
        self.state = SessionState::Active;
    }
}

/// Session management configuration
#[derive(Debug, Clone)]
pub struct SessionManagerConfig {
    /// Maximum number of concurrent sessions
    pub max_sessions: usize,
    /// Default auto-cleanup time in hours
    pub default_cleanup_hours: u32,
    /// Command history limit per session
    pub command_history_limit: usize,
    /// Enable session persistence
    pub enable_persistence: bool,
    /// Session storage directory
    pub storage_directory: String,
    /// Cleanup check interval in minutes
    pub cleanup_interval_minutes: u32,
}

impl Default for SessionManagerConfig {
    fn default() -> Self {
        Self {
            max_sessions: constants::DEFAULT_MAX_SESSIONS,
            default_cleanup_hours: constants::DEFAULT_CLEANUP_HOURS,
            command_history_limit: constants::DEFAULT_COMMAND_HISTORY_LIMIT,
            enable_persistence: true,
            storage_directory: "./debug_sessions".to_string(),
            cleanup_interval_minutes: constants::DEFAULT_CLEANUP_INTERVAL_MINUTES,
        }
    }
}

/// Debug session manager
pub struct SessionManager {
    /// Configuration
    config: SessionManagerConfig,
    /// Active sessions
    sessions: Arc<RwLock<HashMap<String, DebugSession>>>,
    /// Checkpoint manager
    checkpoint_manager: Arc<RwLock<CheckpointManager>>,
    /// Cleanup task handle
    cleanup_handle: Arc<RwLock<Option<tokio::task::JoinHandle<()>>>>,
}

impl SessionManager {
    /// Create new session manager
    pub fn new(config: SessionManagerConfig) -> Self {
        let checkpoint_config = CheckpointConfig {
            max_checkpoints: 500,
            max_age_seconds: (config.default_cleanup_hours * 3600) as u64,
            persist_to_disk: config.enable_persistence,
            storage_directory: format!("{}/checkpoints", config.storage_directory),
            cleanup_interval_seconds: (config.cleanup_interval_minutes * 60) as u64,
            max_state_size_bytes: 50 * 1024 * 1024, // 50MB
        };

        Self {
            config,
            sessions: Arc::new(RwLock::new(HashMap::new())),
            checkpoint_manager: Arc::new(RwLock::new(CheckpointManager::new(checkpoint_config))),
            cleanup_handle: Arc::new(RwLock::new(None)),
        }
    }

    /// Start session manager
    pub async fn start(&self) -> Result<()> {
        // Start checkpoint manager
        {
            let mut checkpoint_manager = self.checkpoint_manager.write().await;
            checkpoint_manager.start().await?;
        }

        // Start cleanup task
        let sessions = Arc::clone(&self.sessions);
        let cleanup_interval = Duration::from_secs((self.config.cleanup_interval_minutes * 60) as u64);

        let handle = tokio::spawn(async move {
            let mut interval = tokio::time::interval(cleanup_interval);

            loop {
                interval.tick().await;

                // Handle cleanup with proper error recovery
                match sessions.try_write() {
                    Ok(mut sessions_guard) => {
                        let mut to_remove = Vec::new();

                        for (session_id, session) in sessions_guard.iter() {
                            if session.should_cleanup() {
                                to_remove.push(session_id.clone());
                            }
                        }

                        for session_id in to_remove {
                            sessions_guard.remove(&session_id);
                            info!("Cleaned up inactive session: {}", session_id);
                        }
                    }
                    Err(e) => {
                        warn!("Failed to acquire session lock for cleanup, retrying: {}", e);
                        // Continue to next iteration rather than crashing
                        continue;
                    }
                }
            }
        });

        {
            let mut cleanup_guard = self.cleanup_handle.write().await;
            *cleanup_guard = Some(handle);
        }

        info!("Session manager started");
        Ok(())
    }

    /// Create new session
    pub async fn create_session(&self, name: String, description: Option<String>) -> Result<String> {
        // Validate input
        if name.is_empty() {
            return Err(Error::Validation("Session name cannot be empty".to_string()));
        }
        
        if name.len() > constants::MAX_SESSION_NAME_LENGTH {
            return Err(Error::Validation(format!(
                "Session name too long (max {} characters)", 
                constants::MAX_SESSION_NAME_LENGTH
            )));
        }
        
        // Check for invalid characters that could cause issues
        if name.chars().any(|c| c.is_control() || "/<>:|\"?*\\".contains(c)) {
            return Err(Error::Validation("Session name contains invalid characters".to_string()));
        }

        let mut sessions = self.sessions.write().await;

        // Check session limit
        if sessions.len() >= self.config.max_sessions {
            return Err(Error::Validation(format!(
                "Maximum session limit reached: {}",
                self.config.max_sessions
            )));
        }

        let mut session = DebugSession::new(name.clone(), description);
        session.auto_cleanup_hours = Some(self.config.default_cleanup_hours);

        let session_id = session.id.clone();
        sessions.insert(session_id.clone(), session);

        info!("Created debug session: {} ({})", name, session_id);
        Ok(session_id)
    }

    /// Get session by ID
    pub async fn get_session(&self, session_id: &str) -> Option<DebugSession> {
        let sessions = self.sessions.read().await;
        sessions.get(session_id).cloned()
    }

    /// End session
    pub async fn end_session(&self, session_id: &str) -> Result<()> {
        let mut sessions = self.sessions.write().await;
        
        if let Some(mut session) = sessions.remove(session_id) {
            session.state = SessionState::Ended;
            info!("Ended debug session: {}", session_id);
            Ok(())
        } else {
            Err(Error::Validation(format!("Session not found: {}", session_id)))
        }
    }

    /// Resume session (change state to active)
    pub async fn resume_session(&self, session_id: &str) -> Result<()> {
        let mut sessions = self.sessions.write().await;
        
        if let Some(session) = sessions.get_mut(session_id) {
            session.state = SessionState::Active;
            session.touch();
            info!("Resumed debug session: {}", session_id);
            Ok(())
        } else {
            Err(Error::Validation(format!("Session not found: {}", session_id)))
        }
    }

    /// Create checkpoint for session
    pub async fn create_checkpoint(&self, session_id: &str, description: &str) -> Result<String> {
        let mut sessions = self.sessions.write().await;
        
        if let Some(session) = sessions.get_mut(session_id) {
            // Create checkpoint with session state (clone to avoid borrow issues)
            let session_clone = session.clone();
            let checkpoint_data = serde_json::to_value(&session_clone)?;
            let checkpoint = Checkpoint::new(
                &format!("Session {} Checkpoint", session.name),
                description,
                "session_state",
                "debug_session_manager",
                checkpoint_data,
            );

            let checkpoint_id = checkpoint.id.clone();
            
            {
                let checkpoint_manager = self.checkpoint_manager.read().await;
                checkpoint_manager.create_checkpoint(checkpoint).await?;
            }

            session.checkpoints.push(checkpoint_id.clone());
            session.touch();

            info!("Created checkpoint for session {}: {}", session_id, checkpoint_id);
            Ok(checkpoint_id)
        } else {
            Err(Error::Validation(format!("Session not found: {}", session_id)))
        }
    }

    /// Restore session from checkpoint
    pub async fn restore_checkpoint(&self, session_id: &str, checkpoint_id: &str) -> Result<()> {
        let checkpoint = {
            let checkpoint_manager = self.checkpoint_manager.read().await;
            checkpoint_manager.restore_checkpoint(checkpoint_id).await?
        };

        let restored_session: DebugSession = serde_json::from_value(checkpoint.state_data)?;

        let mut sessions = self.sessions.write().await;
        sessions.insert(session_id.to_string(), restored_session);

        info!("Restored session {} from checkpoint {}", session_id, checkpoint_id);
        Ok(())
    }

    /// Record command execution in session
    pub async fn record_command(
        &self,
        session_id: &str,
        command: DebugCommand,
        response: Option<DebugResponse>,
        execution_duration: Duration,
        correlation_id: String,
    ) -> Result<()> {
        let mut sessions = self.sessions.write().await;
        
        if let Some(session) = sessions.get_mut(session_id) {
            let success = response.is_some() && matches!(response, Some(DebugResponse::Success { .. }));
            let error_message = if !success && response.is_some() {
                Some(format!("{:?}", response))
            } else {
                None
            };

            let entry = CommandHistoryEntry {
                id: Uuid::new_v4().to_string(),
                command,
                response,
                timestamp: Utc::now(),
                execution_duration_us: execution_duration.as_micros() as u64,
                success,
                error_message,
                correlation_id,
            };

            session.add_command_history(entry);
            debug!("Recorded command in session: {}", session_id);
            Ok(())
        } else {
            Err(Error::Validation(format!("Session not found: {}", session_id)))
        }
    }

    /// Get session command history
    pub async fn get_command_history(
        &self,
        session_id: &str,
        limit: Option<usize>,
    ) -> Result<Vec<CommandHistoryEntry>> {
        let sessions = self.sessions.read().await;
        
        if let Some(session) = sessions.get(session_id) {
            let history = session
                .get_recent_history(limit)
                .iter()
                .map(|&entry| entry.clone())
                .collect();
            Ok(history)
        } else {
            Err(Error::Validation(format!("Session not found: {}", session_id)))
        }
    }

    /// Start command replay for session
    pub async fn start_replay(&self, session_id: &str, from_position: Option<usize>) -> Result<()> {
        let mut sessions = self.sessions.write().await;
        
        if let Some(session) = sessions.get_mut(session_id) {
            session.start_replay(from_position)?;
            info!("Started replay for session: {}", session_id);
            Ok(())
        } else {
            Err(Error::Validation(format!("Session not found: {}", session_id)))
        }
    }

    /// Get next replay command
    pub async fn get_next_replay_command(&self, session_id: &str) -> Result<Option<DebugCommand>> {
        let mut sessions = self.sessions.write().await;
        
        if let Some(session) = sessions.get_mut(session_id) {
            if let Some(entry) = session.next_replay_command() {
                Ok(Some(entry.command.clone()))
            } else {
                Ok(None)
            }
        } else {
            Err(Error::Validation(format!("Session not found: {}", session_id)))
        }
    }

    /// Stop command replay
    pub async fn stop_replay(&self, session_id: &str) -> Result<()> {
        let mut sessions = self.sessions.write().await;
        
        if let Some(session) = sessions.get_mut(session_id) {
            session.stop_replay();
            info!("Stopped replay for session: {}", session_id);
            Ok(())
        } else {
            Err(Error::Validation(format!("Session not found: {}", session_id)))
        }
    }

    /// List all active sessions
    pub async fn list_sessions(&self) -> Vec<DebugSession> {
        let sessions = self.sessions.read().await;
        sessions.values().cloned().collect()
    }

    /// Get session statistics
    pub async fn get_statistics(&self) -> HashMap<String, serde_json::Value> {
        let sessions = self.sessions.read().await;
        let checkpoint_stats = {
            let checkpoint_manager = self.checkpoint_manager.read().await;
            checkpoint_manager.get_statistics().await
        };

        let mut stats = HashMap::new();

        stats.insert(
            "total_sessions".to_string(),
            serde_json::Value::Number(sessions.len().into()),
        );

        let active_sessions = sessions
            .values()
            .filter(|s| matches!(s.state, SessionState::Active))
            .count();

        stats.insert(
            "active_sessions".to_string(),
            serde_json::Value::Number(active_sessions.into()),
        );

        let replaying_sessions = sessions
            .values()
            .filter(|s| matches!(s.state, SessionState::Replaying))
            .count();

        stats.insert(
            "replaying_sessions".to_string(),
            serde_json::Value::Number(replaying_sessions.into()),
        );

        let total_commands: usize = sessions
            .values()
            .map(|s| s.command_history.len())
            .sum();

        stats.insert(
            "total_commands_recorded".to_string(),
            serde_json::Value::Number(total_commands.into()),
        );

        stats.insert(
            "total_checkpoints".to_string(),
            serde_json::Value::Number(checkpoint_stats.total_count.into()),
        );

        stats
    }

    /// Shutdown session manager
    pub async fn shutdown(&mut self) -> Result<()> {
        // Stop cleanup task
        {
            let mut cleanup_guard = self.cleanup_handle.write().await;
            if let Some(handle) = cleanup_guard.take() {
                handle.abort();
            }
        }

        // Shutdown checkpoint manager
        {
            let mut checkpoint_manager = self.checkpoint_manager.write().await;
            checkpoint_manager.shutdown().await?;
        }

        info!("Session manager shutdown complete");
        Ok(())
    }
}

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

    #[tokio::test]
    async fn test_session_creation() {
        let config = SessionManagerConfig::default();
        let manager = SessionManager::new(config);
        manager.start().await.unwrap();

        let session_id = manager
            .create_session("Test Session".to_string(), Some("Test description".to_string()))
            .await
            .unwrap();

        assert!(!session_id.is_empty());

        let session = manager.get_session(&session_id).await.unwrap();
        assert_eq!(session.name, "Test Session");
        assert!(session.description.is_some());
        assert!(matches!(session.state, SessionState::Active));
    }

    #[tokio::test]
    async fn test_command_history() {
        let config = SessionManagerConfig::default();
        let manager = SessionManager::new(config);
        manager.start().await.unwrap();

        let session_id = manager
            .create_session("Test Session".to_string(), None)
            .await
            .unwrap();

        let command = DebugCommand::GetMemoryProfile;
        let response = DebugResponse::Success {
            message: "Test response".to_string(),
            data: None,
        };

        manager
            .record_command(
                &session_id,
                command,
                Some(response),
                Duration::from_millis(10),
                "test-correlation-id".to_string(),
            )
            .await
            .unwrap();

        let history = manager.get_command_history(&session_id, Some(10)).await.unwrap();
        assert_eq!(history.len(), 1);
        assert_eq!(history[0].correlation_id, "test-correlation-id");
        assert!(history[0].success);
    }

    #[tokio::test]
    async fn test_checkpoint_creation() {
        let config = SessionManagerConfig::default();
        let manager = SessionManager::new(config);
        manager.start().await.unwrap();

        let session_id = manager
            .create_session("Test Session".to_string(), None)
            .await
            .unwrap();

        let checkpoint_id = manager
            .create_checkpoint(&session_id, "Test checkpoint")
            .await
            .unwrap();

        assert!(!checkpoint_id.is_empty());

        let session = manager.get_session(&session_id).await.unwrap();
        assert!(session.checkpoints.contains(&checkpoint_id));
    }

    #[tokio::test]
    async fn test_replay_functionality() {
        let config = SessionManagerConfig::default();
        let manager = SessionManager::new(config);
        manager.start().await.unwrap();

        let session_id = manager
            .create_session("Test Session".to_string(), None)
            .await
            .unwrap();

        // Add some commands to history
        for i in 0..5 {
            let command = DebugCommand::GetMemoryProfile;
            manager
                .record_command(
                    &session_id,
                    command,
                    None,
                    Duration::from_millis(10),
                    format!("correlation-{}", i),
                )
                .await
                .unwrap();
        }

        // Start replay
        manager.start_replay(&session_id, Some(0)).await.unwrap();

        // Get replay commands
        let mut replay_count = 0;
        while let Some(_command) = manager.get_next_replay_command(&session_id).await.unwrap() {
            replay_count += 1;
        }

        assert_eq!(replay_count, 5);

        // Session should be back to active state
        let session = manager.get_session(&session_id).await.unwrap();
        assert!(matches!(session.state, SessionState::Active));
    }

    #[tokio::test]
    async fn test_session_cleanup_logic() {
        let mut config = SessionManagerConfig::default();
        config.default_cleanup_hours = 0; // Immediate cleanup for testing

        let manager = SessionManager::new(config);
        manager.start().await.unwrap();

        let session_id = manager
            .create_session("Test Session".to_string(), None)
            .await
            .unwrap();

        let session = manager.get_session(&session_id).await.unwrap();
        assert!(session.should_cleanup()); // Should be marked for cleanup
    }

    #[tokio::test]
    async fn test_statistics() {
        let config = SessionManagerConfig::default();
        let manager = SessionManager::new(config);
        manager.start().await.unwrap();

        let _session_id = manager
            .create_session("Test Session".to_string(), None)
            .await
            .unwrap();

        let stats = manager.get_statistics().await;
        assert_eq!(stats["total_sessions"], 1);
        assert_eq!(stats["active_sessions"], 1);
        assert_eq!(stats["replaying_sessions"], 0);
    }
}