mecha10-cli 0.7.0

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
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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
//! 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::paths;
use crate::services::credentials::CredentialsService;
use crate::services::TemplateDownloadService;
use anyhow::{Context, Result};
use mecha10_robot_config::{collect_config_files, write_config_value, RobotConfigClient};
use std::path::Path;

pub(crate) const ROBOT_CONFIG_PATH: &str = "/api/robots";

/// Handle the config push command
///
/// Walks the whole `configs/` directory (plus `mecha10.json`) and pushes each file as its own
/// config key, one PUT per key - reverted off LAB-2937's single tar.gz-archive-per-robot upload:
/// the dashboard can't display or version an opaque blob, and the server now versions every key
/// on each upsert. No client-side diffing either: every push sends every key, every time - a
/// project's `configs/` tree is small, and per-key HTTP requests stay well under any body-size
/// limit regardless.
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!();

    println!("Validating configs...");
    match crate::config_validation::validate_configs(&ctx.working_dir, crate::config_validation::ConfigKind::ALL) {
        Ok(()) => println!("✅ All configs are valid"),
        Err(e) => {
            println!("❌ Config validation failed:");
            println!();
            println!("{:#}", e);
            println!();
            return Err(e.context("Refusing to push: fix the invalid config(s) above and try again"));
        }
    }
    println!();

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

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

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

    let client = create_config_client(ctx).await?;
    for (key, value) in &configs {
        client
            .upsert_config(&robot_id, key, value.clone())
            .await
            .map_err(|e| anyhow::anyhow!("Failed to push config '{}': {}", key, e))?;
    }

    println!("Pushed {} config(s)", configs.len());

    println!();
    Ok(())
}

