mecha10-cli 0.6.5

Mecha10 CLI tool
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
//! Config command handlers
//!
//! Handles pushing, pulling, and listing robot configurations.
//! Uses shared sync logic from mecha10-robot-config crate.

use crate::commands::config::{ConfigListArgs, ConfigPullArgs, ConfigPushArgs, ConfigValidateArgs};
use crate::context::CliContext;
use crate::services::credentials::CredentialsService;
use anyhow::{Context, Result};
use mecha10_robot_config::{build_configs_archive, unpack_configs_archive, RobotConfigClient};

/// Robot config API path (appended to control plane URL). Robot-config routes moved from
/// `/api/robot-config/robots/{id}/configs*` to `/api/robots/{id}/configs*` (LAB-2133) - this now
/// points straight at the robots resource.
const ROBOT_CONFIG_PATH: &str = "/api/robots";

/// Handle the config push command
///
/// Archives the whole `configs/` directory (plus `mecha10.json`) and uploads it as a single
/// blob to the robot-config service (LAB-2937 config-push simplification - see
/// `RobotConfigClient::upload_configs_archive`'s doc comment). No per-file diffing: every push
/// sends the whole tree, every time - a project's `configs/` directory is small, and diffing
/// added complexity without solving the actual problem (a handful of binary simulation-asset
/// files, bundled into one oversized bulk JSON request, tripped the service's 413 body-size
/// limit).
pub async fn handle_config_push(ctx: &mut CliContext, args: &ConfigPushArgs) -> Result<()> {
    println!();
    println!("Pushing configurations...");
    println!();

    mecha10_core::relay_topics::regenerate_websocket_bridge_relay_config(&ctx.working_dir)
        .context("Failed to regenerate websocket-bridge relay topics")?;

    let robot_id = get_robot_id(ctx, args.robot_id.as_deref()).await?;

    let configs_dir = match &args.path {
        Some(path) => path.clone(),
        None => ctx.working_dir.join("configs"),
    };

    if !configs_dir.exists() {
        println!("No configs/ directory found");
        println!();
        println!("Expected:");
        println!("  - configs/ directory with node/behavior/simulation/rl configs");
        println!("  - mecha10.json at project root");
        return Ok(());
    }

    println!("Robot ID:     {}", robot_id);
    println!("Configs dir:  {}", configs_dir.display());
    println!();

    if args.dry_run {
        println!("DRY RUN - No changes will be made");
        return Ok(());
    }

    let mecha10_json = ctx.working_dir.join("mecha10.json");
    let archive = build_configs_archive(&configs_dir, Some(&mecha10_json))
        .map_err(|e| anyhow::anyhow!("Failed to archive configs: {}", e))?;

    let client = create_config_client(ctx).await?;
    client
        .upload_configs_archive(&robot_id, archive)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to push configs: {}", e))?;

    println!("Pushed configs/");

    println!();
    Ok(())
}

/// Handle the config pull command
///
/// Downloads the whole `configs/` archive (plus `mecha10.json`) previously pushed by
/// `mecha10 config push` and unpacks it locally (LAB-2937 config-push simplification - see
/// `handle_config_push`). `mecha10.json` always lands at the project root; `--output` only
/// relocates where `configs/` itself is extracted to.
pub async fn handle_config_pull(ctx: &mut CliContext, args: &ConfigPullArgs) -> Result<()> {
    println!();
    println!("Pulling configurations...");
    println!();

    let robot_id = get_robot_id(ctx, args.robot_id.as_deref()).await?;

    let output_dir = args.output.clone().unwrap_or_else(|| ctx.working_dir.join("configs"));

    println!("Robot ID:    {}", robot_id);
    println!("Output dir:  {}", output_dir.display());
    println!();

    if output_dir.exists() && output_dir.read_dir().is_ok_and(|mut d| d.next().is_some()) && !args.force {
        return Err(anyhow::anyhow!(
            "{} already exists and is not empty - pass --force to overwrite",
            output_dir.display()
        ));
    }

    let client = create_config_client(ctx).await?;

    let archive = client
        .download_configs_archive(&robot_id)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to fetch configs: {}", e))?;

    let mecha10_json_dest = ctx.working_dir.join("mecha10.json");
    let wrote_mecha10_json = unpack_configs_archive(&archive, &output_dir, Some(&mecha10_json_dest))
        .await
        .map_err(|e| anyhow::anyhow!("Failed to unpack configs: {}", e))?;

    println!(
        "Pulled configs/{}",
        if wrote_mecha10_json { " + mecha10.json" } else { "" }
    );
    println!();

    Ok(())
}

