mecha10_cli/dev/lifecycle_adapter.rs
1//! Lifecycle adapter for CLI process management
2//!
3//! This module adapts the runtime lifecycle system for the CLI's process-based
4//! node management. While the runtime manages nodes in-process, the CLI spawns
5//! nodes as separate processes via node-runner.
6//!
7//! This adapter:
8//! - Reads lifecycle config from mecha10.json
9//! - Determines which nodes to spawn based on current mode
10//! - Provides mode change logic without runtime dependency
11
12use crate::types::project::{LifecycleConfig, ModeConfig, ProjectConfig};
13use anyhow::Result;
14use std::collections::{HashMap, HashSet};
15
16/// Lifecycle mode manager for CLI
17///
18/// Manages mode transitions and determines which nodes should run in each mode.
19/// This is a lightweight adapter that doesn't depend on the full runtime.
20pub struct CliLifecycleManager {
21 /// Current operational mode
22 current_mode: String,
23
24 /// Set of currently running node names
25 running_nodes: HashSet<String>,
26
27 /// Mode configurations from mecha10.json
28 mode_config: HashMap<String, ModeConfig>,
29}
30
31/// Result of calculating mode transition
32#[derive(Debug)]
33#[allow(dead_code)] // Will be used for mode change commands
34pub struct ModeTransitionDiff {
35 /// Nodes that need to be started
36 pub start: Vec<String>,
37
38 /// Nodes that need to be stopped
39 pub stop: Vec<String>,
40}
41
42impl CliLifecycleManager {
43 /// Create a new CLI lifecycle manager from project config
44 ///
45 /// Returns None if project doesn't have lifecycle configuration
46 pub fn from_project_config(config: &ProjectConfig) -> Option<Self> {
47 let lifecycle = config.lifecycle.as_ref()?;
48
49 Some(Self {
50 current_mode: lifecycle.default_mode.clone(),
51 running_nodes: HashSet::new(),
52 mode_config: lifecycle.modes.clone(),
53 })
54 }
55
56 /// Get the current mode
57 pub fn current_mode(&self) -> &str {
58 &self.current_mode
59 }
60
61 /// Get list of nodes that should run in the current mode
62 pub fn nodes_for_current_mode(&self) -> Vec<String> {
63 self.mode_config
64 .get(&self.current_mode)
65 .map(|config| config.nodes.clone())
66 .unwrap_or_default()
67 }
68
69 /// Calculate what changes are needed to transition to target mode
70 ///
71 /// Returns the diff (nodes to start/stop) without changing state.
72 #[allow(dead_code)] // Will be used for mode change commands
73 pub fn calculate_mode_diff(&self, target_mode: &str) -> Result<ModeTransitionDiff> {
74 // Validate mode exists
75 let target_config = self
76 .mode_config
77 .get(target_mode)
78 .ok_or_else(|| anyhow::anyhow!("Mode '{}' not found", target_mode))?;
79
80 // Nodes that should run in target mode
81 let target_nodes: HashSet<_> = target_config.nodes.iter().map(|s| s.as_str()).collect();
82
83 // Nodes to start: in target but not currently running
84 let start: Vec<_> = target_nodes
85 .iter()
86 .filter(|n| !self.running_nodes.contains(**n))
87 .map(|s| s.to_string())
88 .collect();
89
90 // Nodes to stop: running but not in target
91 let stop: Vec<_> = self
92 .running_nodes
93 .iter()
94 .filter(|n| !target_nodes.contains(n.as_str()))
95 .cloned()
96 .collect();
97
98 Ok(ModeTransitionDiff { start, stop })
99 }
100
101 /// Mark nodes as running (after spawning them)
102 pub fn mark_nodes_running(&mut self, nodes: &[String]) {
103 for node in nodes {
104 self.running_nodes.insert(node.clone());
105 }
106 }
107
108 /// Mark nodes as stopped (after killing them)
109 #[allow(dead_code)] // Will be used for mode change commands
110 pub fn mark_nodes_stopped(&mut self, nodes: &[String]) {
111 for node in nodes {
112 self.running_nodes.remove(node);
113 }
114 }
115
116 /// Change to a new mode (updates internal state only)
117 ///
118 /// Returns the diff of what needs to change. Caller is responsible
119 /// for actually spawning/killing processes.
120 #[allow(dead_code)] // Will be used for mode change commands
121 pub fn change_mode(&mut self, target_mode: &str) -> Result<ModeTransitionDiff> {
122 let diff = self.calculate_mode_diff(target_mode)?;
123 self.current_mode = target_mode.to_string();
124 Ok(diff)
125 }
126
127 /// Get available modes
128 #[allow(dead_code)] // Will be used for mode change commands
129 pub fn available_modes(&self) -> Vec<&str> {
130 self.mode_config.keys().map(|s| s.as_str()).collect()
131 }
132
133 /// Validate lifecycle configuration
134 ///
135 /// Checks that:
136 /// - All node references exist in project config
137 /// - Default mode exists
138 #[allow(dead_code)] // Will be used for validation on project init
139 pub fn validate(lifecycle: &LifecycleConfig, available_nodes: &[String]) -> Result<()> {
140 // Check default mode exists
141 if !lifecycle.modes.contains_key(&lifecycle.default_mode) {
142 return Err(anyhow::anyhow!(
143 "Default mode '{}' not found in modes",
144 lifecycle.default_mode
145 ));
146 }
147
148 // Check all node references are valid
149 let node_set: HashSet<_> = available_nodes.iter().map(|s| s.as_str()).collect();
150
151 for (mode_name, mode_config) in &lifecycle.modes {
152 for node in &mode_config.nodes {
153 if !node_set.contains(node.as_str()) {
154 return Err(anyhow::anyhow!(
155 "Mode '{}' references unknown node '{}'",
156 mode_name,
157 node
158 ));
159 }
160 }
161 }
162
163 Ok(())
164 }
165}