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
//! 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::{
    catalog_client, BehaviorGeneratorService, DriverGeneratorService, DriverType, NodeGeneratorService,
};
use crate::ui::prompts::is_interactive_terminal;
use anyhow::{Context, Result};

/// Fetch the live framework node catalog from `mecha10-api`'s `GET /api/nodes/catalog` (via
/// [`catalog_client::fetch_node_catalog`]) - the same catalog `mecha10 init`'s node-selection
/// wizard now reads, so this can never drift from the wizard's list the way a
/// hand-maintained/compiled-in local list could. Each entry's `targets` field is now the single
/// source of truth for which `mecha10.json` `targets.<key>.nodes` list(s) the node belongs in
/// (see [`catalog_client::NodeCatalogEntry`]) - there is no separate local inference anymore.
///
/// Previously fetched `GET /api/downloads/nodes` directly (a Postgres-backed table that every
/// node binary upload self-registers into); migrated to the shared `/api/nodes/catalog` catalog
/// client so `mecha10 add <node>` and `mecha10 init` validate/select against the exact same
/// source of truth.
///
/// No fallback to a local list and no silent retry: if `mecha10-api` is unreachable, this fails
/// hard with an explanatory error - same as `mecha10 init`'s template download already does when
/// it can't reach the network (see `handlers/init.rs`).
async fn fetch_framework_nodes() -> Result<Vec<catalog_client::NodeCatalogEntry>> {
    catalog_client::fetch_node_catalog()
        .await
        .context("Failed to fetch known node list")
}

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 names: Vec<String> = args
                .iter()
                .filter(|a| !NON_INTERACTIVE_FLAGS.contains(&a.as_str()))
                .cloned()
                .collect();
            handle_add_framework_node(ctx, &names, non_interactive).await
        }
    }
}

