mecha10-cli 0.9.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
#![allow(dead_code)]

//! CLI execution context
//!
//! The CliContext is the single source of truth for runtime configuration,
//! combining CLI flags, environment variables, and config file settings.

use crate::paths;
use crate::services::{
    AssetsDownloadService, ComponentCatalogService, ConfigService, DeploymentService, DevService, DiscoveryService,
    DockerService, InitService, PackageService, ProcessService, ProjectService, ProjectTemplateService, RedisService,
    SimulationService, TemplateDownloadService, TopologyService,
};
use crate::types::ProjectConfig;
use std::path::PathBuf;
use tracing::Level;

pub struct CliContext {
    pub config_path: PathBuf,

    pub log_level: Level,

    pub working_dir: PathBuf,

    redis_url: String,

    postgres_url: Option<String>,

    verbose: bool,

    redis_service: Option<RedisService>,
    project_service: Option<ProjectService>,
    simulation_service: Option<SimulationService>,
    process_service: Option<ProcessService>,
    shared_process_service: Option<std::sync::Arc<std::sync::Mutex<ProcessService>>>,
    docker_service: Option<DockerService>,
    package_service: Option<PackageService>,
    deployment_service: Option<DeploymentService>,
    component_catalog_service: Option<ComponentCatalogService>,
    discovery_service: Option<DiscoveryService>,
    init_service: Option<InitService>,
    project_template_service: Option<ProjectTemplateService>,
    dev_service: Option<DevService>,
    topology_service: Option<TopologyService>,
    template_download_service: Option<TemplateDownloadService>,
    assets_download_service: Option<AssetsDownloadService>,

    _phantom: std::marker::PhantomData<ProjectConfig>,
}

