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
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
//! Add command handler
//!
//! Handles adding components to a Mecha10 project.

use crate::commands::add::{AddBehaviorArgs, AddCommand, AddDriverArgs, AddDriverType, AddNodeArgs};
use crate::context::CliContext;
use crate::paths;
use crate::services::{BehaviorGeneratorService, DriverGeneratorService, DriverType, NodeGeneratorService};
use anyhow::{Context, Result};

/// Known framework nodes — must match entries in mecha10.json template and configs/nodes/
const FRAMEWORK_NODES: &[&str] = &[
    "behavior-executor",
    "camera",
    "image-classifier",
    "imu",
    "listener",
    "llm-command",
    "motor",
    "simulator",
    "object-detector",
    "speaker",
    "teleop",
    "video-streamer",
    "websocket-bridge",
];

/// Flags recognized within `AddCommand::Framework`'s raw external-subcommand args (clap can't
/// parse flags for an `external_subcommand`, so `handle_add` scans for them manually). Either
/// spelling opts out of the interactive lifecycle-mode/target menus below, falling back to pure
/// tag-based inference - the same convention `mecha10 init --non-interactive` already uses (see
/// `handlers/init.rs`), so scripted/CI callers of `mecha10 add <node>` keep working unchanged.
const NON_INTERACTIVE_FLAGS: &[&str] = &["--non-interactive", "--yes"];

/// Handle add command
pub async fn handle_add(ctx: &mut CliContext, command: &AddCommand) -> Result<()> {
    match command {
        AddCommand::Node(args) => handle_add_node(ctx, args).await,
        AddCommand::Driver(args) => handle_add_driver(ctx, args).await,
        AddCommand::Behavior(args) => handle_add_behavior(ctx, args).await,
        AddCommand::Framework(args) => {
            let non_interactive = args.iter().any(|a| NON_INTERACTIVE_FLAGS.contains(&a.as_str()));
            let name = args
                .iter()
                .find(|a| !NON_INTERACTIVE_FLAGS.contains(&a.as_str()))
                .map(|s| s.as_str())
                .unwrap_or("");
            handle_add_framework_node(ctx, name, non_interactive).await
        }
    }
}

/// All lifecycle modes a framework node can be registered under. Kept in one place so the
/// interactive multiselect (all current modes + "select all") and the non-interactive tag-based
/// fallback agree on the universe of choices - see
/// `mecha10_cli_core::component_catalog::Component::relevant_lifecycle_modes`, which currently
/// only ever infers a subset of this same list.
const ALL_LIFECYCLE_MODES: &[&str] = &["simulation", "hardware"];

/// All dispatch targets a framework node can be registered under (mirrors
/// `mecha10_cli_core::types::project::TargetsConfig`'s `robot`/`remote` fields).
const ALL_TARGETS: &[&str] = &["robot", "remote"];

/// Whether stdin and stdout are both attached to a real terminal - same check
/// `handlers::init::handle_init` uses to decide whether to launch its interactive wizard.
fn is_interactive_terminal() -> bool {
    atty::is(atty::Stream::Stdin) && atty::is(atty::Stream::Stdout)
}