/// Resolve which framework node(s) `mecha10 add` should add, given the raw node-name arguments
/// the user passed on the command line.
///
/// If one or more names were passed, they're used as-is (this is what makes `mecha10 add camera
/// motor` add both in one invocation). If none were passed and a real terminal is available,
/// prompts a multiselect over `available` (the live list fetched from `mecha10-api`, see
/// [`fetch_framework_nodes`]) instead of erroring outright - the interactive counterpart to the
/// non-interactive/scripted usage error below. Non-interactively with no names, the caller must
/// still pass a name explicitly, exactly as before this feature existed.
fn select_framework_node_names(names: &[String], interactive: bool, available: &[String]) -> Result<Vec<String>> {
    if !names.is_empty() {
        return Ok(names.to_vec());
    }

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

    let options: Vec<&str> = available.iter().map(String::as_str).collect();
    let selected = crate::ui::prompts::multiselect(
        "Which framework node(s) would you like to add?",
        &options,
        &vec![false; options.len()],
    )?;

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

/// Write a single framework node into an in-memory `mecha10.json` `Value` - the `nodes`/
/// `targets` completeness logic shared across every node added via this invocation of `mecha10
/// add`. Returns `false` (no-op) if `name` is already present in `nodes`, `true` if it was newly
/// added.
///
/// `targets` is exactly the live-catalog entry's own `targets` field
/// ([`catalog_client::NodeCatalogEntry::targets`]) - no more separate lifecycle-mode/`run_target`
/// inference (nor an interactive override prompt for it) since that was only ever an artifact of
/// approximating this same placement locally from two different heuristics
/// (`Component::relevant_lifecycle_modes`/`relevant_target`, both retired by this migration). A
/// node fetched from the live catalog is placed into exactly what the catalog says, full stop.
fn add_node_to_json_config(config: &mut serde_json::Value, name: &str, targets: &[String]) -> Result<bool> {
    let identifier = format!("@mecha10/{}", name);

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

    config["nodes"][&identifier] = serde_json::json!(env!("CARGO_PKG_VERSION"));

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

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

/// Handle `mecha10 add <node-name> [<node-name>...]` — adds one or more framework nodes to
/// mecha10.json. With no node name(s) on the command line and a real terminal available, prompts
/// a multiselect (LAB-2155) instead of requiring the name up front.
async fn handle_add_framework_node(ctx: &mut CliContext, names: &[String], non_interactive: bool) -> Result<()> {
    if !ctx.is_project_initialized() {
        anyhow::bail!("Not in a Mecha10 project directory");
    }

    let interactive = !non_interactive && is_interactive_terminal();
    let catalog_entries = fetch_framework_nodes().await?;
    let available_nodes: Vec<String> = catalog_entries.iter().map(|e| e.name.clone()).collect();
    let names = select_framework_node_names(names, interactive, &available_nodes)?;

    let names: Vec<&str> = names.iter().map(|n| n.trim_start_matches("@mecha10/")).collect();

    if names.is_empty() {
        println!();
        println!("No nodes selected.");
        println!();
        return Ok(());
    }

    for name in &names {
        if !available_nodes.iter().any(|n| n == name) {
            anyhow::bail!(
                "Unknown framework node '{}'. Available nodes:\n  {}",
                name,
                available_nodes.join("\n  ")
            );
        }
    }

    let config_path = ctx.working_dir.join(paths::PROJECT_CONFIG);

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

    let mut added = Vec::new();
    for name in &names {
        println!();
        println!("Adding node: @mecha10/{}", name);
        println!();

        let targets: &[String] = catalog_entries
            .iter()
            .find(|e| e.name == *name)
            .map(|e| e.targets.as_slice())
            .unwrap_or_default();

        if add_node_to_json_config(&mut config, name, targets)? {
            added.push(*name);
        }
    }

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

    if !added.is_empty() {
        // The release templates archive no longer bundles any built-in node's config/schema at
        // all - that content moved out to mecha-industries/mecha10-nodes (see
        // scripts/release/build/package-templates.sh's "KNOWN GAP" note). `mecha10 init` hits
        // the same wall and falls back to the same source, so this is the only thing that
        // actually works here: fetch straight from mecha10-api's live node catalog. Never
        // overwrites a file that already exists, and never fails `mecha10 add`.
        let added_names: Vec<String> = added.iter().map(|n| n.to_string()).collect();
        mecha10_robot_config::pull_node_catalog_configs(&ctx.working_dir, &added_names, None).await;

        for name in &added {
            let config_path = ctx
                .working_dir
                .join(paths::config::framework_node_dir(name))
                .join("config.json");
            if config_path.exists() {
                println!("  ✓ Config written to configs/nodes/@mecha10/{}/", name);
            } else {
                println!(
                    "  âš   No config found for {}. Create configs/nodes/@mecha10/{}/config.json manually.",
                    name, name
                );
            }
        }

        println!();
        println!("Next steps:");
        for name in &added {
            println!(
                "  - Edit configs/nodes/@mecha10/{}/config.json to configure the node",
                name
            );
        }
        println!("  - Run 'mecha10 dev' to start the node(s)");
        println!();
    }

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

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

    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 std::io::{Read, Write};
    use std::net::TcpListener;
    use tempfile::tempdir;

    /// Spins up a minimal local HTTP server (same raw-`TcpListener` approach
    /// `mecha10_node_resolver`'s tests use for its own fake download server - no `wiremock`/
    /// `mockito` dependency anywhere in this workspace) that answers every request with `nodes`
    /// encoded as a `/api/nodes/catalog`-shaped JSON array (`[{"name": ..., "recommended": true,
    /// "targets": [...]}, ...]`), for driving [`fetch_framework_nodes`] (now backed by
    /// [`crate::services::catalog_client::fetch_node_catalog`]) against a controlled response
    /// instead of the real `mecha10-api`. Each `nodes` entry is a `(name, targets)` pair so
    /// callers can drive the live-catalog-sourced placement logic in [`add_node_to_json_config`]
    /// directly, rather than through a separate local inference table.
    fn spawn_fake_node_list_server(nodes: &[(&str, &[&str])]) -> std::net::SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let entries: Vec<serde_json::Value> = nodes
            .iter()
            .map(|(name, targets)| serde_json::json!({"name": name, "recommended": true, "targets": targets}))
            .collect();
        let body = serde_json::to_string(&entries).unwrap();

        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let mut stream = match stream {
                    Ok(s) => s,
                    Err(_) => continue,
                };
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf);
                let header = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                );
                let _ = stream.write_all(header.as_bytes());
                let _ = stream.write_all(body.as_bytes());
                let _ = stream.flush();
            }
        });

        addr
    }

    /// Points `MECHA10_API_URL` at a freshly spawned [`spawn_fake_node_list_server`] for the
    /// lifetime of the returned guard, so `fetch_framework_nodes()` resolves against `nodes`
    /// instead of the real `mecha10-api`. Removes the env var on drop (including on panic/
    /// `.unwrap()` failure, unlike a plain set-then-remove) so a failing test can't leak the
    /// override into whichever test runs next - tests touching this env var must still be
    /// `#[serial_test::serial(mecha10_api_url_env_var)]` since it's process-global.
    struct FakeNodeListServer;

    impl Drop for FakeNodeListServer {
        fn drop(&mut self) {
            std::env::remove_var("MECHA10_API_URL");
        }
    }

    fn start_fake_node_list_server(nodes: &[(&str, &[&str])]) -> FakeNodeListServer {
        let addr = spawn_fake_node_list_server(nodes);
        std::env::set_var("MECHA10_API_URL", format!("http://{}/api", addr));
        FakeNodeListServer
    }

    /// The fixed `(name, targets)` catalog shared by most tests below - mirrors what
    /// `mecha10-api`'s live `/nodes/catalog` would now report for these nodes, sourced from each
    /// node crate's own `Cargo.toml` `[package.metadata.mecha10] targets = [...]` in
    /// `mecha10-nodes` (`image-classifier` lands in both `simulation` and `remote`, combining
    /// what used to be two separate local inference paths - AI/perception tag, and
    /// `run_target: "remote"` - into a single live list).
    const DEFAULT_CATALOG: &[(&str, &[&str])] = &[
        ("simulator", &["simulation"]),
        ("camera", &["robot"]),
        ("motor", &["robot"]),
        ("image-classifier", &["simulation", "remote"]),
    ];

    /// Direct, network-free coverage of [`add_node_to_json_config`] - the placement logic
    /// itself, rather than the `handle_add_framework_node` integration tests below that exercise
    /// it through a fake `mecha10-api` server. Asserts a node is placed into every `targets`
    /// entry its own `targets` list names, and nowhere else.
    #[test]
    fn add_node_to_json_config_places_node_into_exactly_its_given_targets() {
        let mut config = serde_json::json!({ "nodes": {} });

        let added = add_node_to_json_config(
            &mut config,
            "image-classifier",
            &["simulation".to_string(), "remote".to_string()],
        )
        .unwrap();

        assert!(added);
        assert!(config["nodes"].get("@mecha10/image-classifier").is_some());
        assert_eq!(
            config["targets"]["simulation"]["nodes"],
            serde_json::json!(["@mecha10/image-classifier"])
        );
        assert_eq!(
            config["targets"]["remote"]["nodes"],
            serde_json::json!(["@mecha10/image-classifier"])
        );
        assert!(
            config["targets"].get("robot").is_none(),
            "image-classifier's targets list doesn't name \"robot\", so no targets.robot entry should be created"
        );
    }

    #[test]
    fn add_node_to_json_config_is_a_no_op_for_a_node_already_present() {
        let mut config = serde_json::json!({ "nodes": { "@mecha10/motor": "0.1.0" } });

        let added = add_node_to_json_config(&mut config, "motor", &["robot".to_string()]).unwrap();

        assert!(!added);
        assert!(
            config["targets"].get("robot").is_none(),
            "an already-present node must be a pure no-op, not retroactively placed into targets"
        );
    }

    #[test]
    fn add_node_to_json_config_does_not_duplicate_an_existing_target_entry() {
        let mut config = serde_json::json!({
            "nodes": {},
            "targets": { "robot": { "nodes": ["@mecha10/camera"] } }
        });

        add_node_to_json_config(&mut config, "motor", &["robot".to_string()]).unwrap();

        assert_eq!(
            config["targets"]["robot"]["nodes"],
            serde_json::json!(["@mecha10/camera", "@mecha10/motor"])
        );
    }

    #[tokio::test]
    #[serial_test::serial(mecha10_api_url_env_var)]
    async fn handle_add_framework_node_pins_actual_framework_version_not_latest() {
        let _server = start_fake_node_list_server(DEFAULT_CATALOG);
        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".to_string()], 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]
    #[serial_test::serial(mecha10_api_url_env_var)]
    async fn handle_add_framework_node_places_node_into_every_target_its_live_catalog_entry_names() {
        let _server = start_fake_node_list_server(DEFAULT_CATALOG);
        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": {},
                "targets": {
                    "simulation": { "nodes": ["@mecha10/simulator"] }
                }
            })
            .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".to_string()], true)
            .await
            .unwrap();

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

        let mode_nodes = updated["targets"]["simulation"]["nodes"]
            .as_array()
            .expect("expected 'simulation' 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 targets.simulation.nodes, got {mode_nodes:?}"
        );
    }

    #[tokio::test]
    #[serial_test::serial(mecha10_api_url_env_var)]
    async fn handle_add_framework_node_does_not_duplicate_node_already_present_in_mode() {
        const CATALOG: &[(&str, &[&str])] = &[
            ("simulator", &["simulation"]),
            ("camera", &["robot"]),
            ("motor", &["robot"]),
            ("image-classifier", &["simulation", "remote"]),
            ("websocket-bridge", &["dev", "simulation", "robot", "remote"]),
        ];
        let _server = start_fake_node_list_server(CATALOG);
        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": {},
                "targets": {
                    "simulation": { "nodes": ["@mecha10/simulator", "@mecha10/image-classifier"] },
                    "robot": { "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".to_string()], 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["targets"]["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]
    #[serial_test::serial(mecha10_api_url_env_var)]
    async fn handle_add_framework_node_does_not_add_a_node_to_a_target_its_catalog_entry_does_not_name() {
        let _server = start_fake_node_list_server(DEFAULT_CATALOG);
        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": {},
                "targets": {
                    "simulation": { "nodes": ["@mecha10/simulator"] }
                }
            })
            .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".to_string()], 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["targets"]["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's catalog entry only names \"robot\", must not be added to simulation, got {simulation_nodes:?}"
        );
    }

    #[tokio::test]
    #[serial_test::serial(mecha10_api_url_env_var)]
    async fn handle_add_framework_node_places_node_into_its_live_catalog_robot_target() {
        let _server = start_fake_node_list_server(DEFAULT_CATALOG);
        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".to_string()], 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"]["nodes"].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.nodes, got {robot_targets:?}"
        );
        assert!(
            updated["targets"].get("remote").is_none()
                || updated["targets"]["remote"]["nodes"].as_array().unwrap().is_empty(),
            "motor should not be added to targets.remote"
        );
    }

    #[test]
    fn select_framework_node_names_non_interactive_with_no_names_errors() {
        let available = vec!["camera".to_string(), "motor".to_string()];
        let err = select_framework_node_names(&[], false, &available).unwrap_err();
        assert!(err.to_string().contains("Node name is required"), "got: {}", err);
    }

    #[test]
    fn select_framework_node_names_passes_through_given_names_unchanged() {
        let names = select_framework_node_names(&["camera".to_string(), "motor".to_string()], false, &[]).unwrap();
        assert_eq!(names, vec!["camera".to_string(), "motor".to_string()]);
    }

    #[tokio::test]
    #[serial_test::serial(mecha10_api_url_env_var)]
    async fn handle_add_framework_node_multiple_names_writes_all_three_sections_for_each() {
        let _server = start_fake_node_list_server(DEFAULT_CATALOG);
        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, &["image-classifier".to_string(), "motor".to_string()], true)
            .await
            .unwrap();

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

        assert!(updated["nodes"].get("@mecha10/image-classifier").is_some());
        assert!(updated["nodes"].get("@mecha10/motor").is_some());

        let simulation_nodes = updated["targets"]["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/image-classifier"),
            "expected @mecha10/image-classifier in targets.simulation.nodes, got {simulation_nodes:?}"
        );

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

    #[tokio::test]
    #[serial_test::serial(mecha10_api_url_env_var)]
    async fn handle_add_framework_node_multiple_names_rejects_whole_batch_on_unknown_node() {
        let _server = start_fake_node_list_server(DEFAULT_CATALOG);
        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();

        let err = handle_add_framework_node(&mut ctx, &["camera".to_string(), "not-a-real-node".to_string()], true)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("Unknown framework node"));

        let updated: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
        assert!(
            updated["nodes"].get("@mecha10/camera").is_none(),
            "no node should be written when the batch contains an unknown node"
        );
    }

    #[tokio::test]
    #[serial_test::serial(mecha10_api_url_env_var)]
    async fn fetch_framework_nodes_returns_the_live_list_from_mecha10_api() {
        let _server = start_fake_node_list_server(DEFAULT_CATALOG);

        let entries = fetch_framework_nodes().await.unwrap();
        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();

        assert!(
            names.contains(&"simulator"),
            "expected fetched node list to include simulator, got {names:?}"
        );
        assert!(
            !names.contains(&"simulation-bridge"),
            "fetched node list must not reference the deleted simulation-bridge node, got {names:?}"
        );

        let simulator_entry = entries.iter().find(|e| e.name == "simulator").unwrap();
        assert_eq!(
            simulator_entry.targets,
            vec!["simulation".to_string()],
            "expected simulator's live catalog entry to carry its targets field through"
        );
    }

    #[tokio::test]
    #[serial_test::serial(mecha10_api_url_env_var)]
    async fn fetch_framework_nodes_fails_hard_when_mecha10_api_is_unreachable() {
        std::env::set_var("MECHA10_API_URL", "http://127.0.0.1:1/api");

        let result = fetch_framework_nodes().await;

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

        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Failed to fetch known node list"),
            "got: {}",
            err
        );
    }

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

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