/// Handle the config list command
///
/// Lists all configs for a robot.
pub async fn handle_config_list(ctx: &mut CliContext, args: &ConfigListArgs) -> Result<()> {
    println!();

    let robot_id = get_robot_id(ctx, args.robot_id.as_deref()).await?;

    println!("Configs for robot: {}", robot_id);
    println!();

    let client = create_config_client(ctx).await?;

    let configs = match client.get_configs(&robot_id).await {
        Ok(configs) => configs,
        Err(e) => {
            return Err(anyhow::anyhow!("Failed to fetch configs: {}", e));
        }
    };

    if configs.is_empty() {
        println!("No configs found");
        println!();
        return Ok(());
    }

    for config in configs {
        println!("{}:", config.config_key);
        println!("  Updated: {}", config.updated_at.format("%Y-%m-%d %H:%M:%S UTC"));
        println!("  Created by: {}", config.created_by);

        if args.verbose {
            let value_str = serde_json::to_string_pretty(&config.config_value).unwrap_or_else(|_| "{}".to_string());
            for line in value_str.lines() {
                println!("    {}", line);
            }
        }
        println!();
    }

    Ok(())
}

/// Push configs from the project's configs/ directory that have changed since last push.
///
/// Fetches current remote configs, compares by value, and only pushes new or modified entries.
/// Used by build and upload handlers to auto-push configs after a successful operation.
pub async fn push_configs(ctx: &mut CliContext) -> Result<()> {
    mecha10_core::relay_topics::regenerate_websocket_bridge_relay_config(&ctx.working_dir)
        .context("Failed to regenerate websocket-bridge relay topics")?;

    let configs_dir = ctx.working_dir.join("configs");

    if !configs_dir.exists() {
        println!("  No configs/ directory found, skipping config push");
        return Ok(());
    }

    let robot_id = get_robot_id(ctx, None).await?;

    let mecha10_json = ctx.working_dir.join("mecha10.json");
    let archive = build_configs_archive(&configs_dir, Some(&mecha10_json))
        .map_err(|e| anyhow::anyhow!("Failed to archive configs: {}", e))?;

    let client = create_config_client(ctx).await?;

    println!("  Pushing configs/ for robot {}...", robot_id);

    client
        .upload_configs_archive(&robot_id, archive)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to push configs: {}", e))?;

    println!("  ✅ Pushed configs/");

    Ok(())
}

/// Handle the config show command
///
/// Prints the resolved project identity (name, robot ID, control plane URL for the
/// active environment, login status, and local configs/ directory path). These
/// `name`/`robot_id` values must match `robot_project.name`/`robot_id` in the
/// robot's `~/.mecha10/launcher/config.json` — verify with `mecha10-launcher config show`
/// on the robot.
pub async fn handle_config_show(ctx: &mut CliContext) -> Result<()> {
    println!();

    if !ctx.is_project_initialized() {
        println!("Not inside a mecha10 project (no mecha10.json found).");
        println!();
        println!("Run `mecha10 init` to create a new project.");
        println!();
        return Ok(());
    }

    let project_config = ctx.load_project_config().await?;
    let env_name = project_config.environments.current_env_name();
    let control_plane_url = project_config.environments.control_plane_url();
    let auth_status = mecha10_auth::commands::auth_status_line()?;
    let configs_dir = ctx.working_dir.join("configs");

    println!("Project name:      {}", project_config.name);
    println!("Robot ID:          {}", project_config.robot.id);
    println!("Environment:       {}", env_name);
    println!("Control plane URL: {}", control_plane_url);
    println!("Auth status:       {}", auth_status);
    println!("Configs dir:       {}", configs_dir.display());
    println!();

    Ok(())
}

