clawgarden-cli 0.1.4

ClawGarden CLI - Multi-bot/multi-agent Garden management tool
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
//! ClawGarden CLI - Host-side garden management tool
//!
//! Manages the Garden (Docker container) lifecycle, bot/agent registry,
//! and provides operational commands like logs, exec, status, and doctor.

mod compose;
mod config;
mod deps;
mod garden;
mod providers;
mod security;
mod ui;
mod wizard;

use anyhow::Result;
use clap::{Parser, Subcommand};
use std::process::ExitCode;

/// ClawGarden CLI version (injected at compile time)
const VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(Parser)]
#[command(name = "garden")]
#[command(about = "ClawGarden CLI - Manage multi-bot/multi-agent Garden", long_about = None)]
#[command(version = VERSION)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Start interactive onboarding wizard to create a new garden
    New {
        /// Skip dependency check
        #[arg(long)]
        skip_deps: bool,
    },
    /// List all registered gardens
    List {},
    /// Show garden status — container health, uptime, resource usage
    Status {
        /// Garden name (defaults to first registered)
        #[arg(short, long)]
        name: Option<String>,
    },
    /// Run full diagnostic — deps, container health, config validity
    Doctor {
        /// Garden name (defaults to first registered)
        #[arg(short, long)]
        name: Option<String>,
    },
    /// Remove a garden
    Remove {
        /// Garden name to remove
        name: String,
        /// Also delete garden files
        #[arg(short, long)]
        delete_files: bool,
    },
    /// Start a garden (Docker container)
    Up {
        /// Garden name (defaults to first registered)
        #[arg(short, long)]
        name: Option<String>,
    },
    /// Stop a garden (Docker container)
    Down {
        /// Garden name
        #[arg(short, long)]
        name: Option<String>,
    },
    /// Restart a garden (stop + start)
    Restart {
        /// Garden name
        #[arg(short, long)]
        name: Option<String>,
    },
    /// Stream logs from a garden
    Logs {
        /// Garden name
        #[arg(short, long)]
        name: Option<String>,
        /// Follow log output
        #[arg(short, long)]
        follow: bool,
        /// Number of lines to show
        #[arg(short, long, default_value = "100")]
        lines: usize,
    },
    /// Execute command inside a garden container
    Exec {
        /// Garden name
        #[arg(short, long)]
        name: Option<String>,
        /// Command to execute
        command: Vec<String>,
    },
    /// Open an interactive shell inside a garden container
    Shell {
        /// Garden name
        #[arg(short, long)]
        name: Option<String>,
        /// Shell to use (default: bash)
        #[arg(short, long, default_value = "bash")]
        shell: String,
    },
    /// Check system dependencies
    Deps {},
    /// Configure a garden (bots, providers, etc.)
    Config {
        /// Garden name
        #[arg(short, long)]
        name: Option<String>,
    },
    /// Print CLI version information
    Version {},
    /// Initialize workspace directory structure (deprecated, use 'new')
    Init {
        /// Force re-initialization even if workspace exists
        #[arg(long)]
        force: bool,
    },
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    let result = match cli.command {
        Commands::New { skip_deps } => cmd_new(skip_deps),
        Commands::List {} => cmd_list(),
        Commands::Status { name } => cmd_status(name.as_deref()),
        Commands::Doctor { name } => cmd_doctor(name.as_deref()),
        Commands::Remove { name, delete_files } => cmd_remove(&name, delete_files),
        Commands::Up { name } => cmd_up(name.as_deref()),
        Commands::Down { name } => cmd_down(name.as_deref()),
        Commands::Restart { name } => cmd_restart(name.as_deref()),
        Commands::Logs {
            name,
            follow,
            lines,
        } => cmd_logs(name.as_deref(), follow, lines),
        Commands::Exec { name, command } => cmd_exec(name.as_deref(), &command),
        Commands::Shell { name, shell } => cmd_shell(name.as_deref(), &shell),
        Commands::Deps {} => cmd_deps(),
        Commands::Config { name } => cmd_config(name.as_deref()),
        Commands::Version {} => cmd_version(),
        Commands::Init { force } => cmd_init(force),
    };

    match result {
        Ok(exit_code) => exit_code,
        Err(e) => {
            eprintln!("\n  \x1b[38;5;203m✘\x1b[0m {}", e);
            ExitCode::FAILURE
        }
    }
}

// ── Command handlers ─────────────────────────────────────────────────────────

/// Start onboarding wizard
fn cmd_new(skip_deps: bool) -> Result<ExitCode> {
    if !skip_deps {
        deps::check()?;
        // Deps already checked — tell wizard to skip its own step 1
        wizard::run_wizard_skip_deps()?;
    } else {
        wizard::run_wizard()?;
    }
    Ok(ExitCode::SUCCESS)
}

/// List all gardens
fn cmd_list() -> Result<ExitCode> {
    garden::list_gardens()?;
    Ok(ExitCode::SUCCESS)
}