/// Handle the config pull command
///
/// Fetches every config key for the robot and writes each back to disk individually - reverted
/// off LAB-2937's single tar.gz archive (see `handle_config_push`). `mecha10.json` always lands
/// at the project root; `--output` only relocates where the rest of `configs/` is written.
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 configs = client
        .get_configs(&robot_id)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to fetch configs: {}", e))?;

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

    let mecha10_json_dest = ctx.working_dir.join("mecha10.json");
    let mut wrote_mecha10_json = false;
    for config in &configs {
        write_config_value(
            &output_dir,
            Some(&mecha10_json_dest),
            &config.config_key,
            &config.config_value,
        )
        .await
        .map_err(|e| anyhow::anyhow!("Failed to write config '{}': {}", config.config_key, e))?;
        if config.config_key == "mecha10.json" {
            wrote_mecha10_json = true;
        }
    }

    println!(
        "Pulled {} config(s){}",
        configs.len(),
        if wrote_mecha10_json {
            " (incl. 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 every config file from the project's `configs/` directory (plus `mecha10.json`) that
/// differs from what's currently stored for the robot, one key per file. Used by build, upload,
/// and train handlers to auto-push configs after a successful operation / before dispatching a
/// job.
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 configs = collect_config_files(&configs_dir, Some(&mecha10_json))
        .await
        .map_err(|e| anyhow::anyhow!("Failed to collect configs: {}", e))?;

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

    let client = create_config_client(ctx).await?;

    let remote = client
        .get_configs(&robot_id)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to fetch current configs for robot {}: {}", robot_id, e))?;
    let remote_by_key: std::collections::HashMap<&str, &mecha10_robot_config::ConfigValue> = remote
        .iter()
        .map(|c| (c.config_key.as_str(), &c.config_value))
        .collect();

    let to_push: Vec<&(String, mecha10_robot_config::ConfigValue)> = configs
        .iter()
        .filter(|(key, value)| remote_by_key.get(key.as_str()) != Some(&value))
        .collect();

    if to_push.is_empty() {
        println!("  Configs unchanged, skipping push");
        return Ok(());
    }

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

    for (key, value) in &to_push {
        client
            .upsert_config(&robot_id, key, value.clone())
            .await
            .map_err(|e| anyhow::anyhow!("Failed to push config '{}': {}", key, e))?;
    }

    println!("  ✅ Pushed {} config(s)", to_push.len());

    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 `$VISUAL`/`$EDITOR`
/// (falling back to `vi` if neither is set). 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_command = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| "vi".to_string());

    let mut parts = editor_command.split_whitespace();
    let editor = parts
        .next()
        .ok_or_else(|| anyhow::anyhow!("$VISUAL/$EDITOR is set but empty"))?;

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

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

/// Framework-tier (`@mecha10/`) bundled behavior templates, relative to the cached templates
/// directory for a given version - see `BehaviorGeneratorService`'s module doc and
/// `packages/mecha10-templates/templates/configs/behaviors/@mecha10/` for the bundled set.
const FRAMEWORK_BEHAVIORS_TEMPLATE_DIR: &str = "configs/behaviors/@mecha10";

/// Handle the config sync command
///
/// Closes the gap `mecha10 init` otherwise leaves open: framework-tier (`@mecha10/`) behaviors
/// are only ever written to disk by `mecha10 init` at scaffold time (see
/// `handlers::init::copy_downloaded_templates`). A project scaffolded before a given bundled
/// behavior existed (e.g. `instance-track`/`takeoff-land`) never gets it - there was previously no
/// command to backfill it, so `behavior-executor`'s auto-discovery
/// (`mecha10_behavior_runtime::config::loader::list_available_behaviors`) and the dashboard's
/// behavior list simply never see it.
///
/// Resolves the current bundled behaviors the exact same way `mecha10 init` does - via
/// `TemplateDownloadService`, never by reading the local source tree directly - diffs them
/// against what's already on disk under `configs/behaviors/@mecha10/`, and copies in only what's
/// missing. Non-destructive: project-tier custom behaviors (`configs/behaviors/<name>/` without
/// the `@mecha10/` prefix) are never touched, and an `@mecha10/<name>` directory that already
/// exists on disk (e.g. a prior sync, or a user/tool customization) is never overwritten - this
/// only ever creates directories that were missing.
pub async fn handle_config_sync(ctx: &mut CliContext) -> Result<()> {
    println!();
    println!("Syncing framework behaviors...");
    println!();

    if !ctx.is_project_initialized() {
        anyhow::bail!("Not in a Mecha10 project directory");
    }

    let project_config = ctx.load_project_config().await?;
    let platform = project_config.robot.platform.as_deref().unwrap_or("rover").to_string();
    let working_dir = ctx.working_dir.clone();

    let template_download = ctx.template_download();
    let version = template_download
        .resolve_version()
        .await
        .context("Failed to resolve templates version")?;
    template_download
        .ensure_templates(&version)
        .await
        .context("Failed to fetch bundled templates")?;

    let added = sync_framework_behaviors(template_download, &working_dir, &version)?;

    println!("Platform: {}", platform);
    println!();

    if added.is_empty() {
        println!("✅ Framework behaviors are already up to date.");
    } else {
        println!("Added {} new framework behavior(s):", added.len());
        for name in &added {
            println!("  - @mecha10/{}", name);
        }
    }
    println!();

    Ok(())
}

/// Copy in any `@mecha10/<name>` framework behavior that exists in the bundled templates for
/// `version` but is missing on disk under `configs/behaviors/@mecha10/` in `project_root`.
///
/// Only ever adds a whole, previously-absent behavior directory - never touches an `@mecha10/
/// <name>` directory that already exists (so a customized bundled behavior is never clobbered),
/// and never looks at `configs/behaviors/<name>/` project-tier directories at all. Returns the
/// names of behaviors that were newly copied in, sorted for deterministic output.
fn sync_framework_behaviors(
    template_download: &TemplateDownloadService,
    project_root: &Path,
    version: &str,
) -> Result<Vec<String>> {
    let entries = template_download
        .list_template_dir(version, FRAMEWORK_BEHAVIORS_TEMPLATE_DIR)
        .context("Failed to list bundled framework behaviors")?;

    let mut behavior_names: Vec<String> = entries
        .into_iter()
        .filter(|path| path.is_dir())
        .filter_map(|path| path.file_name().map(|n| n.to_string_lossy().into_owned()))
        .collect();
    behavior_names.sort();

    let mut added = Vec::new();
    for name in behavior_names {
        let dest = project_root.join(paths::config::framework_behavior_dir(&name));
        if dest.exists() {
            continue;
        }

        let template_rel = format!("{}/{}", FRAMEWORK_BEHAVIORS_TEMPLATE_DIR, name);
        template_download
            .copy_template_dir(version, &template_rel, &dest)
            .with_context(|| format!("Failed to copy bundled behavior '{}'", name))?;
        added.push(name);
    }

    Ok(added)
}

/// 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 tempfile::{tempdir, 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"));
    }

    /// LAB-4246: `mecha10 config push` must run the full build-time validation gate
    /// (`config_validation::validate_configs`) before collecting/pushing anything, and refuse
    /// to push at all when any config fails its schema -- here, an `environment.json` missing
    /// every required field. `args.robot_id` is supplied explicitly so this never reaches
    /// `create_config_client`/auth, keeping the test offline; the validation gate runs well
    /// before that point in `handle_config_push`, so a failure here proves it short-circuits
    /// before any push/network activity, not just before auth happens to fail first.
    #[tokio::test]
    async fn config_push_fails_cleanly_and_does_not_push_when_a_config_is_invalid() {
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({"name": "proj", "version": "1.0.0"}).to_string(),
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join("configs/simulation/environments/broken_env")).unwrap();
        std::fs::write(
            dir.path()
                .join("configs/simulation/environments/broken_env/environment.json"),
            serde_json::json!({}).to_string(),
        )
        .unwrap();

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

        let args = ConfigPushArgs {
            path: None,
            robot_id: Some("test-robot".to_string()),
            dry_run: true,
        };

        let err = handle_config_push(&mut ctx, &args).await.unwrap_err();
        assert!(
            err.to_string().contains("Refusing to push"),
            "expected the push to be refused, got: {}",
            err
        );
    }

    /// Companion to the failure case above: a project whose configs all pass validation
    /// (project/node, simulation environment) must sail through the gate and reach the
    /// dry-run short-circuit (still offline, no auth/network needed).
    #[tokio::test]
    async fn config_push_proceeds_past_validation_when_every_config_is_valid() {
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("mecha10.json"),
            serde_json::json!({"name": "proj", "version": "1.0.0"}).to_string(),
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join("configs/simulation/environments/basic_arena")).unwrap();
        std::fs::write(
            dir.path()
                .join("configs/simulation/environments/basic_arena/environment.json"),
            serde_json::json!({
                "id": "basic_arena",
                "version": "1.0.0",
                "name": "Basic Arena",
                "description": "A test arena",
                "scene_path": "res://basic_arena.tscn",
                "dimensions": {"width": 20.0, "length": 20.0, "height": 3.0, "unit": "meters"},
                "features": {}
            })
            .to_string(),
        )
        .unwrap();

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

        let args = ConfigPushArgs {
            path: None,
            robot_id: Some("test-robot".to_string()),
            dry_run: true,
        };

        let result = handle_config_push(&mut ctx, &args).await;
        assert!(result.is_ok(), "{:?}", result.err());
    }

    #[tokio::test]
    async fn per_key_push_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 collected = collect_config_files(&configs_dir, None).await.unwrap();
        assert_eq!(collected.len(), 2);

        let extract_dir = tempdir().unwrap();
        for (key, value) in &collected {
            write_config_value(&extract_dir.path().join("configs"), None, key, value)
                .await
                .unwrap();
        }

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

    /// Stage a fake bundled-templates cache (mirrors the real release layout
    /// `template_download.rs`'s own tests build) containing one `@mecha10/<name>/config.json`
    /// per entry in `behaviors`, and return a `TemplateDownloadService` pointed at it.
    fn stage_bundled_behaviors(version: &str, behaviors: &[(&str, &str)]) -> (TempDir, TemplateDownloadService) {
        let cache = tempdir().unwrap();
        let templates_dir = cache.path().join(format!("v{version}")).join("templates");

        for (name, config_json) in behaviors {
            let dir = templates_dir.join(FRAMEWORK_BEHAVIORS_TEMPLATE_DIR).join(name);
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join("config.json"), config_json).unwrap();
        }

        let service = TemplateDownloadService::with_cache_dir(cache.path().to_path_buf());
        (cache, service)
    }

    /// A project scaffolded before `instance-track` existed is missing it entirely - `sync` must
    /// add it, leaving the already-present `idle-wander` directory alone (not reported as added).
    #[test]
    fn sync_framework_behaviors_adds_a_missing_bundled_behavior() {
        let version = "1.0.0";
        let (_cache, service) = stage_bundled_behaviors(
            version,
            &[
                ("idle-wander", r#"{"name": "idle-wander"}"#),
                ("instance-track", r#"{"name": "instance-track"}"#),
            ],
        );

        let project = tempdir().unwrap();
        std::fs::create_dir_all(project.path().join("configs/behaviors/@mecha10/idle-wander")).unwrap();
        std::fs::write(
            project
                .path()
                .join("configs/behaviors/@mecha10/idle-wander/config.json"),
            r#"{"name": "idle-wander"}"#,
        )
        .unwrap();

        let added = sync_framework_behaviors(&service, project.path(), version).unwrap();

        assert_eq!(added, vec!["instance-track".to_string()]);
        assert_eq!(
            std::fs::read_to_string(
                project
                    .path()
                    .join("configs/behaviors/@mecha10/instance-track/config.json")
            )
            .unwrap(),
            r#"{"name": "instance-track"}"#
        );
    }

    /// Companion to the above: a project that already has every bundled behavior on disk gets
    /// nothing added.
    #[test]
    fn sync_framework_behaviors_reports_nothing_to_do_when_already_up_to_date() {
        let version = "1.0.0";
        let (_cache, service) = stage_bundled_behaviors(version, &[("idle-wander", r#"{"name": "idle-wander"}"#)]);

        let project = tempdir().unwrap();
        std::fs::create_dir_all(project.path().join("configs/behaviors/@mecha10/idle-wander")).unwrap();
        std::fs::write(
            project
                .path()
                .join("configs/behaviors/@mecha10/idle-wander/config.json"),
            r#"{"name": "idle-wander"}"#,
        )
        .unwrap();

        let added = sync_framework_behaviors(&service, project.path(), version).unwrap();

        assert!(added.is_empty(), "expected nothing to sync, got {:?}", added);
    }

    /// An `@mecha10/<name>` directory already on disk must never be overwritten, even if its
    /// content has been customized and now differs from the bundled template - `sync` only ever
    /// adds behaviors that are entirely missing.
    #[test]
    fn sync_framework_behaviors_never_overwrites_an_existing_customized_behavior() {
        let version = "1.0.0";
        let (_cache, service) =
            stage_bundled_behaviors(version, &[("idle-wander", r#"{"name": "idle-wander-bundled"}"#)]);

        let project = tempdir().unwrap();
        std::fs::create_dir_all(project.path().join("configs/behaviors/@mecha10/idle-wander")).unwrap();
        std::fs::write(
            project
                .path()
                .join("configs/behaviors/@mecha10/idle-wander/config.json"),
            r#"{"name": "idle-wander-customized"}"#,
        )
        .unwrap();

        let added = sync_framework_behaviors(&service, project.path(), version).unwrap();

        assert!(added.is_empty());
        assert_eq!(
            std::fs::read_to_string(
                project
                    .path()
                    .join("configs/behaviors/@mecha10/idle-wander/config.json")
            )
            .unwrap(),
            r#"{"name": "idle-wander-customized"}"#,
            "an existing @mecha10/ behavior must never be overwritten by sync"
        );
    }

    /// Project-tier custom behaviors (no `@mecha10/` prefix) live in the same `configs/behaviors/`
    /// parent directory but must never be touched by sync - it only ever reads/writes under
    /// `configs/behaviors/@mecha10/`.
    #[test]
    fn sync_framework_behaviors_leaves_project_tier_custom_behaviors_untouched() {
        let version = "1.0.0";
        let (_cache, service) =
            stage_bundled_behaviors(version, &[("instance-track", r#"{"name": "instance-track"}"#)]);

        let project = tempdir().unwrap();
        std::fs::create_dir_all(project.path().join("configs/behaviors/my-custom-patrol")).unwrap();
        std::fs::write(
            project.path().join("configs/behaviors/my-custom-patrol/config.json"),
            r#"{"name": "my-custom-patrol"}"#,
        )
        .unwrap();

        let added = sync_framework_behaviors(&service, project.path(), version).unwrap();

        assert_eq!(added, vec!["instance-track".to_string()]);
        assert_eq!(
            std::fs::read_to_string(project.path().join("configs/behaviors/my-custom-patrol/config.json")).unwrap(),
            r#"{"name": "my-custom-patrol"}"#,
            "project-tier custom behaviors must be left untouched by sync"
        );
    }
}