clawgarden-cli 0.7.2

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
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
//! 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 agent;
mod compose;
mod config;
mod deps;
mod garden;
mod provider;
mod providers;
mod secret;
mod security;
mod ui;
mod wizard;

use anyhow::Result;
use clap::{Parser, Subcommand};
use inquire::Confirm;
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)
        name: Option<String>,
    },
    /// Run full diagnostic — deps, container health, config validity
    Doctor {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// Remove a garden
    Remove {
        /// Garden name to remove
        name: Option<String>,
        /// Also delete garden files
        #[arg(short, long)]
        delete_files: bool,
    },
    /// Start a garden (Docker container)
    Up {
        /// Garden name (defaults to first registered)
        name: Option<String>,
        /// Rebuild the container image before starting
        #[arg(long)]
        build: bool,
    },
    /// Stop a garden (Docker container)
    Down {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// Restart a garden (stop + start)
    Restart {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// Stream logs from a garden
    Logs {
        /// Garden name (defaults to first registered)
        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 (defaults to first registered)
        name: Option<String>,
        /// Command to execute
        #[arg(trailing_var_arg = true)]
        command: Vec<String>,
    },
    /// Open an interactive shell inside a garden container
    Shell {
        /// Garden name (defaults to first registered)
        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 (defaults to first registered)
        name: Option<String>,
    },
    /// Manage agents in a garden
    Agent {
        #[command(subcommand)]
        command: AgentCommands,
    },
    /// Manage providers in a garden
    Provider {
        #[command(subcommand)]
        command: ProviderCommands,
    },
    /// Print CLI version information
    Version {},
    /// Manage secrets (API keys, bot tokens)
    Secret {
        #[command(subcommand)]
        command: SecretCommands,
    },
    /// Update CLI and rebuild all garden containers
    Update {
        /// Only update CLI, don't rebuild gardens
        #[arg(long)]
        cli_only: bool,
        /// Garden name (defaults to all gardens)
        name: Option<String>,
    },
}

#[derive(Subcommand)]
enum AgentCommands {
    /// Add a new agent to a garden
    Add {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// List agents in a garden
    List {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// Edit an agent's role or token
    Edit {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// Remove an agent from a garden
    Remove {
        /// Garden name (defaults to first registered)
        name: Option<String>,
        /// Agent name to remove
        agent: Option<String>,
    },
}

#[derive(Subcommand)]
enum ProviderCommands {
    /// Add a provider to a garden
    Add {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// List providers in a garden
    List {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// Edit a provider's model or API key
    Edit {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// Remove a provider from a garden
    Remove {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// Refresh provider model catalog cache
    Refresh {
        /// Provider ID (e.g. openrouter). If omitted, refreshes all catalog providers.
        provider_id: Option<String>,
    },
}

#[derive(Subcommand)]
enum SecretCommands {
    /// List all secrets (values masked)
    List {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// Get a secret value (for scripting)
    Get {
        /// Secret key
        key: String,
        /// Garden name (defaults to first registered)
        #[arg(short, long)]
        name: Option<String>,
    },
    /// Set a secret value (interactive if value omitted)
    Set {
        /// Secret key (e.g. OPENAI_API_KEY, TELEGRAM_BOT_TOKEN_ALEX)
        key: String,
        /// Secret value (will prompt if omitted)
        value: Option<String>,
        /// Garden name (defaults to first registered)
        #[arg(short, long)]
        name: Option<String>,
    },
    /// Remove a secret
    Remove {
        /// Secret key to remove
        key: String,
        /// Garden name (defaults to first registered)
        #[arg(short, long)]
        name: Option<String>,
    },
    /// Migrate secrets from .env to .secrets.toml
    Migrate {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
    /// Export secrets as .env format
    Env {
        /// Garden name (defaults to first registered)
        name: Option<String>,
    },
}

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.as_deref(), delete_files),
        Commands::Up { name, build } => cmd_up(name.as_deref(), build),
        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::Agent { command } => cmd_agent(command),
        Commands::Provider { command } => cmd_provider(command),
        Commands::Secret { command } => cmd_secret(command),
        Commands::Version {} => cmd_version(),
        Commands::Update { cli_only, name } => cmd_update(name.as_deref(), cli_only),
    };

    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");
                }
            }

            // Check 6: Security
            println!();
            println!("  {} Checking security...", "\x1b[1m\x1b[38;5;255m");
            println!();

            // Workspace path scan
            let workspace_dir = registry.workspace_dir(&garden_name);
            match security::scan_workspace_for_blocked_paths(&workspace_dir) {
                Ok(violations) => {
                    if violations.is_empty() {
                        ui::success("No blocked paths in workspace");
                    } else {
                        for v in &violations {
                            ui::error(&format!("Blocked path: {:?}", v));
                        }
                        all_ok = false;
                    }
                }
                Err(e) => {
                    ui::warn(&format!("Could not scan workspace: {}", e));
                }
            }

            // .env security
            let env_warnings = security::check_env_security(&env_file);
            if env_warnings.is_empty() {
                ui::success(".env file looks secure");
            } else {
                for w in &env_warnings {
                    ui::warn(w);
                }
            }

            // Allowlist
            let allowlist_path = workspace_dir.join("agents/.allowlist");
            match security::load_allowlist(&allowlist_path) {
                Ok(allowed) => {
                    ui::success(&format!("Allowlist: {} agent(s) permitted", allowed.len()));
                }
                Err(_) => {
                    ui::warn("No allowlist file found");
                }
            }
        }
    }

    // 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: Option<&str>, delete_files: bool) -> Result<ExitCode> {
    let name = garden::resolve_garden_name(name)?;

    println!();
    ui::section_header_no_step("🗑️", &format!("Remove Garden · {}", name));
    println!();

    if delete_files {
        ui::warn("This will remove the garden AND delete all files.");
    } else {
        ui::warn("This will remove the garden from the registry.");
        ui::hint("Files will be kept. Use --delete-files to remove them too.");
    }
    println!();

    let confirm = ui::retry_prompt(|| {
        Confirm::new(&format!("  Remove garden '{}'?", name))
            .with_default(false)
            .prompt()
    })?;

    if !confirm {
        ui::warn("Cancelled.");
        return Ok(ExitCode::SUCCESS);
    }

    garden::remove_garden(&name, delete_files)?;
    Ok(ExitCode::SUCCESS)
}

/// Start a garden
fn cmd_up(name: Option<&str>, build: bool) -> Result<ExitCode> {
    let name = resolve_garden_name(name)?;

    // Auto-detect if rebuild is needed: compare CLI version with last build version
    let should_build = build || needs_rebuild(&name);

    if should_build && !build {
        println!();
        ui::hint(&format!(
            "CLI v{} is newer than container — auto-rebuilding. Use --no-build to skip.",
            VERSION
        ));
        println!();
    }

    compose::start_garden(&name, should_build)?;

    // Stamp the version we just built
    if should_build {
        stamp_version(&name);
    }

    Ok(ExitCode::SUCCESS)
}

/// Check if the garden container needs rebuilding.
/// Compares the CLI version with the version stamped at last build.
/// Returns false if versions match (no rebuild needed) or on error.
fn needs_rebuild(name: &str) -> bool {
    let registry = match garden::load_gardens() {
        Ok(r) => r,
        Err(_) => return false,
    };
    let stamp_file = registry.garden_dir(name).join(".build-version");
    if !stamp_file.exists() {
        // First run with version tracking — stamp current version and rebuild once
        let _ = std::fs::write(&stamp_file, VERSION);
        return true;
    }
    let stamped = std::fs::read_to_string(&stamp_file).unwrap_or_default();
    let stamped = stamped.trim();
    stamped != VERSION
}

/// Write the current CLI version to the garden's build-version stamp.
fn stamp_version(name: &str) {
    let registry = match garden::load_gardens() {
        Ok(r) => r,
        Err(_) => return,
    };
    let stamp_file = registry.garden_dir(name).join(".build-version");
    let _ = std::fs::write(&stamp_file, VERSION);
}

/// 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)
}

/// Agent subcommands dispatcher
fn cmd_agent(command: AgentCommands) -> Result<ExitCode> {
    match command {
        AgentCommands::Add { name } => {
            agent::cmd_add(name.as_deref())?;
        }
        AgentCommands::List { name } => {
            agent::cmd_list(name.as_deref())?;
        }
        AgentCommands::Edit { name } => {
            agent::cmd_edit(name.as_deref())?;
        }
        AgentCommands::Remove { name, agent } => {
            agent::cmd_remove(name.as_deref(), agent.as_deref())?;
        }
    }
    Ok(ExitCode::SUCCESS)
}

/// Provider subcommands dispatcher
fn cmd_provider(command: ProviderCommands) -> Result<ExitCode> {
    match command {
        ProviderCommands::Add { name } => {
            provider::cmd_add(name.as_deref())?;
        }
        ProviderCommands::List { name } => {
            provider::cmd_list(name.as_deref())?;
        }
        ProviderCommands::Edit { name } => {
            provider::cmd_edit(name.as_deref())?;
        }
        ProviderCommands::Remove { name } => {
            provider::cmd_remove(name.as_deref())?;
        }
        ProviderCommands::Refresh { provider_id } => {
            provider::cmd_refresh(provider_id.as_deref())?;
        }
    }
    Ok(ExitCode::SUCCESS)
}

/// Secret subcommands dispatcher
fn cmd_secret(command: SecretCommands) -> Result<ExitCode> {
    match command {
        SecretCommands::List { name } => {
            secret::cmd_list(name.as_deref())?;
        }
        SecretCommands::Get { key, name } => {
            secret::cmd_get(name.as_deref(), &key)?;
        }
        SecretCommands::Set { key, value, name } => {
            secret::cmd_set(name.as_deref(), &key, value.as_deref())?;
        }
        SecretCommands::Remove { key, name } => {
            secret::cmd_remove(name.as_deref(), &key)?;
        }
        SecretCommands::Migrate { name } => {
            secret::cmd_migrate(name.as_deref())?;
        }
        SecretCommands::Env { name } => {
            secret::cmd_env(name.as_deref())?;
        }
    }
    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)
}

/// Update CLI and rebuild garden containers
fn cmd_update(name: Option<&str>, cli_only: bool) -> Result<ExitCode> {
    println!();
    println!(
        "  {}C L A W G A R D E N   U P D A T E{}",
        "\x1b[38;5;77m\x1b[1m", "\x1b[0m",
    );
    println!();

    // ── Step 1: Update CLI ──────────────────────────────────────────────
    let before_version = VERSION.to_string();

    ui::spinner("Checking for CLI updates...", 300);

    let has_cargo = std::process::Command::new("cargo")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    if !has_cargo {
        ui::warn("cargo not found — cannot auto-update CLI.");
        ui::hint("Install manually: cargo install clawgarden-cli");
    } else {
        ui::spinner("Updating clawgarden-cli via cargo...", 600);

        let install_output = std::process::Command::new("cargo")
            .args(["install", "clawgarden-cli"])
            .output();

        match install_output {
            Ok(output) => {
                let stderr = String::from_utf8_lossy(&output.stderr);
                if output.status.success() {
                    ui::success("CLI updated to latest version.");
                } else if stderr.contains("already installed")
                    || stderr.contains("up to date")
                    || stderr.contains("is already")
                {
                    ui::success(&format!("CLI is already up to date (v{})", before_version));
                } else {
                    ui::warn(&format!(
                        "CLI update: {}",
                        stderr.lines().last().unwrap_or("unknown error")
                    ));
                    ui::hint("Try: cargo install clawgarden-cli --force");
                }
            }
            Err(e) => {
                ui::warn(&format!("Failed to run cargo install: {}", e));
            }
        }
    }

    if cli_only {
        println!();
        ui::hint("Run 'garden update' (without --cli-only) to rebuild containers.");
        return Ok(ExitCode::SUCCESS);
    }

    // ── Step 2: Rebuild garden(s) ────────────────────────────────────────
    let registry = garden::load_gardens()?;

    let gardens_to_update: Vec<String> = if let Some(n) = name {
        if !registry.exists(n) {
            anyhow::bail!("Garden '{}' not found.", n);
        }
        vec![n.to_string()]
    } else if registry.gardens.is_empty() {
        anyhow::bail!("No gardens found. Run 'garden new' first.");
    } else {
        registry.gardens.iter().map(|g| g.name.clone()).collect()
    };

    println!();
    println!(
        "  {}Rebuilding {} garden(s)...{}",
        "\x1b[1m",
        gardens_to_update.len(),
        "\x1b[0m"
    );
    println!();

    for garden_name in &gardens_to_update {
        match compose::start_garden(garden_name, true) {
            Ok(_) => {
                stamp_version(garden_name);
            }
            Err(e) => {
                ui::warn(&format!("Garden '{}': {}", garden_name, e));
            }
        }
    }

    println!();
    ui::success("Update complete!");
    println!();

    Ok(ExitCode::SUCCESS)
}

/// Resolve garden name from argument or default
fn resolve_garden_name(name: Option<&str>) -> Result<String> {
    garden::resolve_garden_name(name)
}