code-mesh-cli 0.1.0

Command-line interface for the Code-Mesh distributed swarm intelligence system
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
//! Status command implementation - System health checks and diagnostics

use crate::cmd::{CliError, Result, UI, Config};
use std::collections::HashMap;
use std::path::Path;
use std::fs;

/// Execute the status command
pub async fn execute(detailed: bool) -> Result<()> {
    let mut ui = UI::new();
    
    ui.print_logo()?;
    ui.info("Code Mesh System Status")?;
    ui.println("")?;

    // Overall health check
    let health_checks = run_health_checks().await?;
    let all_healthy = health_checks.iter().all(|(_, status)| status.healthy);

    if all_healthy {
        ui.success("All systems operational")?;
    } else {
        ui.warning("Some issues detected")?;
    }
    ui.println("")?;

    // Display system information
    display_system_info(&mut ui, detailed).await?;
    
    // Display health checks
    display_health_checks(&mut ui, &health_checks, detailed).await?;
    
    // Display configuration status
    display_config_status(&mut ui, detailed).await?;
    
    // Display authentication status
    display_auth_status(&mut ui, detailed).await?;
    
    // Display recent activity (if detailed)
    if detailed {
        display_recent_activity(&mut ui).await?;
    }

    Ok(())
}

/// System information
#[derive(Debug)]
struct SystemInfo {
    version: String,
    platform: String,
    architecture: String,
    rust_version: String,
    config_dir: String,
    data_dir: String,
    cache_dir: String,
}

/// Health check status
#[derive(Debug)]
struct HealthStatus {
    healthy: bool,
    message: String,
    details: Option<String>,
}

/// Run all health checks
async fn run_health_checks() -> Result<HashMap<String, HealthStatus>> {
    let mut checks = HashMap::new();

    // Configuration check
    checks.insert("Configuration".to_string(), check_configuration().await);
    
    // Directory permissions check
    checks.insert("Directories".to_string(), check_directories().await);
    
    // Authentication check
    checks.insert("Authentication".to_string(), check_authentication().await);
    
    // Dependencies check
    checks.insert("Dependencies".to_string(), check_dependencies().await);
    
    // Network connectivity check (basic)
    checks.insert("Network".to_string(), check_network().await);

    Ok(checks)
}

/// Check configuration status
async fn check_configuration() -> HealthStatus {
    match Config::load() {
        Ok(config) => {
            match config.validate() {
                Ok(()) => HealthStatus {
                    healthy: true,
                    message: "Configuration valid".to_string(),
                    details: Some(format!("Version: {}", config.version)),
                },
                Err(e) => HealthStatus {
                    healthy: false,
                    message: "Configuration invalid".to_string(),
                    details: Some(e.to_string()),
                },
            }
        }
        Err(e) => HealthStatus {
            healthy: false,
            message: "Configuration not found".to_string(),
            details: Some(e.to_string()),
        },
    }
}

/// Check directory permissions
async fn check_directories() -> HealthStatus {
    let dirs_to_check = vec![
        ("Config", Config::config_path()),
        ("Data", Config::data_dir()),
        ("Cache", Config::cache_dir()),
    ];

    let mut issues = Vec::new();

    for (name, dir_result) in dirs_to_check {
        match dir_result {
            Ok(dir) => {
                if let Some(parent) = dir.parent() {
                    if !parent.exists() {
                        if let Err(e) = fs::create_dir_all(parent) {
                            issues.push(format!("{} directory not accessible: {}", name, e));
                        }
                    }
                }
            }
            Err(e) => {
                issues.push(format!("{} directory path error: {}", name, e));
            }
        }
    }

    if issues.is_empty() {
        HealthStatus {
            healthy: true,
            message: "All directories accessible".to_string(),
            details: None,
        }
    } else {
        HealthStatus {
            healthy: false,
            message: "Directory access issues".to_string(),
            details: Some(issues.join("; ")),
        }
    }
}

/// Check authentication status
async fn check_authentication() -> HealthStatus {
    // Check environment variables
    let env_vars = vec![
        "ANTHROPIC_API_KEY",
        "OPENAI_API_KEY",
        "GOOGLE_API_KEY",
        "GITHUB_TOKEN",
    ];

    let env_auth_count = env_vars.iter()
        .filter(|var| std::env::var(var).is_ok())
        .count();

    // TODO: Check stored credentials using AuthManager
    let stored_auth_count = 0; // Placeholder

    let total_auth = env_auth_count + stored_auth_count;

    if total_auth > 0 {
        HealthStatus {
            healthy: true,
            message: format!("{} provider(s) configured", total_auth),
            details: Some(format!(
                "Environment: {}, Stored: {}",
                env_auth_count, stored_auth_count
            )),
        }
    } else {
        HealthStatus {
            healthy: false,
            message: "No authentication configured".to_string(),
            details: Some("Run 'code-mesh auth login' to set up authentication".to_string()),
        }
    }
}

/// Check dependencies
async fn check_dependencies() -> HealthStatus {
    let mut missing = Vec::new();
    let mut present = Vec::new();

    // Check for optional external tools
    let tools = vec![
        ("git", "Git version control"),
        ("rg", "Ripgrep for fast searching"),
        ("fzf", "Fuzzy finder"),
    ];

    for (tool, description) in tools {
        if crate::cmd::utils::Utils::command_exists(tool) {
            present.push(format!("{} ({})", tool, description));
        } else {
            missing.push(format!("{} ({})", tool, description));
        }
    }

    if missing.is_empty() {
        HealthStatus {
            healthy: true,
            message: "All optional tools available".to_string(),
            details: Some(format!("Found: {}", present.join(", "))),
        }
    } else {
        HealthStatus {
            healthy: true, // Not critical
            message: format!("{} optional tools missing", missing.len()),
            details: Some(format!("Missing: {}", missing.join(", "))),
        }
    }
}

