Skip to main content

sprite/utils/
session_recovery.rs

1//! Session recovery and cleanup utilities for the Sprite multi-agent workflow toolkit.
2//!
3//! This module provides functions for detecting orphaned sessions, cleaning up
4//! dead resources, and recovering from session failures.
5
6#![allow(dead_code)]
7
8use crate::utils::project;
9use crate::utils::tmux::{kill_session, list_sessions, SessionInfo};
10use anyhow::{Context, Result};
11use std::fs;
12use std::path::Path;
13use std::process::Command;
14use std::time::{Duration, SystemTime};
15
16/// Information about a session health status
17#[derive(Debug, Clone)]
18pub struct SessionHealth {
19    /// Session name
20    pub name: String,
21    /// Health status
22    pub status: SessionStatus,
23    /// Number of windows
24    pub windows: usize,
25    /// Number of active panes
26    pub active_panes: usize,
27    /// Session age in seconds
28    pub age_seconds: u64,
29    /// Last activity timestamp
30    pub last_activity: Option<SystemTime>,
31    /// Issues found
32    pub issues: Vec<SessionIssue>,
33}
34
35/// Session health status
36#[derive(Debug, Clone, PartialEq)]
37pub enum SessionStatus {
38    /// Session is healthy and responsive
39    Healthy,
40    /// Session exists but has issues
41    Degraded,
42    /// Session is unresponsive or dead
43    Dead,
44    /// Session is orphaned (no matching workspace)
45    Orphaned,
46}
47
48/// Types of session issues
49#[derive(Debug, Clone)]
50pub enum SessionIssue {
51    /// No active panes
52    NoActivePanes,
53    /// Session has been idle too long
54    IdleTooLong(Duration),
55    /// Session has zombie processes
56    ZombieProcesses(usize),
57    /// Workspace directory missing
58    WorkspaceMissing(String),
59    /// Git repository issues
60    GitIssues(String),
61    /// Tmux socket issues
62    TmuxSocketIssues(String),
63    /// Memory usage too high
64    HighMemoryUsage(u64),
65}
66
67/// Recovery options for sessions
68#[derive(Debug, Clone)]
69pub enum RecoveryAction {
70    /// No action needed
71    None,
72    /// Restart the session
73    Restart,
74    /// Clean up and kill session
75    Cleanup,
76    /// Attempt to repair session
77    Repair,
78    /// Prompt user for action
79    Prompt,
80}
81
82/// Session recovery configuration
83#[derive(Debug, Clone)]
84pub struct RecoveryConfig {
85    /// Maximum idle time before considering session stale
86    pub max_idle_time: Duration,
87    /// Maximum session age before cleanup
88    pub max_session_age: Duration,
89    /// Enable automatic cleanup
90    pub auto_cleanup: bool,
91    /// Directories to monitor for cleanup
92    pub cleanup_dirs: Vec<String>,
93    /// Processes to monitor
94    pub monitored_processes: Vec<String>,
95}
96
97impl Default for RecoveryConfig {
98    fn default() -> Self {
99        Self {
100            max_idle_time: Duration::from_secs(3600),    // 1 hour
101            max_session_age: Duration::from_secs(86400), // 24 hours
102            auto_cleanup: false,
103            cleanup_dirs: vec!["/tmp".to_string(), "/var/tmp".to_string()],
104            monitored_processes: vec!["tmux".to_string(), "git".to_string(), "sprite".to_string()],
105        }
106    }
107}
108
109/// Analyze the health of all tmux sessions
110pub fn analyze_session_health(config: &RecoveryConfig) -> Result<Vec<SessionHealth>> {
111    let sessions = match list_sessions() {
112        Ok(sessions) => sessions,
113        Err(_) => {
114            // Handle case where tmux server is not running or no sessions exist
115            return Ok(Vec::new());
116        }
117    };
118
119    let mut health_reports = Vec::new();
120
121    for session in sessions {
122        let health = check_session_health(&session, config)?;
123        health_reports.push(health);
124    }
125
126    Ok(health_reports)
127}
128
129/// Check the health of a specific session
130pub fn check_session_health(
131    session: &SessionInfo,
132    config: &RecoveryConfig,
133) -> Result<SessionHealth> {
134    let mut issues = Vec::new();
135    let mut active_panes = 0;
136
137    // Check if session actually responds
138    let is_responsive = check_session_responsiveness(&session.name)?;
139
140    // Check for active panes
141    match crate::utils::tmux::get_session_panes(&session.name) {
142        Ok(panes) => {
143            active_panes = panes.len();
144            if active_panes == 0 {
145                issues.push(SessionIssue::NoActivePanes);
146            }
147        }
148        Err(_) => {
149            issues.push(SessionIssue::TmuxSocketIssues(
150                "Failed to list session panes".to_string(),
151            ));
152        }
153    }
154
155    // Check session age
156    let age_seconds = parse_session_age(&session.created)?;
157    if age_seconds > config.max_session_age.as_secs() {
158        issues.push(SessionIssue::IdleTooLong(Duration::from_secs(age_seconds)));
159    }
160
161    // Check workspace integrity
162    if let Some(workspace_issue) = check_workspace_integrity(&session.name)? {
163        issues.push(workspace_issue);
164    }
165
166    // Check for zombie processes
167    if let Ok(zombie_count) = count_zombie_processes(&session.name) {
168        if zombie_count > 0 {
169            issues.push(SessionIssue::ZombieProcesses(zombie_count));
170        }
171    }
172
173    // Determine overall status
174    let status = if !is_responsive
175        || issues
176            .iter()
177            .any(|i| matches!(i, SessionIssue::TmuxSocketIssues(_)))
178    {
179        SessionStatus::Dead
180    } else if issues
181        .iter()
182        .any(|i| matches!(i, SessionIssue::WorkspaceMissing(_)))
183    {
184        SessionStatus::Orphaned
185    } else if !issues.is_empty() {
186        SessionStatus::Degraded
187    } else {
188        SessionStatus::Healthy
189    };
190
191    Ok(SessionHealth {
192        name: session.name.clone(),
193        status,
194        windows: session.windows,
195        active_panes,
196        age_seconds,
197        last_activity: None, // Would need additional tmux commands to get this
198        issues,
199    })
200}
201
202/// Check if a session is responsive
203fn check_session_responsiveness(session_name: &str) -> Result<bool> {
204    let output = Command::new("tmux")
205        .args(["display-message", "-p", "-t", session_name, "#S"])
206        .output()
207        .context("Failed to check session responsiveness")?;
208
209    Ok(output.status.success() && !output.stdout.is_empty())
210}
211
212/// Parse session creation time to seconds
213fn parse_session_age(_created_str: &str) -> Result<u64> {
214    // For now, return a reasonable default. In a real implementation,
215    // we would parse the tmux timestamp format
216    Ok(3600) // 1 hour default
217}
218
219/// Check workspace integrity for a session
220fn check_workspace_integrity(session_name: &str) -> Result<Option<SessionIssue>> {
221    // Attempt to locate the Sprite project root regardless of current working directory
222    match project::find_project_root() {
223        Ok(project_root) => {
224            let config_path = project_root.join("agents").join("agents.yaml");
225
226            if !config_path.exists() {
227                return Ok(Some(SessionIssue::WorkspaceMissing(format!(
228                    "Sprite configuration not found at {}",
229                    config_path.display()
230                ))));
231            }
232
233            let git_metadata = project_root.join(".git");
234            if !git_metadata.exists() {
235                return Ok(Some(SessionIssue::GitIssues(format!(
236                    "Project root {} is not a git repository",
237                    project_root.display()
238                ))));
239            }
240
241            Ok(None)
242        }
243        Err(_) => Ok(Some(SessionIssue::WorkspaceMissing(format!(
244            "No Sprite project detected for session {}",
245            session_name
246        )))),
247    }
248}
249
250/// Count zombie processes associated with a session
251fn count_zombie_processes(_session_name: &str) -> Result<usize> {
252    // This is a placeholder implementation
253    // In practice, we would parse /proc or use ps to find zombies
254    Ok(0)
255}
256
257/// Get recommended recovery action for a session
258pub fn get_recovery_action(health: &SessionHealth, config: &RecoveryConfig) -> RecoveryAction {
259    match health.status {
260        SessionStatus::Healthy => RecoveryAction::None,
261        SessionStatus::Dead => {
262            if config.auto_cleanup {
263                RecoveryAction::Cleanup
264            } else {
265                RecoveryAction::Prompt
266            }
267        }
268        SessionStatus::Orphaned => {
269            if config.auto_cleanup {
270                RecoveryAction::Cleanup
271            } else {
272                RecoveryAction::Prompt
273            }
274        }
275        SessionStatus::Degraded => {
276            if health
277                .issues
278                .iter()
279                .any(|i| matches!(i, SessionIssue::NoActivePanes))
280            {
281                RecoveryAction::Repair
282            } else if health.age_seconds > config.max_session_age.as_secs() {
283                if config.auto_cleanup {
284                    RecoveryAction::Cleanup
285                } else {
286                    RecoveryAction::Prompt
287                }
288            } else {
289                RecoveryAction::Repair
290            }
291        }
292    }
293}
294
295/// Perform recovery action on a session
296pub fn perform_recovery_action(session_name: &str, action: RecoveryAction) -> Result<()> {
297    match action {
298        RecoveryAction::None => Ok(()),
299        RecoveryAction::Restart => {
300            println!("๐Ÿ”„ Restarting session: {}", session_name);
301            // Kill existing session and recreate it
302            kill_session(session_name)?;
303            // In practice, we'd need to recreate the session with proper layout
304            Ok(())
305        }
306        RecoveryAction::Cleanup => {
307            println!("๐Ÿงน Cleaning up session: {}", session_name);
308            cleanup_session_resources(session_name)?;
309            kill_session(session_name)?;
310            Ok(())
311        }
312        RecoveryAction::Repair => {
313            println!("๐Ÿ”ง Repairing session: {}", session_name);
314            repair_session(session_name)?;
315            Ok(())
316        }
317        RecoveryAction::Prompt => {
318            println!("โ“ Action required for session: {}", session_name);
319            // In practice, this would prompt the user
320            Ok(())
321        }
322    }
323}
324
325/// Clean up resources associated with a session
326pub fn cleanup_session_resources(session_name: &str) -> Result<()> {
327    // Clean up temporary files
328    let temp_patterns = vec![
329        format!("/tmp/sprite-{}-*", session_name),
330        format!("/var/tmp/sprite-{}-*", session_name),
331        format!("/tmp/tmux-{}*", session_name),
332    ];
333
334    for pattern in temp_patterns {
335        if let Ok(output) = Command::new("find")
336            .args(["/tmp", "-name", &pattern, "-delete"])
337            .output()
338        {
339            if !output.status.success() {
340                eprintln!(
341                    "Warning: Failed to cleanup pattern {}: {}",
342                    pattern,
343                    String::from_utf8_lossy(&output.stderr)
344                );
345            }
346        }
347    }
348
349    // Clean up any sprite-specific state files
350    let state_dir = Path::new(".sprites");
351    if state_dir.exists() {
352        let session_state = state_dir.join(format!("{}.json", session_name));
353        if session_state.exists() {
354            fs::remove_file(&session_state).with_context(|| {
355                format!("Failed to remove session state file: {:?}", session_state)
356            })?;
357        }
358    }
359
360    Ok(())
361}
362
363/// Attempt to repair a degraded session
364fn repair_session(session_name: &str) -> Result<()> {
365    // Check if session has no active panes
366    match crate::utils::tmux::get_session_panes(session_name) {
367        Ok(panes) if panes.is_empty() => {
368            // Try to create a new window
369            crate::utils::tmux::create_window(session_name, "recovery")?;
370            println!("โœ… Created recovery window for session: {}", session_name);
371        }
372        Ok(_) => {
373            println!("โœ… Session {} appears to be functioning", session_name);
374        }
375        Err(e) => {
376            eprintln!("โŒ Failed to repair session {}: {}", session_name, e);
377            return Err(e);
378        }
379    }
380
381    Ok(())
382}
383
384/// Clean up old sessions based on configuration
385pub fn cleanup_old_sessions(config: &RecoveryConfig) -> Result<Vec<String>> {
386    let health_reports = analyze_session_health(config)?;
387    let mut cleaned_sessions = Vec::new();
388
389    for health in health_reports {
390        let action = get_recovery_action(&health, config);
391
392        if matches!(action, RecoveryAction::Cleanup) {
393            if let Err(e) = perform_recovery_action(&health.name, action) {
394                eprintln!("Failed to cleanup session {}: {}", health.name, e);
395            } else {
396                cleaned_sessions.push(health.name);
397            }
398        }
399    }
400
401    Ok(cleaned_sessions)
402}
403
404/// Clean up temporary files and directories
405pub fn cleanup_temp_files(config: &RecoveryConfig) -> Result<()> {
406    for temp_dir in &config.cleanup_dirs {
407        if Path::new(temp_dir).exists() {
408            cleanup_directory(temp_dir, "sprite-*")?;
409            cleanup_directory(temp_dir, "tmux-*")?;
410        }
411    }
412    Ok(())
413}
414
415/// Clean up files matching a pattern in a directory
416fn cleanup_directory(dir: &str, pattern: &str) -> Result<()> {
417    let output = Command::new("find")
418        .args([dir, "-name", pattern, "-mtime", "+1", "-delete"])
419        .output()
420        .context("Failed to cleanup temporary files")?;
421
422    if !output.status.success() {
423        eprintln!(
424            "Warning: Failed to cleanup {} in {}: {}",
425            pattern,
426            dir,
427            String::from_utf8_lossy(&output.stderr)
428        );
429    }
430
431    Ok(())
432}
433
434/// Generate a session health report
435pub fn generate_health_report(health_reports: &[SessionHealth]) -> String {
436    let mut report = String::new();
437    report.push_str("๐Ÿฅ Session Health Report\n");
438    report.push_str("========================\n\n");
439
440    let mut healthy_count = 0;
441    let mut degraded_count = 0;
442    let mut dead_count = 0;
443    let mut orphaned_count = 0;
444
445    for health in health_reports {
446        match health.status {
447            SessionStatus::Healthy => healthy_count += 1,
448            SessionStatus::Degraded => degraded_count += 1,
449            SessionStatus::Dead => dead_count += 1,
450            SessionStatus::Orphaned => orphaned_count += 1,
451        }
452
453        let status_icon = match health.status {
454            SessionStatus::Healthy => "๐ŸŸข",
455            SessionStatus::Degraded => "๐ŸŸก",
456            SessionStatus::Dead => "๐Ÿ”ด",
457            SessionStatus::Orphaned => "โšช",
458        };
459
460        report.push_str(&format!(
461            "{} {} ({} windows, {} panes, {}s old)\n",
462            status_icon, health.name, health.windows, health.active_panes, health.age_seconds
463        ));
464
465        if !health.issues.is_empty() {
466            for issue in &health.issues {
467                let issue_desc = match issue {
468                    SessionIssue::NoActivePanes => "No active panes".to_string(),
469                    SessionIssue::IdleTooLong(duration) => format!("Idle for {:?}", duration),
470                    SessionIssue::ZombieProcesses(count) => format!("{} zombie processes", count),
471                    SessionIssue::WorkspaceMissing(path) => format!("Workspace missing: {}", path),
472                    SessionIssue::GitIssues(msg) => format!("Git issues: {}", msg),
473                    SessionIssue::TmuxSocketIssues(msg) => format!("Tmux socket issues: {}", msg),
474                    SessionIssue::HighMemoryUsage(bytes) => {
475                        format!("High memory usage: {} MB", bytes / 1024 / 1024)
476                    }
477                };
478                report.push_str(&format!("    โš ๏ธ  {}\n", issue_desc));
479            }
480        }
481        report.push('\n');
482    }
483
484    report.push_str("--- Summary ---\n");
485    report.push_str(&format!("๐ŸŸข Healthy: {}\n", healthy_count));
486    report.push_str(&format!("๐ŸŸก Degraded: {}\n", degraded_count));
487    report.push_str(&format!("๐Ÿ”ด Dead: {}\n", dead_count));
488    report.push_str(&format!("โšช Orphaned: {}\n", orphaned_count));
489
490    report
491}
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496
497    #[test]
498    fn test_recovery_config_default() {
499        let config = RecoveryConfig::default();
500        assert_eq!(config.max_idle_time, Duration::from_secs(3600));
501        assert_eq!(config.max_session_age, Duration::from_secs(86400));
502        assert!(!config.auto_cleanup);
503    }
504
505    #[test]
506    fn test_session_age_parsing() {
507        let age = parse_session_age("created Wed Oct 18 10:30:00 2023").unwrap();
508        assert_eq!(age, 3600); // Default fallback value
509    }
510
511    #[test]
512    fn test_health_report_generation() {
513        let health = SessionHealth {
514            name: "test-session".to_string(),
515            status: SessionStatus::Healthy,
516            windows: 3,
517            active_panes: 3,
518            age_seconds: 1800,
519            last_activity: None,
520            issues: vec![],
521        };
522
523        let report = generate_health_report(&[health]);
524        assert!(report.contains("Session Health Report"));
525        assert!(report.contains("test-session"));
526        assert!(report.contains("๐ŸŸข"));
527    }
528
529    #[test]
530    fn test_recovery_action_selection() {
531        let config = RecoveryConfig::default();
532
533        let healthy_session = SessionHealth {
534            name: "healthy".to_string(),
535            status: SessionStatus::Healthy,
536            windows: 1,
537            active_panes: 1,
538            age_seconds: 100,
539            last_activity: None,
540            issues: vec![],
541        };
542
543        let action = get_recovery_action(&healthy_session, &config);
544        assert!(matches!(action, RecoveryAction::None));
545    }
546}