mecha10-cli 0.1.47

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
//! Init service for project initialization
//!
//! Handles business logic for creating new Mecha10 projects including:
//! - Directory structure creation
//! - Component addition
//! - Framework path detection

use crate::paths;
use anyhow::Result;
use std::path::Path;

// Embedded node configs for standalone mode (V2 structure: dev/production)
mod embedded_configs {
    // Motor node (V2 structure)
    pub const MOTOR_DEV: &str = include_str!("../../templates/configs/nodes/motor/dev/config.json");
    pub const MOTOR_PRODUCTION: &str = include_str!("../../templates/configs/nodes/motor/production/config.json");
}

/// Service for initializing new Mecha10 projects
///
/// # Examples
///
/// ```rust,ignore
/// use mecha10_cli::services::InitService;
///
/// let service = InitService::new();
///
/// // Create project structure
/// service.create_project_directories(&project_path).await?;
///
/// // Add example nodes
/// service.add_example_node(&project_path, "speaker").await?;
/// ```
pub struct InitService;

impl InitService {
    /// Create a new InitService
    pub fn new() -> Self {
        Self
    }

    /// Create project directory structure
    ///
    /// Creates all the necessary directories for a new Mecha10 project:
    /// - nodes/ - Custom node implementations
    /// - drivers/ - Hardware driver implementations
    /// - types/ - Shared type definitions
    /// - behaviors/ - Behavior tree definitions
    /// - config/ - Configuration files
    /// - logs/ - Runtime logs
    /// - models/ - ML/AI models (ONNX, etc.) for remote nodes
    /// - simulation/ - Simulation environments
    /// - simulation/models/ - Robot physical models (for Godot)
    /// - assets/ - Static assets for simulation and visualization
    /// - assets/images/ - Image assets for simulation textures, UI, etc.
    pub async fn create_project_directories(&self, path: &Path) -> Result<()> {
        let dirs = vec![
            paths::project::NODES_DIR,
            paths::project::DRIVERS_DIR,
            paths::project::TYPES_DIR,
            paths::project::BEHAVIORS_DIR,
            paths::project::LOGS_DIR,
            paths::project::MODELS_DIR,
            paths::project::SIMULATION_DIR,
            paths::project::SIMULATION_MODELS_DIR,
            paths::project::ASSETS_DIR,
            paths::project::ASSETS_IMAGES_DIR,
            // Config directories (nodes grouped by scope: @mecha10/, @local/)
            paths::config::NODES_DIR,
            paths::config::SIMULATION_DIR,
        ];

        for dir in dirs {
            let dir_path = path.join(dir);
            tokio::fs::create_dir_all(&dir_path).await?;

            // Create .gitkeep to ensure empty directories are tracked
            tokio::fs::write(dir_path.join(".gitkeep"), "").await?;
        }

        Ok(())
    }

    /// Add an example node from the catalog to the project
    ///
    /// This method:
    /// 1. Searches the component catalog for the component
    /// 2. Generates component files from templates (if any)
    /// 3. Updates Cargo.toml (workspace members or dependencies)
    /// 4. Updates mecha10.json configuration
    ///
    /// # Arguments
    ///
    /// * `project_root` - Root path of the project
    /// * `component_name` - Name of the component to add (e.g., "speaker", "listener")
    pub async fn add_example_node(&self, project_root: &Path, component_name: &str) -> Result<()> {
        use crate::component_catalog::ComponentCatalog;

        // Load catalog and find component
        let catalog = ComponentCatalog::new();
        let components = catalog.search(component_name);

        if components.is_empty() {
            return Err(anyhow::anyhow!("Component '{}' not found in catalog", component_name));
        }

        let component = &components[0];

        // Generate component files from catalog templates (if any)
        // For monorepo nodes like speaker/listener, files vec is empty
        for file_template in &component.files {
            let file_path = project_root.join(&file_template.path);

            // Create parent directories
            if let Some(parent) = file_path.parent() {
                tokio::fs::create_dir_all(parent).await?;
            }

            // Write file content
            tokio::fs::write(&file_path, &file_template.content).await?;
        }

        // Only update workspace Cargo.toml if files were generated
        // For monorepo nodes, skip workspace member updates since there's no wrapper directory
        if !component.files.is_empty() {
            self.add_workspace_member(project_root, component_name).await?;
        }

        // For monorepo nodes, add as dependency to Cargo.toml
        let is_monorepo_node = component.files.is_empty();
        if is_monorepo_node {
            self.add_dependency(project_root, component).await?;
        }

        // Update mecha10.json configuration
        self.add_node_to_config(project_root, component_name, component, is_monorepo_node)
            .await?;

        // Copy node configs from framework package to project
        self.copy_node_configs(project_root, component_name).await?;

        Ok(())
    }