/// Resolve which `lifecycle.modes` entries a newly-added framework node should be registered
/// under.
///
/// Interactively (a real terminal, and the caller didn't pass `--non-interactive`/`--yes`), this
/// prompts a multiselect over [`ALL_LIFECYCLE_MODES`], pre-checked with whatever
/// `relevant_lifecycle_modes()` already inferred from the component's tags, so accepting the
/// defaults reproduces today's behavior exactly. Non-interactively, tag-based inference alone
/// decides - unchanged from before this feature existed, which is what keeps scripted/CI callers
/// working.
fn select_lifecycle_modes(interactive: bool, inferred: &[&'static str]) -> Result<Vec<String>> {
    if !interactive {
        return Ok(inferred.iter().map(|s| s.to_string()).collect());
    }

    let checked: Vec<bool> = ALL_LIFECYCLE_MODES.iter().map(|m| inferred.contains(m)).collect();
    let selected = crate::ui::prompts::multiselect(
        "Add this node to which lifecycle mode(s)?",
        ALL_LIFECYCLE_MODES,
        &checked,
    )?;

    Ok(selected
        .into_iter()
        .map(|i| ALL_LIFECYCLE_MODES[i].to_string())
        .collect())
}

/// Resolve which `targets` entry (`robot`/`remote`) a newly-added framework node should be
/// registered under - same interactive-vs-tag-inferred split as [`select_lifecycle_modes`], using
/// `Component::relevant_target()` as the non-interactive fallback / interactive pre-check.
fn select_targets(interactive: bool, inferred: Option<&'static str>) -> Result<Vec<String>> {
    if !interactive {
        return Ok(inferred.into_iter().map(|s| s.to_string()).collect());
    }

    let checked: Vec<bool> = ALL_TARGETS.iter().map(|t| Some(*t) == inferred).collect();
    let selected = crate::ui::prompts::multiselect("Add this node to which target(s)?", ALL_TARGETS, &checked)?;

    Ok(selected.into_iter().map(|i| ALL_TARGETS[i].to_string()).collect())
}

/// Handle `mecha10 add <node-name>` — adds a framework node to mecha10.json
async fn handle_add_framework_node(ctx: &mut CliContext, name: &str, non_interactive: bool) -> Result<()> {
    // Strip @mecha10/ prefix if provided
    let name = name.trim_start_matches("@mecha10/");

    if name.is_empty() {
        anyhow::bail!(
            "Node name is required. Usage: mecha10 add <node-name>\n\nAvailable nodes: {}",
            FRAMEWORK_NODES.join(", ")
        );
    }

    if !FRAMEWORK_NODES.contains(&name) {
        anyhow::bail!(
            "Unknown framework node '{}'. Available nodes:\n  {}",
            name,
            FRAMEWORK_NODES.join("\n  ")
        );
    }

    println!();
    println!("Adding node: @mecha10/{}", name);
    println!();

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

    let config_path = ctx.working_dir.join(paths::PROJECT_CONFIG);
    let identifier = format!("@mecha10/{}", name);

    // Read mecha10.json as Value to preserve key order
    let content = tokio::fs::read_to_string(&config_path)
        .await
        .context("Failed to read mecha10.json")?;
    let mut config: serde_json::Value = serde_json::from_str(&content).context("Failed to parse mecha10.json")?;

    // Check if already present
    if config["nodes"].get(&identifier).is_some() {
        println!("  {} is already in mecha10.json", identifier);
        println!();
        return Ok(());
    }

    // Add to nodes map, pinned to the compiled CLI's own framework version — mirrors
    // `add_node_to_config` in mecha10-templates' init_service.rs. Writing the literal string
    // "latest" here is a bug: nothing downstream (resolve.rs, binary_manager.rs,
    // downloads/store.rs) treats an explicit `Some("latest")` as a sentinel to resolve against
    // latest.txt — it's used verbatim as a version string, which 404s and falls through to a
    // confusing `cargo install` failure.
    config["nodes"][&identifier] = serde_json::json!(env!("CARGO_PKG_VERSION"));

    // Keep `lifecycle.modes.*.nodes` (and `targets.*`) in sync with this newly added node —
    // mirrors `add_node_to_config` in mecha10-templates' init_service.rs. Those lists are seeded
    // once from the static `mecha10.json.template` and otherwise never grow, so without this the
    // node would be registered in `nodes` but never actually spawned by
    // `CliLifecycleManager::nodes_for_current_mode`, which only reads
    // `lifecycle.modes.<mode>.nodes`.
    //
    // Which mode(s)/target(s) to use is either picked interactively (LAB-2086) or, when running
    // non-interactively (no TTY, or an explicit `--non-interactive`/`--yes`), falls back to pure
    // tag-based inference exactly as before this feature existed.
    let component = crate::component_catalog::ComponentCatalog::new().get(name).cloned();
    let inferred_modes = component
        .as_ref()
        .map(|c| c.relevant_lifecycle_modes())
        .unwrap_or_default();
    let inferred_target = component.as_ref().and_then(|c| c.relevant_target());

    let interactive = !non_interactive && is_interactive_terminal();
    let modes = select_lifecycle_modes(interactive, &inferred_modes)?;
    let targets = select_targets(interactive, inferred_target)?;

    for mode in &modes {
        let mut mode_nodes = config["lifecycle"]["modes"][mode]["nodes"]
            .as_array()
            .cloned()
            .unwrap_or_default();
        if !mode_nodes.iter().any(|n| n == &identifier) {
            mode_nodes.push(serde_json::json!(identifier));
        }
        config["lifecycle"]["modes"][mode]["nodes"] = serde_json::json!(mode_nodes);
    }

    for target in &targets {
        let mut target_nodes = config["targets"][target].as_array().cloned().unwrap_or_default();
        if !target_nodes.iter().any(|n| n == &identifier) {
            target_nodes.push(serde_json::json!(identifier));
        }
        config["targets"][target] = serde_json::json!(target_nodes);
    }

    // Write back
    let updated = serde_json::to_string_pretty(&config)?;
    tokio::fs::write(&config_path, updated)
        .await
        .context("Failed to write mecha10.json")?;

    println!("  ✓ Added {} to mecha10.json", identifier);

    // Copy config templates for this node
    copy_node_configs(ctx, name).await?;

    println!();
    println!("Next steps:");
    println!(
        "  1. Edit configs/nodes/@mecha10/{}/config.json to configure the node",
        name
    );
    println!("  2. Run 'mecha10 dev' to start the node");
    println!();

    Ok(())
}

/// Copy config templates for a framework node to the project
async fn copy_node_configs(ctx: &mut CliContext, node_name: &str) -> Result<()> {
    let dest = ctx.working_dir.join(paths::config::framework_node_dir(node_name));

    if dest.exists() {
        println!("  ✓ Config already exists at configs/nodes/@mecha10/{}/", node_name);
        return Ok(());
    }

    // Try downloading from GitHub release templates first (or a locally
    // `--install`ed dev build, if one is present - see
    // `TemplateDownloadService::resolve_version`)
    let template_download = ctx.template_download();
    match template_download.resolve_version().await {
        Ok(version) => {
            if template_download.ensure_templates(&version).await.is_ok() {
                let template_rel = paths::config::framework_node_dir(node_name);
                template_download.copy_template_dir(&version, &template_rel, &dest)?;
                if dest.exists() {
                    println!("  ✓ Config written to configs/nodes/@mecha10/{}/", node_name);
                    return Ok(());
                }
            }
        }
        Err(_) => {
            tracing::debug!("Could not fetch template version, falling back to manual-create warning");
        }
    }

    // No config template could be downloaded — the previous fallback that copied from
    // packages/cli/templates/configs/nodes (embedded/monorepo templates) was removed
    // (LAB-2027): that tree was a stale, unmaintained duplicate of the real
    // packages/nodes/*/configs/ source of truth and could silently hand out outdated
    // config values. Ask the user to create the config manually instead.
    println!(
        "  ⚠  No config template found for {}. Create configs/nodes/@mecha10/{}/config.json manually.",
        node_name, node_name
    );

    Ok(())
}

/// Handle add node subcommand — scaffolds a custom Rust node
async fn handle_add_node(ctx: &mut CliContext, args: &AddNodeArgs) -> Result<()> {
    println!();
    println!("Creating node: {}", args.name);
    println!();

    let project_root = &ctx.working_dir;
    let generator = NodeGeneratorService::new();

    // Generate the node
    generator
        .generate_node(project_root, &args.name, args.description.as_deref())
        .await?;

    // Success message
    println!("Node created successfully!");
    println!();
    println!("  nodes/{}/", args.name);
    println!("  ├── Cargo.toml");
    println!("  └── src/");
    println!("      ├── lib.rs");
    println!("      ├── main.rs");
    println!("      └── config.rs");
    println!();
    println!("  configs/nodes/{}/", args.name);
    println!("  └── config.json");
    println!();
    println!("Node has been added to dev mode automatically.");
    println!();
    println!("Next steps:");
    println!("  1. Edit nodes/{}/src/lib.rs to implement your node logic", args.name);
    println!("  2. Update configs/nodes/{}/config.json with your settings", args.name);
    println!("  3. Run 'mecha10 dev' to test your node");
    println!();

    Ok(())
}

/// Convert the clap-facing `AddDriverType` to `mecha10_templates`' plain `DriverType`.
fn to_driver_type(arg_type: AddDriverType) -> DriverType {
    match arg_type {
        AddDriverType::Camera => DriverType::Camera,
        AddDriverType::Motor => DriverType::Motor,
        AddDriverType::Sensor => DriverType::Sensor,
        AddDriverType::Imu => DriverType::Imu,
    }
}

/// Handle add driver subcommand — scaffolds a custom Rust hardware driver crate
async fn handle_add_driver(ctx: &mut CliContext, args: &AddDriverArgs) -> Result<()> {
    let driver_type = to_driver_type(args.r#type);

    println!();
    println!("Creating {} driver: {}", driver_type.as_str(), args.name);
    println!();

    let project_root = &ctx.working_dir;
    let generator = DriverGeneratorService::new();

    generator.generate_driver(project_root, &args.name, driver_type).await?;

    println!("Driver created successfully!");
    println!();
    println!("  drivers/{}/", args.name);
    println!("  ├── Cargo.toml");
    println!("  └── src/");
    println!("      ├── lib.rs");
    println!("      └── main.rs");
    println!();
    println!("Next steps:");
    println!(
        "  1. Edit drivers/{}/src/lib.rs to talk to your actual hardware",
        args.name
    );
    println!(
        "  2. Depend on it from a node crate, or run it standalone with 'cargo run -p {}'",
        args.name
    );
    println!();

    Ok(())
}

/// Handle add behavior subcommand — scaffolds a custom project behavior tree
///
/// Unlike `mecha10 add node`/`mecha10 add driver`, a behavior is not a Rust crate — it's a
/// purely declarative `configs/behaviors/<name>/config.json` behavior-tree composition, loaded
/// at runtime by the `behavior-executor` node. See `BehaviorGeneratorService`'s module doc for
/// why.
async fn handle_add_behavior(ctx: &mut CliContext, args: &AddBehaviorArgs) -> Result<()> {
    println!();
    println!("Creating behavior: {}", args.name);
    println!();

    let project_root = &ctx.working_dir;
    let generator = BehaviorGeneratorService::new();

    generator
        .generate_behavior(project_root, &args.name, args.description.as_deref())
        .await?;

    println!("Behavior created successfully!");
    println!();
    println!("  configs/behaviors/{}/", args.name);
    println!("  └── config.json");
    println!();
    println!("Next steps:");
    println!(
        "  1. Edit configs/behaviors/{}/config.json to define your behavior tree",
        args.name
    );
    println!(
        "  2. Set \"behavior_name\": \"{}\" in a behavior-executor node's config.json to run it",
        args.name
    );
    println!("  3. Run 'mecha10 dev' to test your behavior");
    println!();

    Ok(())
}

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

    // `select_lifecycle_modes`/`select_targets` short-circuit to tag-based inference whenever
    // `interactive` is `false`, without ever touching `dialoguer::MultiSelect::interact()` (which
    // needs a real TTY and would otherwise make these untestable in CI). This is also exactly the
    // non-interactive fallback path `mecha10 add <node> --non-interactive`/`--yes` and a
    // non-TTY invocation take (LAB-2086's "Existing non-interactive/scripted invocation still
    // works" acceptance criterion).

    #[test]
    fn select_lifecycle_modes_non_interactive_uses_tag_inferred_modes_only() {
        let modes = select_lifecycle_modes(false, &["simulation", "hardware"]).unwrap();
        assert_eq!(modes, vec!["simulation".to_string(), "hardware".to_string()]);
    }

    #[test]
    fn select_lifecycle_modes_non_interactive_with_no_inference_selects_nothing() {
        let modes = select_lifecycle_modes(false, &[]).unwrap();
        assert!(modes.is_empty());
    }

    #[test]
    fn select_targets_non_interactive_uses_inferred_target_only() {
        let targets = select_targets(false, Some("robot")).unwrap();
        assert_eq!(targets, vec!["robot".to_string()]);
    }

    #[test]
    fn select_targets_non_interactive_with_no_inference_selects_nothing() {
        let targets = select_targets(false, None).unwrap();
        assert!(targets.is_empty());
    }

    #[tokio::test]
    async fn handle_add_framework_node_pins_actual_framework_version_not_latest() {
        // Regression test: mecha10.json used to end up with the literal string "latest" as the
        // pinned version for a node added post-init, which nothing downstream can resolve
        // (resolve.rs / binary_manager.rs / downloads/store.rs all treat "latest" as a literal,
        // unresolvable version string). It must instead match the compiled CLI's own framework
        // version, same as `add_node_to_config` in mecha10-templates' init_service.rs.
        let dir = tempdir().unwrap();
        let config_path = dir.path().join(paths::PROJECT_CONFIG);
        std::fs::write(
            &config_path,
            serde_json::json!({
                "name": "proj",
                "version": "0.1.0",
                "nodes": {},
            })
            .to_string(),
        )
        .unwrap();

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

        handle_add_framework_node(&mut ctx, "simulator", true).await.unwrap();

        let updated: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
        let pinned_version = updated["nodes"]["@mecha10/simulator"]
            .as_str()
            .expect("version should be a string");

        assert_ne!(pinned_version, "latest");
        assert_eq!(pinned_version, env!("CARGO_PKG_VERSION"));
    }

    #[tokio::test]
    async fn handle_add_framework_node_syncs_ai_perception_node_into_simulation_and_hardware_modes() {
        // Regression test: `mecha10 add image-classifier` used to only register the node in the
        // top-level `nodes` map, never in `lifecycle.modes.*.nodes`. Since
        // `CliLifecycleManager::nodes_for_current_mode` only reads the latter, the node was
        // registered but never actually spawned. `image-classifier` is tagged `ai`/`ml`/`vision`
        // in the component catalog (packages.rs), so `relevant_lifecycle_modes()` must route it
        // into both "simulation" and "hardware".
        let dir = tempdir().unwrap();
        let config_path = dir.path().join(paths::PROJECT_CONFIG);
        std::fs::write(
            &config_path,
            serde_json::json!({
                "name": "proj",
                "version": "0.1.0",
                "nodes": {},
                "lifecycle": {
                    "modes": {
                        "simulation": { "nodes": ["@mecha10/simulator"] },
                        "hardware": { "nodes": ["@mecha10/websocket-bridge"] }
                    }
                }
            })
            .to_string(),
        )
        .unwrap();

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

        handle_add_framework_node(&mut ctx, "image-classifier", true)
            .await
            .unwrap();

        let updated: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();

        for mode in ["simulation", "hardware"] {
            let mode_nodes = updated["lifecycle"]["modes"][mode]["nodes"]
                .as_array()
                .unwrap_or_else(|| panic!("expected '{mode}' nodes array"));
            let mode_nodes: Vec<&str> = mode_nodes.iter().map(|v| v.as_str().unwrap()).collect();
            assert!(
                mode_nodes.contains(&"@mecha10/image-classifier"),
                "expected @mecha10/image-classifier in lifecycle.modes.{mode}.nodes, got {mode_nodes:?}"
            );
        }
    }

    #[tokio::test]
    async fn handle_add_framework_node_does_not_duplicate_node_already_present_in_mode() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join(paths::PROJECT_CONFIG);
        std::fs::write(
            &config_path,
            serde_json::json!({
                "name": "proj",
                "version": "0.1.0",
                "nodes": {},
                "lifecycle": {
                    "modes": {
                        "simulation": { "nodes": ["@mecha10/simulator", "@mecha10/image-classifier"] },
                        "hardware": { "nodes": ["@mecha10/websocket-bridge"] }
                    }
                }
            })
            .to_string(),
        )
        .unwrap();

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

        handle_add_framework_node(&mut ctx, "image-classifier", true)
            .await
            .unwrap();

        let updated: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
        let simulation_nodes = updated["lifecycle"]["modes"]["simulation"]["nodes"].as_array().unwrap();
        let occurrences = simulation_nodes
            .iter()
            .filter(|n| n.as_str() == Some("@mecha10/image-classifier"))
            .count();
        assert_eq!(
            occurrences, 1,
            "expected exactly one @mecha10/image-classifier entry in simulation mode, got {simulation_nodes:?}"
        );
    }

    #[tokio::test]
    async fn handle_add_framework_node_does_not_add_hardware_only_driver_node_to_simulation() {
        // `motor` is a hardware-backed node (driver), not AI/perception, so
        // `relevant_lifecycle_modes()` should route it into "hardware" only.
        let dir = tempdir().unwrap();
        let config_path = dir.path().join(paths::PROJECT_CONFIG);
        std::fs::write(
            &config_path,
            serde_json::json!({
                "name": "proj",
                "version": "0.1.0",
                "nodes": {},
                "lifecycle": {
                    "modes": {
                        "simulation": { "nodes": ["@mecha10/simulator"] },
                        "hardware": { "nodes": ["@mecha10/websocket-bridge"] }
                    }
                }
            })
            .to_string(),
        )
        .unwrap();

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

        handle_add_framework_node(&mut ctx, "motor", true).await.unwrap();

        let updated: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();

        let hardware_nodes = updated["lifecycle"]["modes"]["hardware"]["nodes"].as_array().unwrap();
        let hardware_nodes: Vec<&str> = hardware_nodes.iter().map(|v| v.as_str().unwrap()).collect();
        assert!(
            hardware_nodes.contains(&"@mecha10/motor"),
            "expected @mecha10/motor in lifecycle.modes.hardware.nodes, got {hardware_nodes:?}"
        );

        let simulation_nodes = updated["lifecycle"]["modes"]["simulation"]["nodes"].as_array().unwrap();
        let simulation_nodes: Vec<&str> = simulation_nodes.iter().map(|v| v.as_str().unwrap()).collect();
        assert!(
            !simulation_nodes.contains(&"@mecha10/motor"),
            "motor is not AI/perception, must not be added to simulation mode, got {simulation_nodes:?}"
        );
    }

    #[tokio::test]
    async fn handle_add_framework_node_non_interactive_syncs_targets_from_run_target_inference() {
        // LAB-2086: `targets.*` (robot/remote) must stay in sync with the node's own
        // `run_target`, the same way `lifecycle.modes.*.nodes` already does - `motor` is a
        // `custom_node` with `run_target: "robot"` (see component_catalog/packages.rs).
        let dir = tempdir().unwrap();
        let config_path = dir.path().join(paths::PROJECT_CONFIG);
        std::fs::write(
            &config_path,
            serde_json::json!({
                "name": "proj",
                "version": "0.1.0",
                "nodes": {},
            })
            .to_string(),
        )
        .unwrap();

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

        handle_add_framework_node(&mut ctx, "motor", true).await.unwrap();

        let updated: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
        let robot_targets = updated["targets"]["robot"].as_array().unwrap();
        let robot_targets: Vec<&str> = robot_targets.iter().map(|v| v.as_str().unwrap()).collect();
        assert!(
            robot_targets.contains(&"@mecha10/motor"),
            "expected @mecha10/motor in targets.robot, got {robot_targets:?}"
        );
        assert!(
            updated["targets"].get("remote").is_none() || updated["targets"]["remote"].as_array().unwrap().is_empty(),
            "motor should not be added to targets.remote"
        );
    }

    #[test]
    fn framework_nodes_allowlist_includes_simulator() {
        // `mecha10 add simulator` must work for existing projects (LAB-1775) so they can
        // pick up the MuJoCo simulation node without re-scaffolding.
        assert!(
            FRAMEWORK_NODES.contains(&"simulator"),
            "FRAMEWORK_NODES must include simulator, got {FRAMEWORK_NODES:?}"
        );
    }

    #[test]
    fn framework_nodes_allowlist_excludes_deleted_simulation_bridge() {
        assert!(
            !FRAMEWORK_NODES.contains(&"simulation-bridge"),
            "FRAMEWORK_NODES must not reference the deleted simulation-bridge node"
        );
    }

    #[tokio::test]
    async fn handle_add_driver_creates_driver_crate() {
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join("Cargo.toml"), "[workspace]\nmembers = []\n").unwrap();

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

        let args = AddDriverArgs {
            name: "front-camera".to_string(),
            r#type: AddDriverType::Camera,
        };

        handle_add_driver(&mut ctx, &args).await.unwrap();

        let driver_dir = dir.path().join("drivers/front-camera");
        assert!(driver_dir.join("Cargo.toml").exists());
        assert!(driver_dir.join("src/lib.rs").exists());
        assert!(driver_dir.join("src/main.rs").exists());
    }

    #[tokio::test]
    async fn handle_add_behavior_creates_behavior_config() {
        let dir = tempdir().unwrap();

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

        let args = AddBehaviorArgs {
            name: "patrol-perimeter".to_string(),
            description: Some("Patrols the building perimeter".to_string()),
        };

        handle_add_behavior(&mut ctx, &args).await.unwrap();

        let behavior_dir = dir.path().join("configs/behaviors/patrol-perimeter");
        let config_path = behavior_dir.join("config.json");
        assert!(config_path.exists());
        // A behavior is declarative config, not a Rust crate — no src/ tree, no Cargo.toml.
        assert!(!behavior_dir.join("src").exists());
        assert!(!behavior_dir.join("Cargo.toml").exists());

        let content = std::fs::read_to_string(&config_path).unwrap();
        let config: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(config["name"], serde_json::json!("patrol-perimeter"));
        assert_eq!(
            config["description"],
            serde_json::json!("Patrols the building perimeter")
        );
    }

    #[tokio::test]
    async fn handle_add_behavior_fails_if_behavior_already_exists() {
        let dir = tempdir().unwrap();

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

        let args = AddBehaviorArgs {
            name: "patrol".to_string(),
            description: None,
        };

        handle_add_behavior(&mut ctx, &args).await.unwrap();
        let err = handle_add_behavior(&mut ctx, &args).await.unwrap_err();
        assert!(err.to_string().contains("already exists"));
    }

    #[tokio::test]
    #[serial_test::serial(mecha10_api_url_env_var)]
    async fn copy_node_configs_falls_back_to_manual_create_warning_without_copying_stale_configs() {
        // Regression test for LAB-2027: `copy_node_configs` used to fall back to copying from
        // packages/cli/templates/configs/nodes (a stale, unmaintained duplicate of the real
        // packages/nodes/*/configs/ source of truth) whenever the GitHub release-template
        // download failed. That embedded-template fallback has been removed entirely, so when
        // the download fails, `copy_node_configs` must fall straight through to the "create
        // manually" warning without ever creating the destination config directory.
        //
        // Point MECHA10_API_URL at a port nothing listens on so both `resolve_version` and
        // `ensure_templates` fail fast and deterministically, regardless of real network
        // access or a locally cached template version on the machine running the test.
        std::env::set_var("MECHA10_API_URL", "http://127.0.0.1:1/api");

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

        let result = copy_node_configs(&mut ctx, "teleop").await;

        std::env::remove_var("MECHA10_API_URL");

        result.unwrap();

        let dest = dir.path().join(paths::config::framework_node_dir("teleop"));
        assert!(
            !dest.exists(),
            "copy_node_configs must not create a config dir when no template source is available"
        );
    }

    #[test]
    fn to_driver_type_maps_every_clap_variant() {
        assert_eq!(to_driver_type(AddDriverType::Camera).as_str(), "camera");
        assert_eq!(to_driver_type(AddDriverType::Motor).as_str(), "motor");
        assert_eq!(to_driver_type(AddDriverType::Sensor).as_str(), "sensor");
        assert_eq!(to_driver_type(AddDriverType::Imu).as_str(), "imu");
    }
}