Skip to main content

mecha10_cli_core/
paths.rs

1//! Centralized path definitions for the CLI
2//!
3//! All hardcoded paths should be defined here to ensure consistency across the codebase.
4
5#![allow(dead_code)]
6
7/// Project configuration file
8pub const PROJECT_CONFIG: &str = "mecha10.json";
9
10/// Project directories
11pub mod project {
12    /// Node source code directory
13    pub const NODES_DIR: &str = "nodes";
14
15    /// Framework node (`@mecha10` scope) schema directory, under the project's `nodes/`
16    /// directory. This is where a framework node's `<name>.schema.json` lives.
17    pub const NODES_MECHA10_DIR: &str = "nodes/@mecha10";
18
19    /// The framework node's schema *directory* (no `<name>.schema.json` suffix) under
20    /// `nodes/@mecha10/<node_name>`.
21    pub fn framework_node_schema_dir(node_name: &str) -> String {
22        format!("{}/{}", NODES_MECHA10_DIR, node_name)
23    }
24
25    /// Driver source code directory
26    pub const DRIVERS_DIR: &str = "drivers";
27
28    /// Types directory
29    pub const TYPES_DIR: &str = "types";
30
31    /// Behavior trees directory - nested under `configs/` (LAB-2072) so `mecha10 config
32    /// push`/`pull`/`list` genuinely sync it like any other config, instead of living as a
33    /// sibling top-level directory `collect_configs_from_dir` never walked.
34    pub const BEHAVIORS_DIR: &str = "configs/behaviors";
35
36    /// Models directory (ONNX models, etc.)
37    pub const MODELS_DIR: &str = "models";
38
39    /// Model catalog subdirectory, bind-mounted into the `ollama` Compose service as
40    /// `/root/.ollama/models` (see `docker-compose.yml.template`).
41    pub const MODELS_CATALOG_DIR: &str = "models/catalog";
42
43    /// Logs directory
44    pub const LOGS_DIR: &str = "logs";
45
46    /// Simulation directory - nested under `configs/` (moved from a top-level `simulation/`
47    /// sibling) so `mecha10 config push`/`pull` syncs it like any other config, the same reason
48    /// `BEHAVIORS_DIR` moved under `configs/` in LAB-2072.
49    pub const SIMULATION_DIR: &str = "configs/simulation";
50
51    /// Simulation models directory
52    pub const SIMULATION_MODELS_DIR: &str = "configs/simulation/models";
53
54    /// Simulation environments directory
55    pub const SIMULATION_ENVIRONMENTS_DIR: &str = "configs/simulation/environments";
56
57    /// Simulation billboard-image assets directory (`type: "image"` `environment.json`/
58    /// `task.json` objects' `source` fields point here) - flat, no per-environment nesting.
59    pub const SIMULATION_IMAGES_DIR: &str = "configs/simulation/images";
60
61    /// RL task-curriculum configs directory, scaffolded from the templates package's bundled
62    /// catalog at `mecha10 init` time. `mecha10-rl`'s `AssetResolver` resolves task configs
63    /// (e.g. `task1`) from here for training (`mecha10 train`).
64    pub const RL_TASKS_DIR: &str = "configs/rl/tasks";
65
66    /// Simulation output directory (generated robot/scene files)
67    pub const SIMULATION_OUTPUT_DIR: &str = "configs/simulation/output";
68
69    /// Cargo build target directory
70    pub const TARGET_DIR: &str = "target";
71
72    /// Source directory
73    pub const SRC_DIR: &str = "src";
74
75    /// Local (gitignored) project-scoped state directory - mirrors the `~/.mecha10`
76    /// user-home convention (`user::MECHA10_DIR`) but scoped to this project checkout.
77    pub const STATE_DIR: &str = ".mecha10";
78
79    /// Cache file for `mecha10 dev`'s project-level Python dependency preflight gate.
80    pub const DEV_PREFLIGHT_CACHE_FILE: &str = ".mecha10/dev-preflight-cache.json";
81
82    /// Project-local persisted copy of the `mecha10-assets` extraction, written once at
83    /// `mecha10 init` time and reused by every later command instead of re-downloading.
84    pub const ASSETS_CACHE_DIR: &str = ".mecha10/assets";
85}
86
87/// Configuration paths within project
88pub mod config {
89    use super::project;
90
91    /// Base configs directory
92    pub const DIR: &str = "configs";
93
94    /// Node configs base directory
95    pub const NODES_DIR: &str = "configs/nodes";
96
97    /// Framework node configs (@mecha10 scope)
98    pub const NODES_MECHA10_DIR: &str = "configs/nodes/@mecha10";
99
100    /// Framework-tier (`@mecha10`) `config.json` path for `name` under `category_dir`.
101    fn framework_config(category_dir: &str, name: &str) -> String {
102        format!("{category_dir}/@mecha10/{name}/config.json")
103    }
104
105    /// Project-tier (plain name) `config.json` path for `name` under `category_dir`.
106    fn project_config(category_dir: &str, name: &str) -> String {
107        format!("{category_dir}/{name}/config.json")
108    }
109
110    /// The 2-tier `config.json` lookup candidates for `name` under `category_dir`, in canonical
111    /// resolution order: framework (`@mecha10`) -> project (plain name).
112    fn config_candidates(category_dir: &str, name: &str) -> [String; 2] {
113        [framework_config(category_dir, name), project_config(category_dir, name)]
114    }
115
116    /// Get config path for a framework node
117    pub fn framework_node(node_name: &str) -> String {
118        framework_config(NODES_DIR, node_name)
119    }
120
121    /// Get config path for a project node (plain name)
122    pub fn project_node(node_name: &str) -> String {
123        project_config(NODES_DIR, node_name)
124    }
125
126    /// Get the framework node's config *directory* (no `config.json` suffix) - the `@mecha10`
127    /// counterpart to [`framework_node`], for callers that need the directory itself (e.g. to
128    /// copy a whole config template tree into it) rather than the `config.json` file path.
129    pub fn framework_node_dir(node_name: &str) -> String {
130        format!("{}/{}", NODES_MECHA10_DIR, node_name)
131    }
132
133    /// The 2-tier `config.json` lookup candidates for a node, in canonical resolution order:
134    /// framework (`@mecha10`) -> project (plain name).
135    pub fn node_config_candidates(node_name: &str) -> [String; 2] {
136        config_candidates(NODES_DIR, node_name)
137    }
138
139    /// Get config path for a framework-default behavior (bundled into the project at scaffold
140    /// time under `configs/behaviors/@mecha10/<name>/config.json`).
141    pub fn framework_behavior(behavior_name: &str) -> String {
142        framework_config(project::BEHAVIORS_DIR, behavior_name)
143    }
144
145    /// The framework behavior's directory (no `config.json` suffix) - the `@mecha10`
146    /// counterpart to [`framework_behavior`].
147    pub fn framework_behavior_dir(behavior_name: &str) -> String {
148        format!("{}/@mecha10/{}", project::BEHAVIORS_DIR, behavior_name)
149    }
150
151    /// Get config path for a project behavior (plain name:
152    /// `configs/behaviors/<name>/config.json`).
153    pub fn project_behavior(behavior_name: &str) -> String {
154        project_config(project::BEHAVIORS_DIR, behavior_name)
155    }
156
157    /// The 2-tier `config.json` lookup candidates for a behavior, in override-precedence order
158    /// (highest first): project (plain name) -> framework (`@mecha10`).
159    pub fn behavior_config_candidates(behavior_name: &str) -> [String; 2] {
160        [project_behavior(behavior_name), framework_behavior(behavior_name)]
161    }
162}
163
164/// Docker-related paths within project
165pub mod docker {
166    /// Docker directory
167    pub const DIR: &str = "docker";
168
169    /// Main docker-compose file
170    pub const COMPOSE_FILE: &str = "docker/docker-compose.yml";
171
172    /// Remote nodes docker-compose file
173    pub const COMPOSE_REMOTE_FILE: &str = "docker/docker-compose.remote.yml";
174
175    /// Remote nodes Dockerfile
176    pub const DOCKERFILE_REMOTE: &str = "docker/Dockerfile.remote";
177
178    /// Remote container entrypoint script (execs mecha10-launcher)
179    pub const ENTRYPOINT_REMOTE: &str = "docker/entrypoint.sh";
180
181    /// rl target docker-compose file - runs a trained RL policy in production
182    pub const COMPOSE_RL_FILE: &str = "docker/docker-compose.rl.yml";
183
184    /// rl target Dockerfile
185    pub const DOCKERFILE_RL: &str = "docker/Dockerfile.rl";
186
187    /// rl target container entrypoint script (execs mecha10-launcher --target rl) - a distinct
188    /// filename from `ENTRYPOINT_REMOTE` since both `docker/entrypoint.sh` and this file coexist
189    /// in the same project (remote and rl are independent, both-scaffolded targets).
190    pub const ENTRYPOINT_RL: &str = "docker/entrypoint-rl.sh";
191}
192
193/// Environment files
194pub mod env {
195    /// Environment example file
196    pub const EXAMPLE: &str = ".env.example";
197
198    /// Environment file
199    pub const FILE: &str = ".env";
200}
201
202/// Meta files (README, gitignore, etc.)
203pub mod meta {
204    /// README file
205    pub const README: &str = "README.md";
206
207    /// Git ignore file
208    pub const GITIGNORE: &str = ".gitignore";
209
210    /// Package.json for Node.js tooling
211    pub const PACKAGE_JSON: &str = "package.json";
212
213    /// Python requirements
214    pub const REQUIREMENTS_TXT: &str = "requirements.txt";
215
216    /// Pinned Python version for `mecha10 setup` to target (see
217    /// `find_python_executable` in `packages/cli/src/handlers/setup.rs`).
218    pub const PYTHON_VERSION: &str = ".python-version";
219}
220
221/// Rust project files
222pub mod rust {
223    /// Cargo workspace manifest
224    pub const CARGO_TOML: &str = "Cargo.toml";
225
226    /// Cargo lock file
227    pub const CARGO_LOCK: &str = "Cargo.lock";
228
229    /// Main entry point
230    pub const MAIN_RS: &str = "src/main.rs";
231
232    /// Library entry point
233    pub const LIB_RS: &str = "src/lib.rs";
234
235    /// Build script
236    pub const BUILD_RS: &str = "build.rs";
237
238    /// Rustfmt config
239    pub const RUSTFMT_TOML: &str = "rustfmt.toml";
240}
241
242/// Model files within a model directory
243pub mod model {
244    /// ONNX model file
245    pub const ONNX_FILE: &str = "model.onnx";
246
247    /// Labels file
248    pub const LABELS_FILE: &str = "labels.txt";
249
250    /// Model config file
251    pub const CONFIG_FILE: &str = "config.json";
252}
253
254/// User-level paths in home directory
255pub mod user {
256    use std::path::PathBuf;
257
258    /// Base mecha10 directory in user home.
259    ///
260    /// Re-exports `mecha10_core::fs_utils::MECHA10_DIR`, shared with `launcher-service`.
261    pub const MECHA10_DIR: &str = mecha10_core::fs_utils::MECHA10_DIR;
262
263    /// Credentials file, relative to the user home directory.
264    ///
265    /// Documentation-only - `credentials_file()` below is the actual source of truth.
266    pub const CREDENTIALS_FILE: &str = ".mecha10/credentials.json";
267
268    /// Templates cache directory
269    pub const TEMPLATES_DIR: &str = ".mecha10/templates";
270
271    /// Binary installation directory
272    pub const BIN_DIR: &str = ".mecha10/bin";
273
274    /// Get the base mecha10 directory path
275    pub fn mecha10_dir() -> PathBuf {
276        dirs::home_dir().unwrap_or_else(|| PathBuf::from(".")).join(MECHA10_DIR)
277    }
278
279    /// Get the credentials file path.
280    ///
281    /// Delegates to `mecha10-auth`'s `credentials::default_credentials_path()`.
282    pub fn credentials_file() -> PathBuf {
283        mecha10_auth::default_credentials_path()
284    }
285
286    /// Get the templates cache directory
287    pub fn templates_dir() -> PathBuf {
288        mecha10_dir().join("templates")
289    }
290
291    /// Get the binary directory
292    pub fn bin_dir() -> PathBuf {
293        mecha10_dir().join("bin")
294    }
295
296    /// Get path to a binary in the mecha10 bin directory
297    pub fn bin(name: &str) -> PathBuf {
298        bin_dir().join(name)
299    }
300
301    /// Get path to a binary in cargo bin directory
302    pub fn cargo_bin(name: &str) -> PathBuf {
303        home_bin_dir(".cargo", name)
304    }
305
306    /// Get path to a binary in local bin directory
307    pub fn local_bin(name: &str) -> PathBuf {
308        home_bin_dir(".local", name)
309    }
310
311    /// Get path to a binary in a `bin` subdirectory of the given home-relative directory
312    /// (e.g. `~/.cargo/bin/{name}`, `~/.local/bin/{name}`).
313    fn home_bin_dir(home_subdir: &str, name: &str) -> PathBuf {
314        mecha10_core::fs_utils::home_subpath(&[home_subdir, "bin", name])
315    }
316}
317
318/// Paths used inside Docker containers
319pub mod container {
320    /// Project mount point in container
321    pub const PROJECT_ROOT: &str = "/project";
322
323    /// Framework mount point in container
324    pub const FRAMEWORK_ROOT: &str = "/mecha10";
325
326    /// App directory (for mecha10-remote)
327    pub const APP_ROOT: &str = "/app";
328
329    /// Config file in mecha10-remote container
330    pub const REMOTE_CONFIG: &str = "/app/mecha10.json";
331
332    /// Get project-relative path inside container
333    pub fn project_path(relative: &str) -> String {
334        format!("{}/{}", PROJECT_ROOT, relative)
335    }
336
337    /// Get framework-relative path inside container
338    pub fn framework_path(relative: &str) -> String {
339        format!("{}/{}", FRAMEWORK_ROOT, relative)
340    }
341}
342
343/// Paths within the mecha10 framework source
344pub mod framework {
345    /// Packages directory
346    pub const PACKAGES_DIR: &str = "packages";
347
348    /// Nodes package directory
349    pub const NODES_DIR: &str = "packages/nodes";
350
351    /// Drivers package directory
352    pub const DRIVERS_DIR: &str = "packages/drivers";
353
354    /// Marker directory used to detect the mecha10 framework root
355    pub const ROOT_MARKER_DIR: &str = "packages/core";
356
357    /// Release binary
358    pub const RELEASE_BINARY: &str = "target/release/mecha10";
359
360    /// Debug binary
361    pub const DEBUG_BINARY: &str = "target/debug/mecha10";
362
363    /// Get node config path within framework
364    pub fn node_config(node_name: &str) -> String {
365        format!("packages/nodes/{}/configs/config.json", node_name)
366    }
367}
368
369/// External service URLs
370pub mod urls {
371    /// Default base URL for the public `mecha10-api` service. All framework/runtime artifact
372    /// downloads are proxied through its `/api/downloads/*` routes.
373    pub const MECHA10_API_URL: &str = "https://mecha.industries/api";
374
375    /// Build the `mecha10-api` base URL (e.g. `https://mecha.industries/api`).
376    ///
377    /// Override at runtime with the `MECHA10_API_URL` env var.
378    pub fn mecha10_api_base_url() -> String {
379        std::env::var("MECHA10_API_URL")
380            .unwrap_or_else(|_| MECHA10_API_URL.to_string())
381            .trim_end_matches('/')
382            .to_string()
383    }
384
385    /// Join `path` onto [`mecha10_api_base_url`]. `path` must not start with a leading
386    /// `/api` of its own, or the request doubles up to `.../api/api/...` and 404s.
387    pub fn mecha10_api_path(path: &str) -> String {
388        format!("{}/{}", mecha10_api_base_url(), path.trim_start_matches('/'))
389    }
390
391    /// Default authentication URL
392    pub const AUTH_URL: &str = "https://mecha.industries/api/auth";
393}
394
395/// Build a target output path
396pub fn target_path(profile: &str, binary: &str) -> String {
397    format!("target/{}/{}", profile, binary)
398}
399
400/// Build a target output path with optional target triple
401pub fn target_path_with_triple(target: Option<&str>, profile: &str) -> String {
402    match target {
403        Some(t) => format!("target/{}/{}", t, profile),
404        None => format!("target/{}", profile),
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    #[test]
413    fn credentials_file_matches_mecha10_auth_source_of_truth() {
414        assert_eq!(user::credentials_file(), mecha10_auth::default_credentials_path());
415    }
416
417    /// `cargo_bin`/`local_bin` share a `home_bin_dir` helper that only differs on which
418    /// home-relative directory it joins.
419    #[test]
420    fn cargo_bin_and_local_bin_join_name_under_their_own_home_subdir() {
421        let home = dirs::home_dir().expect("home dir must resolve in test environment");
422        assert_eq!(
423            user::cargo_bin("mecha10"),
424            home.join(".cargo").join("bin").join("mecha10")
425        );
426        assert_eq!(
427            user::local_bin("mecha10"),
428            home.join(".local").join("bin").join("mecha10")
429        );
430    }
431
432    #[test]
433    fn simulation_project_dirs_share_the_simulation_root() {
434        assert_eq!(project::SIMULATION_MODELS_DIR, "configs/simulation/models");
435        assert_eq!(project::SIMULATION_ENVIRONMENTS_DIR, "configs/simulation/environments");
436        for dir in [project::SIMULATION_MODELS_DIR, project::SIMULATION_ENVIRONMENTS_DIR] {
437            assert!(dir.starts_with(&format!("{}/", project::SIMULATION_DIR)));
438        }
439    }
440
441    /// Task-curriculum configs live under `configs/rl/`, NOT `SIMULATION_DIR` - they're a
442    /// project's RL configuration, not a physics/rendering asset.
443    #[test]
444    fn rl_tasks_dir_lives_under_configs_rl_not_simulation() {
445        assert_eq!(project::RL_TASKS_DIR, "configs/rl/tasks");
446        assert!(!project::RL_TASKS_DIR.starts_with(&format!("{}/", project::SIMULATION_DIR)));
447    }
448
449    #[test]
450    fn test_config_paths() {
451        assert_eq!(
452            config::framework_node("object-detector"),
453            "configs/nodes/@mecha10/object-detector/config.json"
454        );
455        assert_eq!(config::project_node("camera"), "configs/nodes/camera/config.json");
456    }
457
458    #[test]
459    fn test_framework_node_dir() {
460        assert_eq!(config::framework_node_dir("speaker"), "configs/nodes/@mecha10/speaker");
461    }
462
463    #[test]
464    fn test_framework_node_schema_dir_lives_under_nodes_not_configs_nodes() {
465        assert_eq!(project::framework_node_schema_dir("speaker"), "nodes/@mecha10/speaker");
466        assert_ne!(
467            project::framework_node_schema_dir("speaker"),
468            config::framework_node_dir("speaker"),
469            "schema dir (wave 10) must not collide with the config.json dir"
470        );
471    }
472
473    #[test]
474    fn test_node_config_candidates_order() {
475        assert_eq!(
476            config::node_config_candidates("teleop"),
477            [
478                "configs/nodes/@mecha10/teleop/config.json".to_string(),
479                "configs/nodes/teleop/config.json".to_string(),
480            ]
481        );
482    }
483
484    #[test]
485    fn test_behavior_config_paths() {
486        assert_eq!(
487            config::framework_behavior("idle_wander"),
488            "configs/behaviors/@mecha10/idle_wander/config.json"
489        );
490        assert_eq!(
491            config::project_behavior("idle_wander"),
492            "configs/behaviors/idle_wander/config.json"
493        );
494    }
495
496    #[test]
497    fn test_framework_behavior_dir() {
498        assert_eq!(
499            config::framework_behavior_dir("idle_wander"),
500            "configs/behaviors/@mecha10/idle_wander"
501        );
502        assert_eq!(
503            config::framework_behavior("idle_wander"),
504            format!("{}/config.json", config::framework_behavior_dir("idle_wander"))
505        );
506    }
507
508    #[test]
509    fn test_behavior_config_candidates_order() {
510        assert_eq!(
511            config::behavior_config_candidates("idle_wander"),
512            [
513                "configs/behaviors/idle_wander/config.json".to_string(),
514                "configs/behaviors/@mecha10/idle_wander/config.json".to_string(),
515            ]
516        );
517    }
518
519    #[test]
520    fn test_target_path() {
521        assert_eq!(target_path("release", "my-node"), "target/release/my-node");
522        assert_eq!(
523            target_path_with_triple(Some("aarch64-unknown-linux-gnu"), "release"),
524            "target/aarch64-unknown-linux-gnu/release"
525        );
526        assert_eq!(target_path_with_triple(None, "debug"), "target/debug");
527    }
528
529    #[test]
530    fn test_container_paths() {
531        assert_eq!(
532            container::project_path("configs/test.json"),
533            "/project/configs/test.json"
534        );
535        assert_eq!(container::framework_path("packages/core"), "/mecha10/packages/core");
536    }
537
538    #[test]
539    fn test_mecha10_api_base_url_default() {
540        let _guard = ENV_MUTEX.lock().unwrap();
541        std::env::remove_var("MECHA10_API_URL");
542        assert_eq!(urls::mecha10_api_base_url(), "https://mecha.industries/api");
543    }
544
545    #[test]
546    fn test_mecha10_api_base_url_env_override() {
547        let _guard = ENV_MUTEX.lock().unwrap();
548        std::env::set_var("MECHA10_API_URL", "http://localhost:4000/api/");
549        assert_eq!(urls::mecha10_api_base_url(), "http://localhost:4000/api");
550        std::env::remove_var("MECHA10_API_URL");
551    }
552
553    #[test]
554    fn test_mecha10_api_path_does_not_double_the_api_segment() {
555        let _guard = ENV_MUTEX.lock().unwrap();
556        std::env::remove_var("MECHA10_API_URL");
557        assert_eq!(
558            urls::mecha10_api_path("/models/catalog"),
559            "https://mecha.industries/api/models/catalog"
560        );
561    }
562
563    #[test]
564    fn test_mecha10_api_path_works_without_a_leading_slash() {
565        let _guard = ENV_MUTEX.lock().unwrap();
566        std::env::remove_var("MECHA10_API_URL");
567        assert_eq!(
568            urls::mecha10_api_path("downloads/model/deepghs/yolos/yolov8n/model.onnx"),
569            "https://mecha.industries/api/downloads/model/deepghs/yolos/yolov8n/model.onnx"
570        );
571    }
572
573    /// Serializes tests that mutate process-wide env vars, since `cargo test` runs
574    /// tests in this module concurrently by default.
575    static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
576}