mecha10-cli 0.6.3

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
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
//! 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_core::config::config_key_to_path;
use mecha10_robot_config::{
    collect_configs_from_dir, write_configs_to_dir, CollectOptions, RobotConfigClient, WriteOptions,
};

/// Robot config API path (appended to control plane URL)
const ROBOT_CONFIG_PATH: &str = "/api/robot-config";

/// Handle the config push command
///
/// Pushes local config files to the robot-config service.
pub async fn handle_config_push(ctx: &mut CliContext, args: &ConfigPushArgs) -> Result<()> {
    println!();
    println!("Pushing configurations...");
    println!();

    // Regenerate `websocket-bridge`'s relay topic allowlist from other nodes' own configs
    // (LAB relay-topics-core-deriver) before local config files get gathered below, so what
    // gets pushed to the control plane already reflects the current derived allowlist.
    mecha10_core::relay_topics::regenerate_websocket_bridge_relay_config(&ctx.working_dir)
        .context("Failed to regenerate websocket-bridge relay topics")?;

    // Get robot ID from args or project config
    let robot_id = get_robot_id(ctx, args.robot_id.as_deref()).await?;

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

    // Collect configs using shared function
    let options = CollectOptions {
        include_mecha10_json: true,
        project_root: Some(ctx.working_dir.clone()),
    };

    let configs = collect_configs_from_dir(&configs_dir, &options)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to collect configs: {}", e))?;

    if configs.is_empty() {
        println!("No config files found");
        println!();
        println!("Expected:");
        println!("  - configs/ directory with node configs");
        println!("  - mecha10.json at project root");
        return Ok(());
    }

    println!("Robot ID:     {}", robot_id);
    if configs_dir.exists() {
        println!("Configs dir:  {}", configs_dir.display());
    }
    println!();
    println!("Found {} config(s):", configs.len());
    for (key, _) in &configs {
        println!("  - {}", key);
    }
    println!();

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

    // Create client and push configs
    let client = create_config_client(ctx).await?;

    match client.bulk_upsert_configs(&robot_id, configs).await {
        Ok(result) => {
            println!(
                "Pushed {} config(s) ({} created, {} updated)",
                result.configs.len(),
                result.created,
                result.updated
            );
        }
        Err(e) => {
            return Err(anyhow::anyhow!("Failed to push configs: {}", e));
        }
    }

    println!();
    Ok(())
}

/// Handle the config pull command
///
/// Pulls configs from the robot-config service to local files.
pub async fn handle_config_pull(ctx: &mut CliContext, args: &ConfigPullArgs) -> Result<()> {
    println!();
    println!("Pulling configurations...");
    println!();

    // Get robot ID from args or project config
    let robot_id = get_robot_id(ctx, args.robot_id.as_deref()).await?;

    // Output directory
    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!();

    // Create client and fetch configs
    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));
        }
    };

    // Simulation assets (LAB-1984) live in the same robot-config store under a
    // `simulation-assets/` key prefix but use a different on-disk layout (`simulation/`, decoded
    // from base64) than node configs / mecha10.json — `mecha10 sim pull` handles those, so they
    // must not fall through to `write_configs_to_dir` here (it would mangle them into flat,
    // still-base64-encoded files under `configs/`).
    let configs = exclude_sim_assets(configs);

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

    println!("Found {} config(s):", configs.len());
    for config in &configs {
        println!("  - {}", config.config_key);
    }
    println!();

    // Write configs using shared function
    let write_options = WriteOptions {
        force: args.force,
        project_root: Some(ctx.working_dir.clone()),
    };

    let result = write_configs_to_dir(&configs, &output_dir, &write_options)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to write configs: {}", e))?;

    // Print what was written/skipped
    for key in &result.written_keys {
        let display_name = config_key_to_path(key);
        println!("  Wrote {}", display_name);
    }
    for key in &result.skipped_keys {
        let display_name = config_key_to_path(key);
        println!("  Skipped {} (exists, use --force to overwrite)", display_name);
    }

    println!();
    println!("Pulled {} config(s), skipped {}", result.written, result.skipped);
    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!();

    // Get robot ID from args or project config
    let robot_id = get_robot_id(ctx, args.robot_id.as_deref()).await?;

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

    // Create client and fetch configs
    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));
        }
    };

    // Simulation assets (LAB-1984) live in the same store under a `simulation-assets/` key
    // prefix and would otherwise show up here as noisy, unreadable base64 blobs — filter them
    // out, same as `handle_config_pull`. `mecha10 sim push`/`sim pull` report their own asset
    // list directly.
    let configs = exclude_sim_assets(configs);

    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"));
        if let Some(ref user) = config.updated_by {
            println!("  By: {}", user);
        }

        if args.verbose {
            let value_str = serde_json::to_string_pretty(&config.config_value).unwrap_or_else(|_| "{}".to_string());
            // Indent the JSON
            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<()> {
    // Regenerate `websocket-bridge`'s relay topic allowlist from other nodes' own configs
    // (LAB relay-topics-core-deriver) before local config files get gathered below - this is
    // also reached from `mecha10 build`'s auto-push step, not only the direct `config push`
    // command, so the call lives here too rather than only in `handle_config_push`.
    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 options = CollectOptions {
        include_mecha10_json: true,
        project_root: Some(ctx.working_dir.clone()),
    };

    let local_configs = collect_configs_from_dir(&configs_dir, &options)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to collect configs: {}", e))?;

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

    let client = create_config_client(ctx).await?;

    // Fetch current remote configs to diff against
    let remote_configs = client.get_configs(&robot_id).await.unwrap_or_default();

    let remote_map: std::collections::HashMap<&str, &mecha10_robot_config::ConfigValue> = remote_configs
        .iter()
        .map(|c| (c.config_key.as_str(), &c.config_value))
        .collect();

    // Only push configs that are new or have changed
    let changed: Vec<(String, mecha10_robot_config::ConfigValue)> = local_configs
        .into_iter()
        .filter(|(key, value)| {
            remote_map
                .get(key.as_str())
                .map_or(true, |remote_value| *remote_value != value)
        })
        .collect();

    if changed.is_empty() {
        println!("  No config changes detected");
        return Ok(());
    }

    println!(
        "  Pushing {} changed config(s) for robot {}...",
        changed.len(),
        robot_id
    );

    match client.bulk_upsert_configs(&robot_id, changed).await {
        Ok(result) => {
            println!(
                "  ✅ Pushed {} config(s) ({} created, {} updated)",
                result.configs.len(),
                result.created,
                result.updated
            );
        }
        Err(e) => {
            return Err(anyhow::anyhow!("Failed to push configs: {}", e));
        }
    }

    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!();
    println!("Note: `Project name` and `Robot ID` above must match `robot_project.name` and");
    println!("`robot_id` in the robot's ~/.mecha10/launcher/config.json — the launcher's binary");
    println!("registry looks up binaries by project name, and config/relay routing is scoped");
    println!("by robot ID. Run `mecha10-launcher config show` on the robot to verify.");
    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!();

    // `--path` validates an arbitrary file standalone, no project needed.
    // Otherwise, resolve the project's mecha10.json the same way every other
    // config-aware command does.
    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)
        }
    }
}