/// Show garden status
fn cmd_status(name: Option<&str>) -> Result<ExitCode> {
    let name = resolve_garden_name(name)?;

    println!();
    ui::section_header_no_step("🔍", &format!("Garden Status · {}", name));

    let container = compose::inspect_container(&name)?;

    let health_icon = match container.healthy {
        Some(true) => "\x1b[38;5;77m● healthy\x1b[0m".to_string(),
        Some(false) => "\x1b[38;5;203m● unhealthy\x1b[0m".to_string(),
        None => "\x1b[2m○ no healthcheck\x1b[0m".to_string(),
    };

    let state_icon = if container.running {
        "\x1b[38;5;77m▶ running\x1b[0m"
    } else {
        "\x1b[38;5;203m■ stopped\x1b[0m"
    };

    let mut rows = vec![
        (
            "🐳".to_string(),
            "Container".to_string(),
            container.name.clone(),
        ),
        (
            "📡".to_string(),
            "State".to_string(),
            format!("{}", state_icon),
        ),
        ("💊".to_string(), "Health".to_string(), health_icon),
        (
            "📋".to_string(),
            "Status".to_string(),
            container.status.clone(),
        ),
    ];

    if !container.image.is_empty() {
        rows.push((
            "🖼️ ".to_string(),
            "Image".to_string(),
            container.image.clone(),
        ));
    }

    if let Some(ref started) = container.started_at {
        if !started.is_empty() {
            rows.push(("🕐".to_string(), "Started".to_string(), started.clone()));
        }
    }

    // Resource usage (only if running)
    if container.running {
        if let Some(stats) = compose::container_stats(&name) {
            rows.push(("📊".to_string(), "Resources".to_string(), stats));
        }
    }

    // Config file checks
    let registry = garden::load_gardens()?;
    let compose_file = registry.compose_file(&name);
    let env_file = registry.env_file(&name);

    rows.push((
        "📄".to_string(),
        "Compose".to_string(),
        if compose_file.exists() {
            "✓ present".to_string()
        } else {
            "✗ missing".to_string()
        },
    ));
    rows.push((
        "🔐".to_string(),
        ".env".to_string(),
        if env_file.exists() {
            "✓ present".to_string()
        } else {
            "✗ missing".to_string()
        },
    ));

    ui::summary_box(&format!("🌱 {}", name), &rows);

    Ok(ExitCode::SUCCESS)
}

/// Run full diagnostic
fn cmd_doctor(name: Option<&str>) -> Result<ExitCode> {
    println!();
    ui::section_header_no_step("🩺", "Garden Doctor");

    let mut all_ok = true;

    // Check 1: Dependencies
    println!("  {} Checking dependencies...", "\x1b[1m\x1b[38;5;255m");
    println!();
    let dep_check = deps::DependencyCheck::check_all();
    dep_check.print_report();

    if !dep_check.is_ready() {
        all_ok = false;
    }

    // Check 2: Garden exists
    println!();
    println!("  {} Checking garden registry...", "\x1b[1m\x1b[38;5;255m");
    println!();

    let registry = garden::load_gardens()?;
    if registry.gardens.is_empty() {
        ui::warn("No gardens registered. Run 'garden new' first.");
        all_ok = false;
    } else {
        let garden_name = match name {
            Some(n) => n.to_string(),
            None => resolve_garden_name(None)?,
        };

        if !registry.exists(&garden_name) {
            ui::error(&format!("Garden '{}' not found in registry.", garden_name));
            all_ok = false;
        } else {
            ui::success(&format!("Garden '{}' found in registry.", garden_name));

            // Check 3: Files present
            println!();
            println!("  {} Checking garden files...", "\x1b[1m\x1b[38;5;255m");
            println!();

            let compose_file = registry.compose_file(&garden_name);
            let env_file = registry.env_file(&garden_name);
            let auth_file = registry.garden_dir(&garden_name).join("pi-auth.json");
            let reg_file = registry
                .workspace_dir(&garden_name)
                .join("agents/registry.json");

            let files = [
                ("docker-compose.yml", compose_file.exists()),
                (".env", env_file.exists()),
                ("pi-auth.json", auth_file.exists()),
                ("agents/registry.json", reg_file.exists()),
            ];

            for (fname, exists) in &files {
                if *exists {
                    ui::success(&format!("{:<25} present", fname));
                } else {
                    ui::error(&format!("{:<25} missing!", fname));
                    all_ok = false;
                }
            }

            // Check 4: Container status
            println!();
            println!("  {} Checking container...", "\x1b[1m\x1b[38;5;255m");
            println!();

            let container = compose::inspect_container(&garden_name)?;
            if container.running {
                ui::success(&format!("Container is running ({})", container.status));
                match container.healthy {
                    Some(true) => ui::success("Healthcheck: healthy"),
                    Some(false) => {
                        ui::error("Healthcheck: unhealthy!");
                        all_ok = false;
                    }
                    None => ui::warn("No healthcheck defined"),
                }
            } else {
                ui::warn(&format!("Container is not running ({})", container.status));
            }

            // Check 5: .env content validity
            println!();
            println!("  {} Checking configuration...", "\x1b[1m\x1b[38;5;255m");
            println!();

            if env_file.exists() {
                let env_content = std::fs::read_to_string(&env_file)?;
                let has_bot_token = env_content
                    .lines()
                    .any(|l| l.starts_with("TELEGRAM_BOT_TOKEN_"));
                let has_group_id = env_content
                    .lines()
                    .any(|l| l.starts_with("TELEGRAM_GROUP_ID="));

                if has_bot_token {
                    ui::success("Bot token(s) found in .env");
                } else {
                    ui::error("No bot tokens in .env");
                    all_ok = false;
                }

                if has_group_id {
                    ui::success("Telegram group ID configured");
                } else {
                    ui::warn("No Telegram group ID in .env");
                }
            }
        }
    }

    // Summary
    println!();
    ui::divider();
    if all_ok {
        ui::success("All checks passed — your garden is healthy! 🌿");
    } else {
        ui::warn("Some issues found. Fix them and run 'garden doctor' again.");
    }
    println!();

    if all_ok {
        Ok(ExitCode::SUCCESS)
    } else {
        Ok(ExitCode::FAILURE)
    }
}