    /// Add a workspace member to Cargo.toml
    async fn add_workspace_member(&self, project_root: &Path, component_name: &str) -> Result<()> {
        let cargo_toml_path = project_root.join(paths::rust::CARGO_TOML);
        let content = tokio::fs::read_to_string(&cargo_toml_path).await?;

        let new_member = format!("nodes/{}", component_name);
        let updated_content = if content.contains("members = []") {
            // Replace empty array
            content.replace("members = []", &format!("members = [\n    \"{}\",\n]", new_member))
        } else if let Some(start) = content.find("members = [") {
            // Find the closing bracket
            if let Some(end) = content[start..].find(']') {
                let insert_pos = start + end;
                // Check if there are existing members
                let members_section = &content[start..insert_pos];
                if members_section.contains('\"') {
                    // Has existing members, add comma and new member
                    format!(
                        "{}\n    \"{}\",{}",
                        &content[..insert_pos],
                        new_member,
                        &content[insert_pos..]
                    )
                } else {
                    // Empty but not [], add member
                    format!(
                        "{}\n    \"{}\",\n{}",
                        &content[..insert_pos],
                        new_member,
                        &content[insert_pos..]
                    )
                }
            } else {
                content
            }
        } else {
            content
        };

        tokio::fs::write(&cargo_toml_path, updated_content).await?;
        Ok(())
    }

    /// Add a dependency to Cargo.toml
    async fn add_dependency(&self, project_root: &Path, component: &crate::component_catalog::Component) -> Result<()> {
        let cargo_toml_path = project_root.join(paths::rust::CARGO_TOML);
        let content = tokio::fs::read_to_string(&cargo_toml_path).await?;

        // Get the actual package name from the component's cargo dependencies
        let package_name = if let Some(dep) = component.cargo_dependencies.first() {
            dep.name.clone()
        } else {
            // Fallback to old behavior if no cargo dependencies specified
            format!("mecha10-nodes-{}", component.id)
        };

        // Add dependency after mecha10-core if not already present
        if !content.contains(&package_name) {
            let updated_content = if let Some(pos) = content.find("mecha10-core = \"0.1\"") {
                // Find end of line
                if let Some(newline_pos) = content[pos..].find('\n') {
                    let insert_pos = pos + newline_pos + 1;
                    format!(
                        "{}{} = \"0.1\"\n{}",
                        &content[..insert_pos],
                        package_name,
                        &content[insert_pos..]
                    )
                } else {
                    content
                }
            } else {
                content
            };

            tokio::fs::write(&cargo_toml_path, updated_content).await?;
        }

        Ok(())
    }

    /// Add node entry to mecha10.json
    async fn add_node_to_config(
        &self,
        project_root: &Path,
        component_name: &str,
        _component: &crate::component_catalog::Component,
        is_monorepo_node: bool,
    ) -> Result<()> {
        use crate::services::ConfigService;

        let config_path = project_root.join(paths::PROJECT_CONFIG);
        let mut config = ConfigService::load_from(&config_path).await?;

        // Create node identifier based on source
        let node_identifier = if is_monorepo_node {
            // Framework node: @mecha10/node-name
            format!("@mecha10/{}", component_name)
        } else {
            // Project node: @local/node-name
            format!("@local/{}", component_name)
        };

        // Add node using the new format
        config.nodes.add_node(&node_identifier);

        // Save updated config
        let config_json = serde_json::to_string_pretty(&config)?;
        tokio::fs::write(&config_path, config_json).await?;

        Ok(())
    }