macro_rules! lazy_init_getter {
    ($(#[$meta:meta])* fn $name:ident() -> &$ty:ty, $field:ident, self |$self_:ident| $ctor:expr) => {
        $(#[$meta])*
        pub fn $name(&mut self) -> &$ty {
            if self.$field.is_none() {
                let value = {
                    let $self_ = &*self;
                    $ctor
                };
                self.$field = Some(value);
            }
            self.$field.as_ref().unwrap()
        }
    };
    ($(#[$meta:meta])* fn $name:ident() -> &$ty:ty, $field:ident, $ctor:expr) => {
        $(#[$meta])*
        pub fn $name(&mut self) -> &$ty {
            if self.$field.is_none() {
                self.$field = Some($ctor);
            }
            self.$field.as_ref().unwrap()
        }
    };
    ($(#[$meta:meta])* mut fn $name:ident() -> &mut $ty:ty, $field:ident, $ctor:expr) => {
        $(#[$meta])*
        pub fn $name(&mut self) -> &mut $ty {
            if self.$field.is_none() {
                self.$field = Some($ctor);
            }
            self.$field.as_mut().unwrap()
        }
    };
    ($(#[$meta:meta])* try fn $name:ident() -> &$ty:ty, $field:ident, |$self_:ident| $ctor:expr) => {
        $(#[$meta])*
        pub fn $name(&mut self) -> anyhow::Result<&$ty> {
            if self.$field.is_none() {
                let value = {
                    let $self_ = &*self;
                    $ctor
                };
                self.$field = Some(value);
            }
            Ok(self.$field.as_ref().unwrap())
        }
    };
}

impl CliContext {
    /// Load the project configuration
    ///
    /// This loads the configuration from disk each time it's called.
    /// For better performance in commands that access config multiple times,
    /// call this once and store the result.
    pub async fn load_project_config(&self) -> anyhow::Result<ProjectConfig> {
        ConfigService::load_from(&self.config_path).await
    }

    /// Check if a project is initialized (mecha10.json exists)
    pub fn is_project_initialized(&self) -> bool {
        ConfigService::is_initialized(&self.working_dir)
    }

    /// Get a path relative to the project root
    pub fn project_path(&self, path: &str) -> PathBuf {
        self.working_dir.join(path)
    }

    /// Check if verbose mode is enabled
    pub fn is_verbose(&self) -> bool {
        self.verbose
    }

    /// Get the Redis connection URL
    pub fn redis_url(&self) -> &str {
        &self.redis_url
    }

    /// Get the PostgreSQL connection URL if configured
    pub fn postgres_url(&self) -> Option<&str> {
        self.postgres_url.as_deref()
    }

    lazy_init_getter!(
        /// Get Redis service (creates on first access)
        try fn redis() -> &RedisService, redis_service, |s| RedisService::new(&s.redis_url)?
    );

    lazy_init_getter!(
        /// Get Project service (creates on first access)
        try fn project() -> &ProjectService, project_service, |s| ProjectService::detect(&s.working_dir)?
    );

    lazy_init_getter!(
        /// Get Simulation service (creates on first access)
        fn simulation() -> &SimulationService, simulation_service, SimulationService::new()
    );

    lazy_init_getter!(
        /// Get Process service (creates on first access)
        mut fn process() -> &mut ProcessService, process_service, ProcessService::new()
    );

    /// Get shared Process service for concurrent access
    ///
    /// Returns an `Arc<Mutex<ProcessService>>` that can be safely shared between tasks.
    pub fn shared_process(&mut self) -> std::sync::Arc<std::sync::Mutex<ProcessService>> {
        if self.shared_process_service.is_none() {
            self.shared_process_service = Some(std::sync::Arc::new(std::sync::Mutex::new(ProcessService::new())));
        }
        self.shared_process_service.as_ref().unwrap().clone()
    }

    lazy_init_getter!(
        /// Get Docker service (creates on first access)
        fn docker() -> &DockerService, docker_service, DockerService::new()
    );

    /// Get Package service (creates on first access)
    ///
    /// Note: This requires a valid project to be detected with name and version.
    pub fn package(&mut self) -> anyhow::Result<&PackageService> {
        if self.package_service.is_none() {
            let project = self.project()?;
            let name = project.name()?;
            let version = project.version()?;
            self.package_service = Some(PackageService::new(name, version, self.working_dir.clone())?);
        }
        Ok(self.package_service.as_ref().unwrap())
    }

    lazy_init_getter!(
        /// Get Deployment service (creates on first access)
        fn deployment() -> &DeploymentService, deployment_service, DeploymentService::new()
    );

    lazy_init_getter!(
        /// Get Component Catalog service (creates on first access)
        fn component_catalog() -> &ComponentCatalogService, component_catalog_service, ComponentCatalogService::new()
    );

    lazy_init_getter!(
        /// Get Discovery service (creates on first access)
        mut fn discovery() -> &mut DiscoveryService, discovery_service, DiscoveryService::new()
    );

    lazy_init_getter!(
        /// Get Init service (creates on first access)
        fn init_service() -> &InitService, init_service, InitService::new()
    );

    lazy_init_getter!(
        /// Get Project Template service (creates on first access)
        fn project_template_service() -> &ProjectTemplateService, project_template_service, ProjectTemplateService::new()
    );

    lazy_init_getter!(
        /// Get Dev service (creates on first access)
        fn dev() -> &DevService, dev_service, self |s| DevService::new(s.redis_url.clone())
    );

    lazy_init_getter!(
        /// Get Topology service (creates on first access)
        ///
        /// The topology service performs static analysis of project structure,
        /// extracting node definitions and pub/sub topic relationships from source code.
        fn topology() -> &TopologyService, topology_service, self |s| TopologyService::new(s.working_dir.clone())
    );

    lazy_init_getter!(
        /// Get Template Download service (creates on first access)
        ///
        /// Downloads project templates from GitHub releases on-demand.
        /// Templates are versioned and cached locally for offline use.
        fn template_download() -> &TemplateDownloadService, template_download_service, TemplateDownloadService::new()
    );

    lazy_init_getter!(
        /// Get Assets Download service (creates on first access)
        ///
        /// Downloads the current `mecha10-assets` content (behaviors, RL tasks/jobs, simulation
        /// models/environments, `mecha10.json.template`) from `mecha10-api` on-demand. No
        /// version/cache concept, unlike [`Self::template_download`] - every fetch is fresh.
        fn assets_download() -> &AssetsDownloadService, assets_download_service, AssetsDownloadService::new()
    );

    /// Validate project structure
    ///
    /// Checks that the project has the expected directory structure
    /// and required files.
    pub fn validate_project_structure(&self) -> anyhow::Result<()> {
        if !self.is_project_initialized() {
            return Err(anyhow::anyhow!("Project not initialized. Run 'mecha10 init' first."));
        }

        let required_dirs = vec!["nodes", "drivers"];
        for dir in required_dirs {
            let path = self.project_path(dir);
            if !path.exists() {
                return Err(anyhow::anyhow!(
                    "Required directory missing: {}. Expected at: {}",
                    dir,
                    path.display()
                ));
            }
        }

        Ok(())
    }

    /// Check if running in CI environment
    pub fn is_ci(&self) -> bool {
        is_ci_environment()
    }

    /// Get logs directory path
    pub fn logs_dir(&self) -> PathBuf {
        self.project_path("logs")
    }

    /// Get data directory path
    pub fn data_dir(&self) -> PathBuf {
        self.project_path("data")
    }

    /// Get recordings directory path
    pub fn recordings_dir(&self) -> PathBuf {
        self.project_path("data/recordings")
    }

    /// Get maps directory path
    pub fn maps_dir(&self) -> PathBuf {
        self.project_path("data/maps")
    }

    /// Get telemetry directory path
    pub fn telemetry_dir(&self) -> PathBuf {
        self.project_path("data/telemetry")
    }

    /// Get simulation directory path
    pub fn simulation_dir(&self) -> PathBuf {
        self.project_path(paths::project::SIMULATION_DIR)
    }

    /// Get RL task-curriculum configs directory path (`configs/rl/tasks`, LAB-2429) - deliberately
    /// separate from `simulation_dir()` since tasks are project RL config, not a simulation/
    /// physics/rendering asset.
    pub fn rl_tasks_dir(&self) -> PathBuf {
        self.project_path(paths::project::RL_TASKS_DIR)
    }

    /// Get target/debug directory path
    pub fn target_debug_dir(&self) -> PathBuf {
        self.project_path("target/debug")
    }

    /// Get target/release directory path
    pub fn target_release_dir(&self) -> PathBuf {
        self.project_path("target/release")
    }

    /// Get packages output directory path
    pub fn packages_dir(&self) -> PathBuf {
        self.project_path("target/packages")
    }

    /// Ensure a directory exists, creating it if necessary
    pub fn ensure_dir(&self, path: &PathBuf) -> anyhow::Result<()> {
        if !path.exists() {
            std::fs::create_dir_all(path)?;
        }
        Ok(())
    }
}

impl Default for CliContext {
    fn default() -> Self {
        CliContextBuilder::new()
            .log_level(Level::INFO)
            .build()
            .expect("Failed to build default CliContext")
    }
}

pub struct CliContextBuilder {
    config_path: Option<PathBuf>,
    log_level: Option<Level>,
    working_dir: Option<PathBuf>,
    redis_url: Option<String>,
    postgres_url: Option<String>,
    verbose: Option<bool>,
}

impl CliContextBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        Self {
            config_path: None,
            log_level: None,
            working_dir: None,
            redis_url: None,
            postgres_url: None,
            verbose: None,
        }
    }

    mecha10_core::builder_setter!(
        /// Set config file path
        assign, config_path, config_path, Option<PathBuf>
    );

    mecha10_core::builder_setter!(
        /// Set log level
        into_some, log_level, log_level, Level
    );

    mecha10_core::builder_setter!(
        /// Set working directory
        into_some, working_dir, working_dir, PathBuf
    );

    mecha10_core::builder_setter!(
        /// Set Redis URL
        into_some, redis_url, redis_url, String
    );

    mecha10_core::builder_setter!(
        /// Set PostgreSQL URL
        assign, postgres_url, postgres_url, Option<String>
    );

    mecha10_core::builder_setter!(
        /// Set verbose mode
        into_some, verbose, verbose, bool
    );

    /// Build the CliContext with proper precedence
    pub fn build(self) -> anyhow::Result<CliContext> {
        let working_dir = self
            .working_dir
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));

        let config_path = self
            .config_path
            .unwrap_or_else(|| working_dir.join(paths::PROJECT_CONFIG));

        let config_redis_url = if config_path.exists() {
            std::fs::read_to_string(&config_path)
                .ok()
                .and_then(|content| serde_json::from_str::<serde_json::Value>(&content).ok())
                .and_then(|json| json.get("redis")?.get("url")?.as_str().map(String::from))
        } else {
            None
        };

        let redis_url = self
            .redis_url
            .or_else(|| std::env::var("MECHA10_REDIS_URL").ok())
            .or_else(|| std::env::var("REDIS_URL").ok())
            .or(config_redis_url)
            .unwrap_or_else(|| "redis://localhost:6379".to_string());

        let postgres_url = self
            .postgres_url
            .or_else(|| std::env::var("DATABASE_URL").ok())
            .or_else(|| std::env::var("POSTGRES_URL").ok());

        let log_level = self.log_level.unwrap_or(Level::INFO);

        let verbose = self.verbose.unwrap_or(false);

        Ok(CliContext {
            config_path,
            log_level,
            working_dir,
            redis_url,
            postgres_url,
            verbose,
            redis_service: None,
            project_service: None,
            simulation_service: None,
            process_service: None,
            shared_process_service: None,
            docker_service: None,
            package_service: None,
            deployment_service: None,
            component_catalog_service: None,
            discovery_service: None,
            init_service: None,
            project_template_service: None,
            dev_service: None,
            topology_service: None,
            template_download_service: None,
            assets_download_service: None,
            _phantom: std::marker::PhantomData,
        })
    }
}

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

/// Check if running in a CI environment.
///
/// Standalone free function so call sites without a `CliContext` handy can still check this.
pub fn is_ci_environment() -> bool {
    std::env::var("CI").is_ok()
        || std::env::var("GITHUB_ACTIONS").is_ok()
        || std::env::var("GITLAB_CI").is_ok()
        || std::env::var("CIRCLECI").is_ok()
        || std::env::var("JENKINS_HOME").is_ok()
}