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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
#![allow(dead_code)]

//! Process service for managing child processes
//!
//! This service provides process lifecycle management for CLI commands,
//! particularly for the `dev` and `run` commands that need to manage
//! multiple node processes.
//!
//! This is a thin wrapper around mecha10-runtime's ProcessManager,
//! delegating core process management to the runtime layer.

use crate::paths;
use anyhow::{Context, Result};
use mecha10_runtime::ProcessManager;
use std::collections::HashMap;
use std::path::Path;
use std::process::{Command, Stdio};

/// Process service for managing child processes
///
/// This is a thin wrapper around the runtime's ProcessManager,
/// adding CLI-specific conveniences and delegating core functionality
/// to the runtime layer.
///
/// # Examples
///
/// ```rust,ignore
/// use mecha10_cli::services::ProcessService;
///
/// # async fn example() -> anyhow::Result<()> {
/// let mut service = ProcessService::new();
///
/// // Spawn a node process
/// service.spawn_node("camera_driver", "target/debug/camera_driver", &[])?;
///
/// // Check status
/// let status = service.get_status();
/// println!("Running processes: {:?}", status);
///
/// // Stop a specific process
/// service.stop("camera_driver")?;
///
/// // Cleanup all processes
/// service.cleanup();
/// # Ok(())
/// # }
/// ```
pub struct ProcessService {
    /// Runtime's process manager (handles core lifecycle)
    manager: ProcessManager,
}

impl ProcessService {
    /// Create a new process service
    pub fn new() -> Self {
        Self {
            manager: ProcessManager::new(),
        }
    }

    /// Extract node name from a full identifier
    ///
    /// Handles both formats:
    /// - Full identifier: `@mecha10/simulation-bridge` -> `simulation-bridge`
    /// - Plain name: `simulation-bridge` -> `simulation-bridge`
    fn extract_node_name(identifier: &str) -> String {
        if identifier.starts_with('@') {
            // Full identifier format: @scope/name
            identifier.split('/').next_back().unwrap_or(identifier).to_string()
        } else {
            identifier.to_string()
        }
    }

    /// Track dependency relationship for a node
    ///
    /// # Arguments
    ///
    /// * `node` - Name of the node
    /// * `dependencies` - List of nodes this node depends on
    pub fn track_dependency(&mut self, node: &str, dependencies: Vec<String>) {
        for dep in dependencies {
            self.manager.add_dependency(node.to_string(), dep);
        }
    }

    /// Get shutdown order (reverse dependency order)
    ///
    /// Returns nodes in order they should be stopped:
    /// - Nodes with dependents first (high-level nodes)
    /// - Then their dependencies (low-level nodes)
    ///
    /// This ensures we don't stop a node while other nodes depend on it.
    ///
    /// Delegates to the runtime's ProcessManager.
    pub fn get_shutdown_order(&self) -> Vec<String> {
        self.manager.shutdown_order()
    }

    /// Check if we're in framework development mode
    ///
    /// Framework dev mode is detected by MECHA10_FRAMEWORK_PATH environment variable.
    /// This is the only reliable indicator - .cargo/config.toml can exist in user projects too.
    pub fn is_framework_dev_mode() -> bool {
        std::env::var("MECHA10_FRAMEWORK_PATH").is_ok()
    }

    /// Find globally installed binary for a node
    ///
    /// Searches in:
    /// 1. ~/.cargo/bin/{node_name}
    /// 2. ~/.mecha10/bin/{node_name}
    ///
    /// # Arguments
    ///
    /// * `node_name` - Name of the node (e.g., "simulation-bridge")
    ///
    /// # Returns
    ///
    /// Path to the binary if found, None otherwise
    pub fn find_global_binary(node_name: &str) -> Option<std::path::PathBuf> {
        // Try ~/.cargo/bin/ first
        let cargo_bin = paths::user::cargo_bin(node_name);
        if cargo_bin.exists() && cargo_bin.is_file() {
            return Some(cargo_bin);
        }

        // Try ~/.mecha10/bin/
        let mecha10_bin = paths::user::bin(node_name);
        if mecha10_bin.exists() && mecha10_bin.is_file() {
            return Some(mecha10_bin);
        }

        None
    }