/// Drop simulation-asset entries (LAB-1984, `simulation-assets/` key prefix) from a batch of
/// configs fetched from the robot-config service, leaving only node configs and `mecha10.json`.
///
/// Shared by `handle_config_pull` (would otherwise mangle asset bytes into flat, still-base64
/// files under `configs/`) and `handle_config_list` (would otherwise print unreadable base64
/// blobs). `mecha10 sim push`/`sim pull` handle simulation assets separately.
fn exclude_sim_assets(configs: Vec<mecha10_robot_config::ConfigResponse>) -> Vec<mecha10_robot_config::ConfigResponse> {
    configs
        .into_iter()
        .filter(|c| !mecha10_robot_config::is_sim_asset_key(&c.config_key))
        .collect()
}

/// Get robot ID from args or project config
///
/// `pub(crate)` so `handlers::sim`'s `sim push`/`sim pull` (LAB-1984) can reuse the exact same
/// resolution order instead of duplicating it.
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());
    }

    // Try to get from project config
    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)` so `handlers::sim`'s `sim push`/`sim pull` (LAB-1984) can reuse the same
/// authenticated client the config commands use — simulation assets are synced through the same
/// robot-config service, just under a distinct config-key namespace (see
/// `mecha10_robot_config::sim_assets`).
pub(crate) async fn create_config_client(ctx: &mut CliContext) -> Result<RobotConfigClient> {
    // Load credentials
    let credentials_service = CredentialsService::new();
    let credentials = credentials_service
        .load()?
        .ok_or_else(|| anyhow::anyhow!("Not logged in. Run `mecha10 auth login` first."))?;

    // Get control plane URL from project config
    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 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
    }

    fn make_config_response(config_key: &str) -> mecha10_robot_config::ConfigResponse {
        mecha10_robot_config::ConfigResponse {
            id: "id".to_string(),
            robot_id: "robot".to_string(),
            config_key: config_key.to_string(),
            config_value: mecha10_robot_config::ConfigValue::new(),
            updated_by: None,
            updated_at: chrono::Utc::now(),
            created_at: chrono::Utc::now(),
        }
    }

    #[test]
    fn exclude_sim_assets_drops_simulation_asset_keys_only() {
        let configs = vec![
            make_config_response("@mecha10/motor"),
            make_config_response("mecha10.json"),
            make_config_response("simulation-assets/models/rover/model.json"),
            make_config_response("simulation-assets/environments/basic_arena/environment.json"),
        ];

        let filtered = exclude_sim_assets(configs);

        let keys: Vec<&str> = filtered.iter().map(|c| c.config_key.as_str()).collect();
        assert_eq!(keys, vec!["@mecha10/motor", "mecha10.json"]);
    }

    #[test]
    fn exclude_sim_assets_is_a_noop_when_nothing_matches() {
        let configs = vec![
            make_config_response("@mecha10/motor"),
            make_config_response("mecha10.json"),
        ];

        let filtered = exclude_sim_assets(configs);

        assert_eq!(filtered.len(), 2);
    }

    #[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();
        // No mecha10.json written, so the project is not initialized.
        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"));
    }
}