/// Handle the config validate command
///
/// Validates `mecha10.json` plus every node config it references, or --
/// with `--path` -- a single arbitrary config file (project, node, or
/// `model_catalog.toml`). This is the single command hooks/CI/build and
/// `mecha10 lint` all shell out to or call into for config validation (see
/// `docs/validate-configs.md`); it re-implements no validation logic of its
/// own, delegating entirely to [`crate::config_validation::validate_config`].
pub async fn handle_config_validate(ctx: &mut CliContext, args: &ConfigValidateArgs) -> Result<()> {
    println!();
    println!("🔎 Config Validation");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!();

    if args.path.is_none() && !ctx.is_project_initialized() {
        println!("❌ Not in a Mecha10 project directory (no mecha10.json found).");
        println!();
        println!("Run `mecha10 init` to create a new project, or pass --path to validate a single file.");
        println!();
        return Err(anyhow::anyhow!("Not in a Mecha10 project directory"));
    }

    match crate::config_validation::validate_config(args.path.as_deref()) {
        Ok(target) => {
            println!("✅ {} is valid", target.display());
            println!();
            Ok(())
        }
        Err(e) => {
            println!("❌ Config validation failed:");
            println!();
            println!("{:#}", e);
            println!();
            Err(e)
        }
    }
}

/// Handle the config edit command
///
/// Shows a scrollable picker of every editable config this project knows about (node
/// configs, behavior configs, RL job configs, the `configs/simulation/` config,
/// `mecha10.json`, and `simulation/` assets) and opens the selected one in `$EDITOR`
/// (falling back to `vi` if unset). See [`crate::ui::discover_editable_configs`] for the
/// pure discovery/categorization logic.
pub async fn handle_config_edit(ctx: &mut CliContext) -> Result<()> {
    println!();

    if !ctx.is_project_initialized() {
        println!("Not inside a mecha10 project (no mecha10.json found).");
        println!();
        println!("Run `mecha10 init` to create a new project.");
        println!();
        return Ok(());
    }

    let entries = crate::ui::discover_editable_configs(&ctx.working_dir);

    if entries.is_empty() {
        println!("No editable configs found under configs/, mecha10.json, or simulation/.");
        println!();
        println!("Run `mecha10 init` to scaffold a project, or `mecha10 config pull` to fetch existing configs.");
        println!();
        return Ok(());
    }

    let selected_path = run_config_edit_tui(entries)?;

    let Some(path) = selected_path else {
        return Ok(());
    };

    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string());

    let status = std::process::Command::new(&editor)
        .arg(&path)
        .status()
        .with_context(|| format!("Failed to launch editor '{editor}'"))?;

    if !status.success() {
        return Err(anyhow::anyhow!(
            "Editor '{editor}' exited with {}",
            status
                .code()
                .map_or_else(|| "a signal".to_string(), |code| code.to_string())
        ));
    }

    Ok(())
}

/// Run the config edit picker TUI to completion, restoring the terminal exactly like the
/// other ratatui-based pickers in this codebase (`handlers::topics::handle_topics_list`,
/// `handlers::diagnostics::handle_diagnostics`) before returning. Returns the selected file
/// path, or `None` if the user cancelled (Esc/q).
fn run_config_edit_tui(entries: Vec<crate::ui::EditableConfigEntry>) -> Result<Option<std::path::PathBuf>> {
    use crate::ui::{ConfigEditOutcome, ConfigEditTui};
    use crossterm::{
        event::{self, Event},
        execute,
        terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
    };
    use ratatui::{backend::CrosstermBackend, Terminal};
    use std::io::stdout;

    enable_raw_mode()?;
    let mut stdout_handle = stdout();
    execute!(stdout_handle, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout_handle);
    let mut terminal = Terminal::new(backend)?;

    let mut tui = ConfigEditTui::new(entries);

    let result: Result<Option<ConfigEditOutcome>> = loop {
        if let Err(e) = terminal.draw(|f| tui.draw(f)) {
            break Err(e.into());
        }

        match event::poll(std::time::Duration::from_millis(100)) {
            Ok(true) => match event::read() {
                Ok(Event::Key(key_event)) => tui.handle_key(key_event),
                Ok(_) => {}
                Err(e) => break Err(e.into()),
            },
            Ok(false) => {}
            Err(e) => break Err(e.into()),
        }

        if tui.should_quit() {
            break Ok(tui.take_outcome());
        }
    };

    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    let outcome = result?;

    Ok(match outcome {
        Some(ConfigEditOutcome::Selected(path)) => Some(path),
        Some(ConfigEditOutcome::Cancelled) | None => None,
    })
}