    /// Resolve binary path for a node with smart resolution
    ///
    /// Resolution strategy:
    /// 1. If framework dev mode: use local build (target/debug or target/release)
    /// 2. If global binary exists: use global binary
    /// 3. Fallback: use local build path
    ///
    /// # Arguments
    ///
    /// * `node_name` - Name of the node
    /// * `is_monorepo_node` - Whether this is a framework node
    /// * `project_name` - Name of the project
    ///
    /// # Returns
    ///
    /// Path to the binary to execute
    pub fn resolve_node_binary(node_name: &str, is_monorepo_node: bool, project_name: &str) -> String {
        // Framework dev mode: always use local builds
        if Self::is_framework_dev_mode() {
            return Self::get_local_binary_path(node_name, is_monorepo_node, project_name);
        }

        // For monorepo (framework) nodes, check for global installation
        if is_monorepo_node {
            if let Some(global_path) = Self::find_global_binary(node_name) {
                return global_path.to_string_lossy().to_string();
            }
        }

        // Fallback to local build
        Self::get_local_binary_path(node_name, is_monorepo_node, project_name)
    }

    /// Get local binary path (in target/ directory)
    fn get_local_binary_path(node_name: &str, is_monorepo_node: bool, project_name: &str) -> String {
        if is_monorepo_node {
            // Monorepo nodes run via the project binary with 'node' subcommand
            paths::target_path("release", project_name)
        } else {
            // Local nodes have their own binary
            paths::target_path("release", node_name)
        }
    }

    /// Resolve path to mecha10-node-runner binary
    ///
    /// Resolution strategy:
    /// 1. Framework dev mode: $MECHA10_FRAMEWORK_PATH/target/release/mecha10-node-runner
    /// 2. Global installation: ~/.cargo/bin/mecha10-node-runner
    /// 3. Fallback: "mecha10-node-runner" (rely on PATH)
    ///
    /// # Returns
    ///
    /// Path to the mecha10-node-runner binary
    pub fn resolve_node_runner_path() -> String {
        // Framework dev mode: use framework's target directory
        if let Ok(framework_path) = std::env::var("MECHA10_FRAMEWORK_PATH") {
            let framework_binary =
                std::path::PathBuf::from(&framework_path).join(paths::framework::NODE_RUNNER_RELEASE);

            if framework_binary.exists() {
                return framework_binary.to_string_lossy().to_string();
            }

            // Try debug build if release not available
            let framework_binary_debug =
                std::path::PathBuf::from(&framework_path).join(paths::framework::NODE_RUNNER_DEBUG);

            if framework_binary_debug.exists() {
                return framework_binary_debug.to_string_lossy().to_string();
            }
        }

        // Try global installation
        if let Some(global_path) = Self::find_global_binary("mecha10-node-runner") {
            return global_path.to_string_lossy().to_string();
        }

        // Fallback: rely on PATH
        "mecha10-node-runner".to_string()
    }

    /// Spawn a node process
    ///
    /// # Arguments
    ///
    /// * `name` - Name to identify the process
    /// * `binary_path` - Path to the binary to execute
    /// * `args` - Command-line arguments
    ///
    /// # Errors
    ///
    /// Returns an error if the process cannot be spawned
    pub fn spawn_node(&mut self, name: &str, binary_path: &str, args: &[&str]) -> Result<u32> {
        let child = Command::new(binary_path)
            .args(args)
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .spawn()
            .with_context(|| format!("Failed to spawn process: {}", binary_path))?;

        let pid = child.id();
        self.manager.track(name.to_string(), child);

        Ok(pid)
    }

    /// Spawn a process with output capture
    ///
    /// # Arguments
    ///
    /// * `name` - Name to identify the process
    /// * `binary_path` - Path to the binary to execute
    /// * `args` - Command-line arguments
    ///
    /// # Errors
    ///
    /// Returns an error if the process cannot be spawned
    pub fn spawn_with_output(&mut self, name: &str, binary_path: &str, args: &[&str]) -> Result<u32> {
        let child = Command::new(binary_path)
            .args(args)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .with_context(|| format!("Failed to spawn process: {}", binary_path))?;

        let pid = child.id();
        self.manager.track(name.to_string(), child);

        Ok(pid)
    }