/// Remove a garden
fn cmd_remove(name: &str, delete_files: bool) -> Result<ExitCode> {
    garden::remove_garden(name, delete_files)?;
    Ok(ExitCode::SUCCESS)
}

/// Start a garden
fn cmd_up(name: Option<&str>) -> Result<ExitCode> {
    let name = resolve_garden_name(name)?;
    compose::start_garden(&name)?;
    Ok(ExitCode::SUCCESS)
}

/// Stop a garden
fn cmd_down(name: Option<&str>) -> Result<ExitCode> {
    let name = resolve_garden_name(name)?;
    compose::stop_garden(&name)?;
    Ok(ExitCode::SUCCESS)
}

/// Restart a garden
fn cmd_restart(name: Option<&str>) -> Result<ExitCode> {
    let name = resolve_garden_name(name)?;
    compose::restart_garden(&name)?;
    Ok(ExitCode::SUCCESS)
}

/// Get garden logs
fn cmd_logs(name: Option<&str>, follow: bool, lines: usize) -> Result<ExitCode> {
    let name = resolve_garden_name(name)?;

    let status = compose::garden_logs(&name, follow, lines)?;
    Ok(ExitCode::from(status.code().unwrap_or(1) as u8))
}

/// Execute command in garden
fn cmd_exec(name: Option<&str>, command: &[String]) -> Result<ExitCode> {
    let name = resolve_garden_name(name)?;

    let status = compose::garden_exec(&name, command)?;
    Ok(ExitCode::from(status.code().unwrap_or(1) as u8))
}

/// Open interactive shell in garden
fn cmd_shell(name: Option<&str>, shell: &str) -> Result<ExitCode> {
    let name = resolve_garden_name(name)?;

    println!("\n  Entering garden '{}' via {}...", name, shell);
    println!("  {} Type 'exit' to leave.\n", "\x1b[2m");

    let status = compose::garden_shell(&name, shell)?;
    Ok(ExitCode::from(status.code().unwrap_or(1) as u8))
}

/// Check dependencies
fn cmd_deps() -> Result<ExitCode> {
    deps::check()?;
    Ok(ExitCode::SUCCESS)
}

/// Configure a garden (bots, providers, etc.)
fn cmd_config(name: Option<&str>) -> Result<ExitCode> {
    let name = resolve_garden_name(name)?;
    config::run_config(&name)?;
    Ok(ExitCode::SUCCESS)
}

/// Print version information
fn cmd_version() -> Result<ExitCode> {
    println!();
    println!(
        "  {}C L A W G A R D E N{}  {}v{}{}",
        "\x1b[38;5;77m\x1b[1m", "\x1b[0m", "\x1b[2m", VERSION, "\x1b[0m",
    );
    println!();
    println!("  {}Multi-Agent Garden CLI", "\x1b[2m");
    println!("  {}https://github.com/a7garden/clawgarden", "\x1b[2m");
    println!();

    Ok(ExitCode::SUCCESS)
}

/// Initialize workspace (legacy command)
fn cmd_init(_force: bool) -> Result<ExitCode> {
    ui::warn("'garden init' is deprecated. Use 'garden new' for interactive onboarding.");
    println!();

    // Try to run new wizard
    wizard::run_wizard()?;
    Ok(ExitCode::SUCCESS)
}

/// Resolve garden name from argument or default
fn resolve_garden_name(name: Option<&str>) -> Result<String> {
    if let Some(n) = name {
        return Ok(n.to_string());
    }

    let registry = garden::load_gardens()?;

    if registry.gardens.is_empty() {
        anyhow::bail!("No gardens found. Run 'garden new' to create one.");
    }

    if registry.gardens.len() == 1 {
        return Ok(registry.gardens[0].name.clone());
    }

    anyhow::bail!("Multiple gardens found. Specify --name <garden>.");
}