/// Get robot ID from args or project config
pub(crate) async fn get_robot_id(ctx: &mut CliContext, arg_robot_id: Option<&str>) -> Result<String> {
    if let Some(id) = arg_robot_id {
        return Ok(id.to_string());
    }

    if ctx.is_project_initialized() {
        let project_config = ctx.load_project_config().await?;
        return Ok(project_config.robot.id);
    }

    Err(anyhow::anyhow!(
        "No robot ID specified. Use --robot-id or run from a mecha10 project directory."
    ))
}

/// Create a RobotConfigClient with credentials
pub(crate) async fn create_config_client(ctx: &mut CliContext) -> Result<RobotConfigClient> {
    let credentials_service = CredentialsService::new();
    let credentials = if ctx.is_ci() {
        credentials_service
            .load()?
            .ok_or_else(|| anyhow::anyhow!("Not logged in. Run `mecha10 auth login` first."))?
    } else {
        mecha10_auth::ensure_authenticated_interactive(&credentials_service).await?
    };

    let project_config = ctx.load_project_config().await?;
    let control_plane_url = project_config.environments.control_plane_url();
    let config_url = format!("{}{}", control_plane_url, ROBOT_CONFIG_PATH);

    Ok(RobotConfigClient::with_user_id(
        config_url,
        credentials.api_key,
        Some(credentials.user_id),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::CliContextBuilder;
    use mecha10_robot_config::extract_configs_archive;
    use tempfile::tempdir;

    fn write_project_config(dir: &std::path::Path, robot_id: &str) -> std::path::PathBuf {
        let config_path = dir.join("mecha10.json");
        std::fs::write(
            &config_path,
            serde_json::json!({
                "name": "proj",
                "version": "0.1.0",
                "robot_id": robot_id,
            })
            .to_string(),
        )
        .unwrap();
        config_path
    }

    #[tokio::test]
    async fn get_robot_id_prefers_explicit_arg_over_project_config() {
        let dir = tempdir().unwrap();
        let config_path = write_project_config(dir.path(), "from-config");

        let mut ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .config_path(Some(config_path))
            .build()
            .unwrap();

        let robot_id = get_robot_id(&mut ctx, Some("from-arg")).await.unwrap();
        assert_eq!(robot_id, "from-arg");
    }

    #[tokio::test]
    async fn get_robot_id_falls_back_to_project_config() {
        let dir = tempdir().unwrap();
        let config_path = write_project_config(dir.path(), "from-config");

        let mut ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .config_path(Some(config_path))
            .build()
            .unwrap();

        let robot_id = get_robot_id(&mut ctx, None).await.unwrap();
        assert_eq!(robot_id, "from-config");
    }

    #[tokio::test]
    async fn get_robot_id_errors_when_no_arg_and_no_project() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join("mecha10.json");

        let mut ctx = CliContextBuilder::new()
            .working_dir(dir.path().to_path_buf())
            .config_path(Some(config_path))
            .build()
            .unwrap();

        let err = get_robot_id(&mut ctx, None).await.unwrap_err();
        assert!(err.to_string().contains("No robot ID specified"));
    }

    #[test]
    fn configs_archive_round_trips_nodes_and_simulation_images_together() {
        let dir = tempdir().unwrap();
        let configs_dir = dir.path().join("configs");

        std::fs::create_dir_all(configs_dir.join("nodes/@mecha10/motor")).unwrap();
        std::fs::write(configs_dir.join("nodes/@mecha10/motor/config.json"), r#"{"speed": 1}"#).unwrap();

        std::fs::create_dir_all(configs_dir.join("simulation/images")).unwrap();
        std::fs::write(configs_dir.join("simulation/images/aiko.jpg"), [0xFF, 0xD8, 0xFF, 0x00]).unwrap();

        let archive = build_configs_archive(&configs_dir, None).unwrap();

        let extract_dir = tempdir().unwrap();
        extract_configs_archive(&archive, extract_dir.path()).unwrap();

        assert_eq!(
            std::fs::read_to_string(extract_dir.path().join("configs/nodes/@mecha10/motor/config.json")).unwrap(),
            r#"{"speed": 1}"#
        );
        assert_eq!(
            std::fs::read(extract_dir.path().join("configs/simulation/images/aiko.jpg")).unwrap(),
            vec![0xFF, 0xD8, 0xFF, 0x00]
        );
    }
}