    /// Spawn a process with custom environment variables
    ///
    /// # Arguments
    ///
    /// * `name` - Name to identify the process
    /// * `binary_path` - Path to the binary to execute
    /// * `args` - Command-line arguments
    /// * `env` - Environment variables to set
    pub fn spawn_with_env(
        &mut self,
        name: &str,
        binary_path: &str,
        args: &[&str],
        env: HashMap<String, String>,
    ) -> Result<u32> {
        // Create logs directory if it doesn't exist
        let logs_dir = std::path::PathBuf::from(paths::project::LOGS_DIR);
        if !logs_dir.exists() {
            std::fs::create_dir_all(&logs_dir)?;
        }

        // Create log file for this process
        // Use short node name for log file (e.g., "@mecha10/listener" -> "listener.log")
        let log_name = Self::extract_node_name(name);
        let log_file_path = logs_dir.join(format!("{}.log", log_name));
        let log_file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&log_file_path)
            .with_context(|| format!("Failed to create log file: {}", log_file_path.display()))?;

        // Clone for stderr
        let log_file_stderr = log_file.try_clone().context("Failed to clone log file handle")?;

        // Debug: Log environment being passed to process
        tracing::debug!("🔧 spawn_with_env for '{}': received {} env vars", name, env.len());
        if !env.is_empty() {
            for (key, value) in &env {
                if key == "ROBOT_API_KEY" {
                    tracing::debug!("  {} = <redacted>", key);
                } else {
                    tracing::debug!("  {} = {}", key, value);
                }
            }
        } else {
            tracing::warn!("⚠️  No environment variables to inject!");
        }

        let mut cmd = Command::new(binary_path);
        cmd.args(args)
            .envs(&env)
            .stdout(log_file) // Redirect stdout to log file
            .stderr(log_file_stderr); // Redirect stderr to log file