    /// Copy behavior tree templates from framework to project
    ///
    /// Copies seed templates from `packages/behavior-runtime/seeds/` to
    /// `{project}/behaviors/` for use with the behavior tree system.
    ///
    /// # Arguments
    ///
    /// * `project_root` - Root path of the project
    pub async fn copy_behavior_templates(&self, project_root: &Path) -> Result<()> {
        // Detect framework path to find source templates
        // Skip silently if framework path not available (standalone CLI mode)
        let framework_path = match self.detect_framework_path() {
            Ok(path) => path,
            Err(_) => return Ok(()), // Not in dev mode, skip copying
        };
        let source_templates_path = std::path::PathBuf::from(&framework_path)
            .join("packages")
            .join("behavior-runtime")
            .join("seeds");

        // Check if source templates directory exists
        if !source_templates_path.exists() {
            // No templates to copy - this is okay
            return Ok(());
        }

        // Create destination directory
        let dest_templates_path = project_root.join("behaviors");
        tokio::fs::create_dir_all(&dest_templates_path).await?;

        // Copy all .json templates
        let mut entries = tokio::fs::read_dir(&source_templates_path).await?;
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) == Some("json") {
                if let Some(filename) = path.file_name() {
                    let dest_file = dest_templates_path.join(filename);
                    tokio::fs::copy(&path, &dest_file).await?;
                }
            }
        }

        Ok(())
    }

    /// Copy simulation configuration file from framework to project
    ///
    /// Copies `packages/simulation/configs/config.json` to
    /// `{project}/configs/simulation/config.json`
    ///
    /// The config file contains both dev and production sections:
    /// ```json
    /// {
    ///   "dev": { ... },
    ///   "production": { ... }
    /// }
    /// ```
    ///
    /// # Arguments
    ///
    /// * `project_root` - Root path of the project
    pub async fn copy_simulation_configs(&self, project_root: &Path) -> Result<()> {
        // Detect framework path to find source config
        // Skip silently if framework path not available (standalone CLI mode)
        let framework_path = match self.detect_framework_path() {
            Ok(path) => path,
            Err(_) => return Ok(()), // Not in dev mode, skip copying
        };
        let source_config = std::path::PathBuf::from(&framework_path)
            .join("packages")
            .join("simulation")
            .join("configs")
            .join("config.json");

        // Check if source config exists
        if !source_config.exists() {
            return Ok(());
        }

        // Create destination directory and copy file
        let dest_dir = project_root.join("configs").join("simulation");
        tokio::fs::create_dir_all(&dest_dir).await?;

        let dest_file = dest_dir.join("config.json");
        tokio::fs::copy(&source_config, &dest_file).await?;

        Ok(())
    }

    /// Copy simulation asset files from framework to project
    ///
    /// Copies image assets from `packages/simulation/environments/basic_arena/assets/images/`
    /// to `{project}/assets/images/`
    ///
    /// This includes cat images (aiko.jpg, phoebe.jpg) used in the basic arena environment
    ///
    /// # Arguments
    ///
    /// * `project_root` - Root path of the project
    pub async fn copy_simulation_assets(&self, project_root: &Path) -> Result<()> {
        // Detect framework path to find source assets
        // Skip silently if framework path not available (standalone CLI mode)
        let framework_path = match self.detect_framework_path() {
            Ok(path) => path,
            Err(_) => return Ok(()), // Not in dev mode, skip copying
        };
        let source_assets_path = std::path::PathBuf::from(&framework_path)
            .join("packages")
            .join("simulation")
            .join("environments")
            .join("basic_arena")
            .join("assets")
            .join("images");

        // Check if source assets directory exists
        if !source_assets_path.exists() {
            // No assets to copy - this is okay
            return Ok(());
        }

        // Create destination directory
        let dest_assets_path = project_root.join("assets").join("images");
        tokio::fs::create_dir_all(&dest_assets_path).await?;

        // Copy image files
        let images = vec!["aiko.jpg", "phoebe.jpg"];
        for image in images {
            let source_file = source_assets_path.join(image);
            if source_file.exists() {
                let dest_file = dest_assets_path.join(image);
                tokio::fs::copy(&source_file, &dest_file).await?;
            }
        }

        Ok(())
    }

    /// Copy node configuration file from framework package to project
    ///
    /// Supports two config formats:
    /// - V2 (preferred): `packages/nodes/{node}/configs/dev/config.json` and `production/config.json`
    ///   → `{project}/configs/dev/nodes/{node}/config.json` and `production/nodes/{node}/config.json`
    /// - Legacy: `packages/nodes/{node}/configs/config.json`
    ///   → `{project}/configs/nodes/@mecha10/{node}/config.json`
    ///
    /// Falls back to embedded configs for standalone CLI mode when framework path unavailable.
    ///
    /// # Arguments
    ///
    /// * `project_root` - Root path of the project
    /// * `component_name` - Name of the node (e.g., "speaker", "motor")
    async fn copy_node_configs(&self, project_root: &Path, component_name: &str) -> Result<()> {
        // Try framework path first, fall back to embedded configs
        match self.detect_framework_path() {
            Ok(framework_path) => {
                self.copy_node_configs_from_framework(project_root, component_name, &framework_path)
                    .await
            }
            Err(_) => {
                // Standalone mode: use embedded configs
                self.write_embedded_node_configs(project_root, component_name).await
            }
        }
    }

    /// Copy node configs from framework path
    ///
    /// Creates environment-aware config: configs/nodes/@mecha10/{node}/config.json
    /// with `dev` and `production` keys at the top level.
    ///
    /// Source can be either:
    /// - V2 structure: `packages/nodes/{node}/configs/dev/config.json` and `production/config.json`
    /// - Legacy: `packages/nodes/{node}/configs/config.json` (used for both environments)
    async fn copy_node_configs_from_framework(
        &self,
        project_root: &Path,
        component_name: &str,
        framework_path: &str,
    ) -> Result<()> {
        let source_base = std::path::PathBuf::from(framework_path)
            .join("packages")
            .join("nodes")
            .join(component_name)
            .join("configs");

        // Destination path for framework nodes
        let dest_dir = project_root
            .join("configs")
            .join("nodes")
            .join("@mecha10")
            .join(component_name);

        // Check for V2 config structure (dev/ and production/ directories)
        let v2_dev_config = source_base.join("dev").join("config.json");
        let v2_prod_config = source_base.join("production").join("config.json");

        if v2_dev_config.exists() {
            // Read dev config
            let dev_content = tokio::fs::read_to_string(&v2_dev_config).await?;
            let dev_json: serde_json::Value = serde_json::from_str(&dev_content)?;

            // Read production config (fall back to dev if not present)
            let prod_json: serde_json::Value = if v2_prod_config.exists() {
                let prod_content = tokio::fs::read_to_string(&v2_prod_config).await?;
                serde_json::from_str(&prod_content)?
            } else {
                dev_json.clone()
            };

            // Create merged config with dev/production keys
            let merged = serde_json::json!({
                "dev": dev_json,
                "production": prod_json
            });

            tokio::fs::create_dir_all(&dest_dir).await?;
            let dest_file = dest_dir.join("config.json");
            let merged_content = serde_json::to_string_pretty(&merged)?;
            tokio::fs::write(&dest_file, merged_content).await?;
            return Ok(());
        }

        // Legacy single config.json format
        let legacy_config = source_base.join("config.json");
        if legacy_config.exists() {
            let content = tokio::fs::read_to_string(&legacy_config).await?;
            let config_json: serde_json::Value = serde_json::from_str(&content)?;

            // Check if config already has environment-aware structure (dev/production keys)
            let final_config = if let Some(obj) = config_json.as_object() {
                if obj.contains_key("dev") || obj.contains_key("production") {
                    // Already environment-aware, use as-is
                    config_json
                } else {
                    // Not environment-aware, wrap with dev/production keys
                    serde_json::json!({
                        "dev": config_json.clone(),
                        "production": config_json
                    })
                }
            } else {
                // Not an object, wrap it
                serde_json::json!({
                    "dev": config_json.clone(),
                    "production": config_json
                })
            };

            tokio::fs::create_dir_all(&dest_dir).await?;
            let dest_file = dest_dir.join("config.json");
            let merged_content = serde_json::to_string_pretty(&final_config)?;
            tokio::fs::write(&dest_file, merged_content).await?;
        }

        Ok(())
    }

    /// Write embedded node configs for standalone mode
    ///
    /// Creates environment-aware config: configs/nodes/@mecha10/{node}/config.json
    /// with `dev` and `production` keys at the top level.
    async fn write_embedded_node_configs(&self, project_root: &Path, component_name: &str) -> Result<()> {
        // Get embedded configs for this node (both dev and production)
        let configs: Option<(&str, &str)> = match component_name {
            "motor" => Some((embedded_configs::MOTOR_DEV, embedded_configs::MOTOR_PRODUCTION)),
            // Add more nodes here as needed
            _ => None,
        };

        if let Some((dev_content, prod_content)) = configs {
            // Parse both configs
            let dev_json: serde_json::Value = serde_json::from_str(dev_content)?;
            let prod_json: serde_json::Value = serde_json::from_str(prod_content)?;

            // Create merged config with dev/production keys
            let merged = serde_json::json!({
                "dev": dev_json,
                "production": prod_json
            });

            // Write to: configs/nodes/@mecha10/{node}/config.json
            let dest_dir = project_root
                .join("configs")
                .join("nodes")
                .join("@mecha10")
                .join(component_name);
            tokio::fs::create_dir_all(&dest_dir).await?;
            let dest_file = dest_dir.join("config.json");
            let merged_content = serde_json::to_string_pretty(&merged)?;
            tokio::fs::write(&dest_file, merged_content).await?;
        }

        Ok(())
    }

    /// Copy all default node configuration files from framework to project
    ///
    /// Copies configs for all default nodes from `packages/nodes/{node}/configs/`
    /// to `{project}/configs/nodes/@mecha10/{node}/config.json`
    ///
    /// This is called during `mecha10 init` to set up node configs.
    /// Skips silently if framework path is not available (standalone CLI mode).
    ///
    /// # Arguments
    ///
    /// * `project_root` - Root path of the project
    pub async fn copy_all_node_configs(&self, project_root: &Path) -> Result<()> {
        // Default nodes that should have configs copied
        let default_nodes = [
            "behavior-executor",
            "image-classifier",
            "imu",
            "listener",
            "llm-command",
            "motor",
            "object-detector",
            "simulation-bridge",
            "speaker",
            "teleop",
            "websocket-bridge",
        ];

        for node in default_nodes {
            self.copy_node_configs(project_root, node).await?;
        }

        Ok(())
    }

    /// Detect the framework path for development mode
    ///
    /// Searches for the mecha10-monorepo in the following order:
    /// 1. MECHA10_FRAMEWORK_PATH environment variable
    /// 2. Walking up the directory tree from current directory
    ///
    /// This is used when creating projects in development mode to link
    /// to the local framework instead of published crates.
    ///
    /// # Returns
    ///
    /// The absolute path to the framework root, or an error if not found.
    pub fn detect_framework_path(&self) -> Result<String> {
        // First check if MECHA10_FRAMEWORK_PATH is set
        if let Ok(path) = std::env::var("MECHA10_FRAMEWORK_PATH") {
            let path_buf = std::path::PathBuf::from(&path);

            // Expand ~ to home directory if present
            let expanded_path = if let Some(stripped) = path.strip_prefix("~/") {
                if let Ok(home) = std::env::var("HOME") {
                    std::path::PathBuf::from(home).join(stripped)
                } else {
                    path_buf.clone()
                }
            } else {
                path_buf.clone()
            };

            // Validate that this is actually the framework directory
            let core_path = expanded_path.join("packages").join("core");
            if core_path.exists() {
                return Ok(expanded_path.to_string_lossy().to_string());
            } else {
                return Err(anyhow::anyhow!(
                    "MECHA10_FRAMEWORK_PATH is set to '{}' but this doesn't appear to be the framework root.\n\
                     Expected to find packages/core directory at that location.",
                    path
                ));
            }
        }

        // Fall back to walking up from current directory
        let mut current = std::env::current_dir()?;

        loop {
            // Check if this directory contains packages/core (framework marker)
            let core_path = current.join("packages").join("core");
            if core_path.exists() {
                // Found the framework root
                return Ok(current.to_string_lossy().to_string());
            }

            // Check if we reached the filesystem root
            if !current.pop() {
                return Err(anyhow::anyhow!(
                    "Could not detect framework path. Either:\n\
                     1. Set MECHA10_FRAMEWORK_PATH environment variable, or\n\
                     2. Run from within the mecha10-monorepo directory\n\n\
                     Example: export MECHA10_FRAMEWORK_PATH=~/src/mecha-industries/mecha10"
                ));
            }
        }
    }
}

impl Default for InitService {
    fn default() -> Self {
        Self::new()
    }
}