/// Check network connectivity
async fn check_network() -> HealthStatus {
    // Simple connectivity check - try to resolve a DNS name
    // This is a basic check and doesn't test actual API endpoints
    
    use std::time::Duration;
    use tokio::time::timeout;
    
    let check_result = timeout(
        Duration::from_secs(5),
        tokio::net::TcpStream::connect("8.8.8.8:53")
    ).await;

    match check_result {
        Ok(Ok(_)) => HealthStatus {
            healthy: true,
            message: "Network connectivity available".to_string(),
            details: None,
        },
        Ok(Err(e)) => HealthStatus {
            healthy: false,
            message: "Network connectivity issues".to_string(),
            details: Some(e.to_string()),
        },
        Err(_) => HealthStatus {
            healthy: false,
            message: "Network check timed out".to_string(),
            details: Some("Connection attempt took too long".to_string()),
        },
    }
}

/// Display system information
async fn display_system_info(ui: &mut UI, detailed: bool) -> Result<()> {
    ui.info("System Information")?;
    ui.println("")?;

    let info = SystemInfo {
        version: env!("CARGO_PKG_VERSION").to_string(),
        platform: std::env::consts::OS.to_string(),
        architecture: std::env::consts::ARCH.to_string(),
        rust_version: "Unknown".to_string(), // Could use build-time detection
        config_dir: Config::config_path()?.display().to_string(),
        data_dir: Config::data_dir()?.display().to_string(),
        cache_dir: Config::cache_dir()?.display().to_string(),
    };

    let mut table = crate::cmd::ui::Table::new(vec![
        "Property".to_string(),
        "Value".to_string(),
    ]);

    table.add_row(vec!["Version".to_string(), info.version]);
    table.add_row(vec!["Platform".to_string(), format!("{}/{}", info.platform, info.architecture)]);
    
    if detailed {
        table.add_row(vec!["Config Directory".to_string(), info.config_dir]);
        table.add_row(vec!["Data Directory".to_string(), info.data_dir]);
        table.add_row(vec!["Cache Directory".to_string(), info.cache_dir]);
    }

    table.print(ui)?;
    ui.println("")?;

    Ok(())
}

/// Display health check results
async fn display_health_checks(
    ui: &mut UI,
    checks: &HashMap<String, HealthStatus>,
    detailed: bool,
) -> Result<()> {
    ui.info("Health Checks")?;
    ui.println("")?;

    let mut table = crate::cmd::ui::Table::new(vec![
        "Component".to_string(),
        "Status".to_string(),
        "Message".to_string(),
    ]);

    for (component, status) in checks {
        let status_icon = if status.healthy { "" } else { "" };
        let status_text = format!("{} {}", status_icon, if status.healthy { "OK" } else { "ISSUE" });
        
        table.add_row(vec![
            component.clone(),
            status_text,
            status.message.clone(),
        ]);
    }

    table.print(ui)?;

    // Show details if requested
    if detailed {
        ui.println("")?;
        ui.info("Details")?;
        ui.println("")?;

        for (component, status) in checks {
            if let Some(ref details) = status.details {
                ui.dim(&format!("{}: {}", component, details))?;
            }
        }
    }

    ui.println("")?;
    Ok(())
}

/// Display configuration status
async fn display_config_status(ui: &mut UI, detailed: bool) -> Result<()> {
    ui.info("Configuration")?;
    ui.println("")?;

    match Config::load() {
        Ok(config) => {
            let mut table = crate::cmd::ui::Table::new(vec![
                "Setting".to_string(),
                "Value".to_string(),
            ]);

            table.add_row(vec!["Default Profile".to_string(), config.default_profile.clone()]);
            table.add_row(vec!["Profiles".to_string(), config.profiles.len().to_string()]);
            
            if detailed {
                table.add_row(vec!["Auto Save Sessions".to_string(), config.global.auto_save_sessions.to_string()]);
                table.add_row(vec!["Session History Limit".to_string(), config.global.session_history_limit.to_string()]);
                table.add_row(vec!["Log Level".to_string(), config.global.log_level.clone()]);
                table.add_row(vec!["Theme".to_string(), config.global.theme.clone()]);
            }

            table.print(ui)?;
        }
        Err(e) => {
            ui.error(&format!("Failed to load configuration: {}", e))?;
        }
    }

    ui.println("")?;
    Ok(())
}

/// Display authentication status
async fn display_auth_status(ui: &mut UI, detailed: bool) -> Result<()> {
    ui.info("Authentication")?;
    ui.println("")?;

    let providers = vec![
        ("Anthropic", "ANTHROPIC_API_KEY"),
        ("OpenAI", "OPENAI_API_KEY"),
        ("Google", "GOOGLE_API_KEY"),
        ("GitHub", "GITHUB_TOKEN"),
    ];

    let mut table = crate::cmd::ui::Table::new(vec![
        "Provider".to_string(),
        "Environment".to_string(),
        "Stored".to_string(),
    ]);

    for (provider_name, env_var) in providers {
        let env_status = if std::env::var(env_var).is_ok() {
            "".to_string()
        } else {
            "".to_string()
        };

        // TODO: Check stored credentials
        let stored_status = "".to_string(); // Placeholder

        table.add_row(vec![provider_name.to_string(), env_status, stored_status]);
    }

    table.print(ui)?;
    ui.println("")?;

    Ok(())
}

/// Display recent activity
async fn display_recent_activity(ui: &mut UI) -> Result<()> {
    ui.info("Recent Activity")?;
    ui.println("")?;

    // TODO: Implement actual session/activity tracking
    ui.dim("No recent activity (feature not yet implemented)")?;
    ui.println("")?;

    Ok(())
}