        // On Unix: Create new process group to prevent terminal signals from reaching child processes
        // This ensures Ctrl+C in the terminal only affects the main CLI process, not node-runner
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;
            cmd.process_group(0); // 0 = create new process group with same ID as child PID
        }

        let child = cmd
            .spawn()
            .with_context(|| format!("Failed to spawn process: {}", binary_path))?;

        let pid = child.id();
        self.manager.track(name.to_string(), child);

        Ok(pid)
    }

    /// Spawn a process in a specific working directory
    ///
    /// # Arguments
    ///
    /// * `name` - Name to identify the process
    /// * `binary_path` - Path to the binary to execute
    /// * `args` - Command-line arguments
    /// * `working_dir` - Working directory for the process
    pub fn spawn_in_dir(
        &mut self,
        name: &str,
        binary_path: &str,
        args: &[&str],
        working_dir: impl AsRef<Path>,
    ) -> Result<u32> {
        let child = Command::new(binary_path)
            .args(args)
            .current_dir(working_dir)
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .spawn()
            .with_context(|| format!("Failed to spawn process: {}", binary_path))?;

        let pid = child.id();
        self.manager.track(name.to_string(), child);

        Ok(pid)
    }

    /// Spawn multiple node processes from a list
    ///
    /// # Arguments
    ///
    /// * `nodes` - Vec of (name, binary_path, args) tuples
    ///
    /// # Returns
    ///
    /// HashMap of node names to PIDs
    pub fn spawn_nodes(&mut self, nodes: Vec<(&str, &str, Vec<&str>)>) -> Result<HashMap<String, u32>> {
        let mut pids = HashMap::new();

        for (name, binary_path, args) in nodes {
            match self.spawn_node(name, binary_path, &args) {
                Ok(pid) => {
                    pids.insert(name.to_string(), pid);
                }
                Err(e) => {
                    eprintln!("Failed to spawn {}: {}", name, e);
                }
            }
        }

        Ok(pids)
    }

    /// Get status of all processes
    ///
    /// Returns a HashMap mapping process names to status strings
    pub fn get_status(&mut self) -> HashMap<String, String> {
        use mecha10_runtime::ProcessStatus;

        self.manager
            .status_all()
            .into_iter()
            .map(|(name, status)| {
                let status_str = match status {
                    ProcessStatus::Running => "running".to_string(),
                    ProcessStatus::Exited(code) => format!("exited (code: {})", code),
                    ProcessStatus::Error => "error".to_string(),
                };
                (name, status_str)
            })
            .collect()
    }

    /// Get the number of tracked processes
    pub fn count(&self) -> usize {
        self.manager.len()
    }

    /// Check if any processes are being tracked
    pub fn is_empty(&self) -> bool {
        self.manager.is_empty()
    }

    /// Stop a specific process by name
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the process to stop
    ///
    /// # Errors
    ///
    /// Returns an error if the process is not found
    ///
    /// Note: This uses a default 10-second timeout for graceful shutdown.
    /// Use stop_with_timeout() for custom timeout.
    pub fn stop(&mut self, name: &str) -> Result<()> {
        self.manager.stop_graceful(name, std::time::Duration::from_secs(10))
    }

    /// Stop a process with timeout for graceful shutdown
    ///
    /// Tries graceful shutdown (SIGTERM on Unix), then force kills after timeout
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the process to stop
    /// * `timeout` - How long to wait for graceful shutdown
    ///
    /// # Errors
    ///
    /// Returns an error if process not found or cannot be stopped
    pub fn stop_with_timeout(&mut self, name: &str, timeout: std::time::Duration) -> Result<()> {
        self.manager.stop_graceful(name, timeout)
    }

    /// Force kill a process by name
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the process to kill
    pub fn force_kill(&mut self, name: &str) -> Result<()> {
        self.manager.force_kill(name)
    }

    /// Stop all processes gracefully in dependency order
    ///
    /// This delegates to the runtime's ProcessManager which handles:
    /// - Dependency-based shutdown ordering
    /// - Graceful shutdown with timeout
    /// - Force kill fallback
    pub fn cleanup(&mut self) {
        self.manager.shutdown_all();
    }

    /// Check if a process is running
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the process to check
    pub fn is_running(&mut self, name: &str) -> bool {
        self.manager.is_running(name)
    }

    /// Get access to the underlying ProcessManager
    ///
    /// Useful for advanced operations or when migrating existing code.
    /// Provides direct access to the runtime's ProcessManager.
    pub fn manager(&mut self) -> &mut ProcessManager {
        &mut self.manager
    }

    /// Build a node binary if needed
    ///
    /// Helper method to build a specific node package
    ///
    /// # Arguments
    ///
    /// * `node_name` - Name of the node to build
    /// * `release` - Whether to build in release mode
    pub fn build_node(&self, node_name: &str, release: bool) -> Result<()> {
        let mut cmd = Command::new("cargo");
        cmd.arg("build");

        if release {
            cmd.arg("--release");
        }

        cmd.arg("--bin").arg(node_name);

        let output = cmd
            .output()
            .with_context(|| format!("Failed to build node: {}", node_name))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(anyhow::anyhow!("Build failed for {}: {}", node_name, stderr));
        }

        Ok(())
    }

    /// Build all nodes in the workspace
    ///
    /// # Arguments
    ///
    /// * `release` - Whether to build in release mode
    pub fn build_all(&self, release: bool) -> Result<()> {
        let mut cmd = Command::new("cargo");
        cmd.arg("build");

        if release {
            cmd.arg("--release");
        }

        cmd.arg("--all");

        let output = cmd.output().context("Failed to build workspace")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(anyhow::anyhow!("Build failed: {}", stderr));
        }

        Ok(())
    }

    /// Build a binary from the framework monorepo
    ///
    /// This builds a binary from the framework path (MECHA10_FRAMEWORK_PATH).
    /// Used for binaries like `mecha10-node-runner` that exist in the monorepo
    /// but need to be built when running from a generated project.
    ///
    /// # Arguments
    ///
    /// * `package_name` - Name of the package to build (e.g., "mecha10-node-runner")
    /// * `release` - Whether to build in release mode
    ///
    /// # Returns
    ///
    /// Ok(()) on success, or error if build fails or framework path not set
    pub fn build_from_framework(&self, package_name: &str, release: bool) -> Result<()> {
        // Get framework path from environment
        let framework_path = std::env::var("MECHA10_FRAMEWORK_PATH")
            .context("MECHA10_FRAMEWORK_PATH not set - cannot build from framework")?;

        let mut cmd = Command::new("cargo");
        cmd.arg("build");

        if release {
            cmd.arg("--release");
        }

        cmd.arg("-p").arg(package_name);
        cmd.current_dir(&framework_path);

        let output = cmd
            .output()
            .with_context(|| format!("Failed to build package from framework: {}", package_name))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(anyhow::anyhow!(
                "Build failed for {} (from framework): {}",
                package_name,
                stderr
            ));
        }

        Ok(())
    }

    /// Build only packages needed by the current project (smart selective build)
    ///
    /// For generated projects, this just builds the project binary.
    /// Cargo automatically builds only the dependencies actually used.
    /// With .cargo/config.toml patches, this rebuilds framework packages from source.
    ///
    /// # Arguments
    ///
    /// * `release` - Whether to build in release mode
    ///
    /// # Returns
    ///
    /// Ok(()) on success, or error if build fails
    pub fn build_project_packages(&self, release: bool) -> Result<()> {
        use crate::types::ProjectConfig;

        // Load project config
        let config_path = std::path::Path::new(paths::PROJECT_CONFIG);
        if !config_path.exists() {
            // Fallback to build_all if no project config
            return self.build_all(release);
        }

        // Parse config to get project name
        let config_content = std::fs::read_to_string(config_path)?;
        let config: ProjectConfig = serde_json::from_str(&config_content)?;

        // Build just the project binary
        // Cargo will automatically:
        // 1. Resolve dependencies from Cargo.toml
        // 2. Apply .cargo/config.toml patches (framework dev mode)
        // 3. Build only the dependencies actually used
        // 4. Use incremental compilation for unchanged code
        let mut cmd = Command::new("cargo");
        cmd.arg("build");

        if release {
            cmd.arg("--release");
        }

        // Build the project binary - Cargo handles the rest
        cmd.arg("--bin").arg(&config.name);

        let output = cmd.output().context("Failed to build project")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(anyhow::anyhow!("Build failed: {}", stderr));
        }

        Ok(())
    }

    /// Restart a specific process
    ///
    /// Stops the process if running and starts it again
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the process
    /// * `binary_path` - Path to the binary
    /// * `args` - Command-line arguments
    pub fn restart(&mut self, name: &str, binary_path: &str, args: &[&str]) -> Result<u32> {
        // Stop if running
        if self.is_running(name) {
            self.stop(name)?;
            // Give it a moment to shutdown
            std::thread::sleep(std::time::Duration::from_millis(100));
        }

        // Start again
        self.spawn_node(name, binary_path, args)
    }

    /// Restart all processes
    ///
    /// # Arguments
    ///
    /// * `nodes` - Vec of (name, binary_path, args) tuples
    pub fn restart_all(&mut self, nodes: Vec<(&str, &str, Vec<&str>)>) -> Result<HashMap<String, u32>> {
        // Stop all
        self.cleanup();

        // Small delay for cleanup
        std::thread::sleep(std::time::Duration::from_millis(500));

        // Start all
        self.spawn_nodes(nodes)
    }

    /// Spawn a node using mecha10-node-runner
    ///
    /// This is the simplified spawning method for Phase 2+ of Node Lifecycle Architecture.
    /// It delegates all complexity (binary resolution, model pulling, env setup) to node-runner.
    ///
    /// # Arguments
    ///
    /// * `node_name` - Name of the node to run
    ///
    /// # Returns
    ///
    /// Process ID of the spawned node-runner instance
    ///
    /// # Errors
    ///
    /// Returns an error if the node-runner cannot be spawned
    ///
    /// # Configuration
    ///
    /// The node-runner reads configuration from the node's config file (e.g., `configs/nodes/{node_name}.json`)
    /// and supports the following runtime settings:
    ///
    /// ```json
    /// {
    ///   "runtime": {
    ///     "restart_policy": "on-failure",  // never, on-failure, always
    ///     "max_retries": 3,
    ///     "backoff_secs": 1
    ///   },
    ///   "depends_on": ["camera", "lidar"],
    ///   "startup_timeout_secs": 30
    /// }
    /// ```
    ///
    /// To enable dependency checking, use: `mecha10-node-runner --wait-for-deps <node-name>`
    pub fn spawn_node_runner(
        &mut self,
        node_identifier: &str,
        project_env: Option<HashMap<String, String>>,
    ) -> Result<u32> {
        // Extract node name from full identifier (e.g., @mecha10/listener -> listener)
        let node_name = Self::extract_node_name(node_identifier);

        // Simply spawn: mecha10-node-runner <node-name>
        // The node-runner handles:
        // - Binary path resolution (monorepo vs local)
        // - Model pulling (if node needs AI models)
        // - Environment setup
        // - Log redirection
        // - Restart policies (from config)
        // - Health monitoring
        // - Dependency checking (if --wait-for-deps enabled)
        // - Actual node execution

        // Resolve path to mecha10-node-runner binary
        let runner_path = Self::resolve_node_runner_path();

        // Build environment - include project vars for config substitution
        let env = project_env.unwrap_or_default();

        // Register with full identifier (e.g., @mecha10/listener) for consistent tracking
        // The node-runner only needs the short name as an argument
        self.spawn_with_env(node_identifier, &runner_path, &[&node_name], env)
    }

    /// Spawn a node directly (standalone mode)
    ///
    /// This is used when mecha10-node-runner is not available (standalone projects
    /// installed from crates.io). Handles both framework nodes (via BinaryManager)
    /// and local project nodes (built and run directly).
    ///
    /// Resolution strategy for framework nodes:
    /// 1. Check ~/.mecha10/bin/ for pre-downloaded binary
    /// 2. If not found, attempt to download from GitHub releases
    /// 3. If download fails, fall back to cargo install
    ///
    /// # Arguments
    ///
    /// * `node_name` - Name of the node to run
    /// * `project_name` - Name of the project (used to find the binary)
    /// * `project_env` - Optional additional environment variables from project config
    ///
    /// # Returns
    ///
    /// Process ID of the spawned node process
    pub fn spawn_node_direct(
        &mut self,
        node_identifier: &str,
        _project_name: &str,
        project_env: Option<HashMap<String, String>>,
    ) -> Result<u32> {
        // Extract node name from full identifier (e.g., @mecha10/listener -> listener)
        let node_name = Self::extract_node_name(node_identifier);

        // Check if this is a local project node by looking at mecha10.json
        let is_local_node = self.is_local_project_node(&node_name);

        let mut env = HashMap::new();
        // Use full identifier for NODE_NAME so health reports and dashboard are consistent
        env.insert("NODE_NAME".to_string(), node_identifier.to_string());
        if let Ok(rust_log) = std::env::var("RUST_LOG") {
            env.insert("RUST_LOG".to_string(), rust_log);
        }

        // Add project environment variables (REDIS_URL, control plane, robot info, etc.)
        if let Some(project_vars) = project_env {
            tracing::debug!(
                "🔀 spawn_node_direct for '{}': merging {} project vars",
                node_name,
                project_vars.len()
            );
            for (key, value) in &project_vars {
                tracing::debug!(
                    "  Adding: {} = {}",
                    key,
                    if key == "ROBOT_API_KEY" { "<redacted>" } else { value }
                );
            }
            env.extend(project_vars);
        } else {
            tracing::warn!("⚠️  spawn_node_direct for '{}': No project_env provided!", node_name);
        }

        tracing::debug!(
            "🏁 spawn_node_direct for '{}': final env has {} vars, is_local: {}",
            node_name,
            env.len(),
            is_local_node
        );

        if is_local_node {
            // Local project node: build and run the binary directly
            // Register with full identifier (e.g., @local/my-node) for consistent tracking
            self.spawn_local_node_with_identifier(node_identifier, &node_name, env)
        } else {
            // Framework node: resolve binary via BinaryManager
            // This will download from GitHub releases if not cached
            self.spawn_framework_node(node_identifier, &node_name, env)
        }
    }

    /// Spawn a framework node using BinaryManager for binary resolution
    ///
    /// This method resolves the binary path using BinaryManager, which:
    /// 1. Checks the local cache (~/.mecha10/bin/)
    /// 2. Downloads from GitHub releases if needed
    /// 3. Falls back to cargo install for unsupported platforms
    fn spawn_framework_node(
        &mut self,
        node_identifier: &str,
        node_name: &str,
        env: HashMap<String, String>,
    ) -> Result<u32> {
        use super::binary_manager::BinaryManager;

        // Try to resolve binary via BinaryManager
        let binary_manager = BinaryManager::new()?;

        // Use block_in_place to run async code in sync context
        let binary_path = tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current().block_on(binary_manager.resolve(node_name))
        })?;

        tracing::info!(
            "🚀 Spawning framework node '{}' from {}",
            node_name,
            binary_path.display()
        );

        // Spawn the binary directly
        self.spawn_with_env(node_identifier, &binary_path.to_string_lossy(), &[], env)
    }

    /// Check if a node is a local project node (defined in nodes/ directory)
    fn is_local_project_node(&self, node_name: &str) -> bool {
        use crate::types::{NodeSource, ProjectConfig};

        let config_path = std::path::Path::new(paths::PROJECT_CONFIG);
        if !config_path.exists() {
            return false;
        }

        let config_content = match std::fs::read_to_string(config_path) {
            Ok(c) => c,
            Err(_) => return false,
        };

        let config: ProjectConfig = match serde_json::from_str(&config_content) {
            Ok(c) => c,
            Err(_) => return false,
        };

        // Check if node exists as a project node (nodes/<name>)
        config
            .nodes
            .find_by_name(node_name)
            .map(|spec| spec.source == NodeSource::Project)
            .unwrap_or(false)
    }

    /// Spawn a local project node with full identifier for tracking
    ///
    /// Builds the node with cargo and runs the binary directly.
    /// Registers the process with the full identifier (e.g., @local/my-node) for consistent tracking.
    fn spawn_local_node_with_identifier(
        &mut self,
        node_identifier: &str,
        node_name: &str,
        env: HashMap<String, String>,
    ) -> Result<u32> {
        use std::process::Command;

        // First, build the node
        tracing::info!("🔨 Building local node: {}", node_name);

        let build_output = Command::new("cargo")
            .args(["build", "-p", node_name])
            .output()
            .context("Failed to run cargo build")?;

        if !build_output.status.success() {
            let stderr = String::from_utf8_lossy(&build_output.stderr);
            anyhow::bail!("Failed to build node '{}': {}", node_name, stderr);
        }

        tracing::info!("✅ Built local node: {}", node_name);

        // Run the binary from target/debug/<name>
        let binary_path = paths::target_path("debug", node_name);

        if !std::path::Path::new(&binary_path).exists() {
            anyhow::bail!(
                "Binary not found at '{}'. Build may have failed or the package name differs from node name.",
                binary_path
            );
        }

        // Register with full identifier for consistent tracking
        self.spawn_with_env(node_identifier, &binary_path, &[], env)
    }

    /// Resolve path to mecha10 CLI binary
    fn resolve_cli_binary() -> Result<String> {
        // First try to find mecha10 in PATH
        if let Some(path) = Self::find_global_binary("mecha10") {
            return Ok(path.to_string_lossy().to_string());
        }

        // Try common install locations
        let locations = [paths::user::local_bin("mecha10"), paths::user::cargo_bin("mecha10")];

        for path in &locations {
            if path.exists() {
                return Ok(path.to_string_lossy().to_string());
            }
        }

        // Fall back to current executable (we are mecha10!)
        if let Ok(exe) = std::env::current_exe() {
            return Ok(exe.to_string_lossy().to_string());
        }

        anyhow::bail!("Could not find mecha10 CLI binary. Ensure it's installed and in your PATH.")
    }

    /// Check if mecha10-node-runner is available
    pub fn is_node_runner_available() -> bool {
        // Check framework path first
        if let Ok(framework_path) = std::env::var("MECHA10_FRAMEWORK_PATH") {
            let release = std::path::PathBuf::from(&framework_path).join(paths::framework::NODE_RUNNER_RELEASE);
            let debug = std::path::PathBuf::from(&framework_path).join(paths::framework::NODE_RUNNER_DEBUG);
            if release.exists() || debug.exists() {
                return true;
            }
        }

        // Check global installation
        Self::find_global_binary("mecha10-node-runner").is_some()
    }
}

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

impl Drop for ProcessService {
    fn drop(&mut self) {
        // ProcessManager's Drop will handle graceful shutdown
    }
}