mecha10-cli 0.6.5

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
//! Config Edit picker TUI with ratatui
//!
//! Backs `mecha10 config edit`: a single-panel scrollable list of every editable config
//! this project knows about (node configs, behavior configs, RL job configs, the
//! `configs/simulation/` config, `mecha10.json`, and `simulation/` assets), followed by
//! opening the selected file in `$EDITOR`.
//!
//! The catalog of editable entries is built by [`discover_editable_configs`], a pure
//! function over the filesystem with no TUI/terminal dependency, so it's unit-testable
//! without a real terminal - see the `#[cfg(test)]` module at the bottom of this file.
//! Drawing/input handling ([`ConfigEditTui`]) is a thin, separate layer on top, mirroring
//! the split already used by `TopicsListTui`/`DiagnosticsTui` in this module.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use mecha10_core::enum_str_method;
use ratatui::{
    style::{Color, Modifier, Style},
    widgets::{Block, Borders, List, ListItem, ListState},
    Frame,
};
use std::path::{Path, PathBuf};

use super::tui_layout::{render_footer_hints, standard_tui_layout};

/// Category of an [`EditableConfigEntry`], used for both grouping and the short tag shown
/// next to its label in the picker (e.g. `[node]`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditableConfigCategory {
    /// A node config under `configs/nodes/...`.
    Node,
    /// A behavior config under `configs/behaviors/...`.
    Behavior,
    /// An RL job definition under `configs/rl/jobs/*.yml`.
    RlJob,
    /// The simulation *config* at `configs/simulation/config.json` - distinct from a
    /// simulation *asset* (see [`EditableConfigCategory::SimulationAsset`]).
    SimulationConfig,
    /// The project's `mecha10.json`.
    ProjectConfig,
    /// A simulation asset (model/environment/task) under the project's `./simulation/`
    /// directory - distinct from the simulation *config* under `configs/simulation/`.
    SimulationAsset,
}

enum_str_method!(
    fn tag(EditableConfigCategory) -> &str {
        Node => "[node]",
        Behavior => "[behavior]",
        RlJob => "[rl-job]",
        SimulationConfig => "[config]",
        ProjectConfig => "[project]",
        SimulationAsset => "[asset]",
    }
);

/// One editable config discovered by [`discover_editable_configs`]: a human-friendly label,
/// its category, and the file to open in `$EDITOR` on selection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EditableConfigEntry {
    pub label: String,
    pub category: EditableConfigCategory,
    pub path: PathBuf,
}

/// Canonical asset file name for each `simulation/<subdir>/<name>/` asset directory - mirrors
/// `mecha10_cli_core::paths::project::model_config`/`environment_config`, extended with the
/// `tasks/` shape (`simulation/tasks/<name>/task.json`, see `packages/simulation/tasks/*` for
/// the on-disk convention), which has no equivalent `paths.rs` helper today.
const SIMULATION_ASSET_SUBDIRS: [(&str, &str); 3] = [
    ("models", "model.json"),
    ("environments", "environment.json"),
    ("tasks", "task.json"),
];

/// Discover every editable config in a mecha10 project, labeled and categorized for display
/// in the `mecha10 config edit` picker. Pure function over the filesystem - no TUI/terminal
/// dependency - so it's directly unit-testable (see tests below).
///
/// `project_root` is the project root (the directory containing `mecha10.json`).
pub fn discover_editable_configs(project_root: &Path) -> Vec<EditableConfigEntry> {
    let mut entries = Vec::new();

    let configs_dir = project_root.join(crate::paths::config::DIR);

    entries.extend(discover_two_tier_category(
        &configs_dir.join("nodes"),
        EditableConfigCategory::Node,
    ));
    entries.extend(discover_two_tier_category(
        &configs_dir.join("behaviors"),
        EditableConfigCategory::Behavior,
    ));

    let simulation_config = project_root.join(crate::paths::config::SIMULATION_CONFIG);
    if simulation_config.is_file() {
        entries.push(EditableConfigEntry {
            label: "Simulation config".to_string(),
            category: EditableConfigCategory::SimulationConfig,
            path: simulation_config,
        });
    }

    entries.extend(discover_rl_jobs(project_root));

    let mecha10_json = project_root.join(crate::paths::PROJECT_CONFIG);
    if mecha10_json.is_file() {
        entries.push(EditableConfigEntry {
            label: "mecha10.json (project config)".to_string(),
            category: EditableConfigCategory::ProjectConfig,
            path: mecha10_json,
        });
    }

    entries.extend(discover_simulation_assets(project_root));

    entries
}

/// Discover configs under a 2-tier category root (`configs/nodes` or `configs/behaviors`):
/// `<root>/@scope/name/config.json` -> label `@scope/name`, and `<root>/name/config.json` ->
/// label `name`. Mirrors `mecha10_robot_config::sync::derive_config_key`'s shape for these two
/// categories, but stays local (sync, no `ConfigValue` parsing) since this module only needs
/// paths + labels, not config contents.
fn discover_two_tier_category(category_dir: &Path, category: EditableConfigCategory) -> Vec<EditableConfigEntry> {
    let mut out = Vec::new();
    let mut config_jsons = Vec::new();
    collect_config_jsons(category_dir, &mut config_jsons);
    config_jsons.sort();

    for path in config_jsons {
        let Ok(relative) = path.strip_prefix(category_dir) else {
            continue;
        };
        let components: Vec<&str> = relative.components().filter_map(|c| c.as_os_str().to_str()).collect();

        let label = match components.as_slice() {
            [scope, name, "config.json"] if scope.starts_with('@') => format!("{scope}/{name}"),
            [name, "config.json"] => name.to_string(),
            _ => continue,
        };

        out.push(EditableConfigEntry { label, category, path });
    }

    out
}

/// Recursively collect every `config.json` file under `dir` (no-op if `dir` doesn't exist).
fn collect_config_jsons(dir: &Path, out: &mut Vec<PathBuf>) {
    let Ok(read_dir) = std::fs::read_dir(dir) else {
        return;
    };

    for entry in read_dir.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_config_jsons(&path, out);
        } else if path.file_name().and_then(|n| n.to_str()) == Some("config.json") {
            out.push(path);
        }
    }
}

/// Discover RL job definitions under `configs/rl/jobs/*.yml`, reusing
/// `services::train_jobs::load_job_catalog` (the same catalog `mecha10 train` uses) so the
/// picker's job list/naming never drifts from what `mecha10 train` would offer. Malformed job
/// YAML is treated as "no RL jobs" here rather than failing the whole picker - `mecha10 train`
/// is the authoritative place to surface a parse error.
fn discover_rl_jobs(project_root: &Path) -> Vec<EditableConfigEntry> {
    crate::services::train_jobs::load_job_catalog(project_root)
        .unwrap_or_default()
        .into_iter()
        .map(|job| EditableConfigEntry {
            label: job.name,
            category: EditableConfigCategory::RlJob,
            path: job.source_path,
        })
        .collect()
}

/// Discover simulation assets under the project's `./configs/simulation/{models,environments,tasks}/`
/// directories (see `docs/architecture/CONFIGURATION.md#simulation-assets`, synced generically by
/// `mecha10 config push`/`pull` since LAB-2936). Each named subdirectory (e.g.
/// `configs/simulation/models/rover/`) becomes one entry, pointed at its canonical config file
/// (`model.json`/`environment.json`/`task.json`) when present.
fn discover_simulation_assets(project_root: &Path) -> Vec<EditableConfigEntry> {
    let mut out = Vec::new();
    let simulation_dir = project_root.join(crate::paths::project::SIMULATION_DIR);

    for (subdir, asset_file) in SIMULATION_ASSET_SUBDIRS {
        let subdir_path = simulation_dir.join(subdir);
        let Ok(read_dir) = std::fs::read_dir(&subdir_path) else {
            continue;
        };

        let mut names: Vec<String> = read_dir
            .flatten()
            .filter(|entry| entry.path().is_dir())
            .filter_map(|entry| entry.file_name().to_str().map(|s| s.to_string()))
            .collect();
        names.sort();

        for name in names {
            let config_path = subdir_path.join(&name).join(asset_file);
            if !config_path.is_file() {
                continue;
            }

            out.push(EditableConfigEntry {
                label: name,
                category: EditableConfigCategory::SimulationAsset,
                path: config_path,
            });
        }
    }

    out
}

/// Outcome of the picker: either the user selected an entry to edit, or cancelled.
pub enum ConfigEditOutcome {
    /// User pressed Enter on an entry - open this file in `$EDITOR`.
    Selected(PathBuf),
    /// User pressed Esc/q - do nothing.
    Cancelled,
}

/// TUI for the `mecha10 config edit` picker: a single scrollable list of
/// [`EditableConfigEntry`] items.
pub struct ConfigEditTui {
    entries: Vec<EditableConfigEntry>,
    selected_index: usize,
    should_quit: bool,
    outcome: Option<ConfigEditOutcome>,
}

impl ConfigEditTui {
    mecha10_core::new_with_defaults!(
        /// Create a new picker over `entries` (must be non-empty - callers check
        /// `discover_editable_configs` isn't empty before constructing this).
        pub fn new(entries: Vec<EditableConfigEntry>) -> Self {
            selected_index: 0,
            should_quit: false,
            outcome: None
        }
    );

    /// Check if should quit
    pub fn should_quit(&self) -> bool {
        self.should_quit
    }

    /// Take the final outcome (selection or cancellation). `None` until `should_quit()` is
    /// true.
    pub fn take_outcome(&mut self) -> Option<ConfigEditOutcome> {
        self.outcome.take()
    }

    /// Draw the TUI (single frame)
    pub fn draw(&mut self, f: &mut Frame) {
        let (content_area, footer_area) = standard_tui_layout(f.area());

        let items: Vec<ListItem> = self
            .entries
            .iter()
            .enumerate()
            .map(|(i, entry)| {
                let is_selected = i == self.selected_index;
                let style = if is_selected {
                    Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(Color::White)
                };

                let prefix = if is_selected { "â–¶ " } else { "  " };
                let formatted = format!("{}{} {}", prefix, entry.label, entry.category.tag());
                ListItem::new(formatted).style(style)
            })
            .collect();

        let title = format!(" Editable configs ({}) ", self.entries.len());
        let list = List::new(items).block(
            Block::default()
                .borders(Borders::ALL)
                .title(title)
                .border_style(Style::default().fg(Color::Cyan)),
        );

        let mut state = ListState::default();
        state.select(Some(self.selected_index));

        f.render_stateful_widget(list, content_area, &mut state);

        render_footer_hints(
            f,
            footer_area,
            &[
                ("↑/↓", "Navigate", Color::Cyan),
                ("Enter", "Edit", Color::Green),
                ("Q/ESC", "Cancel", Color::Red),
            ],
        );
    }

    /// Handle keyboard input
    pub fn handle_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Char('q') | KeyCode::Esc => {
                self.outcome = Some(ConfigEditOutcome::Cancelled);
                self.should_quit = true;
            }
            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.outcome = Some(ConfigEditOutcome::Cancelled);
                self.should_quit = true;
            }
            KeyCode::Up => {
                if self.selected_index > 0 {
                    self.selected_index -= 1;
                }
            }
            KeyCode::Down => {
                if self.selected_index < self.entries.len().saturating_sub(1) {
                    self.selected_index += 1;
                }
            }
            KeyCode::Enter => {
                if let Some(entry) = self.entries.get(self.selected_index) {
                    self.outcome = Some(ConfigEditOutcome::Selected(entry.path.clone()));
                    self.should_quit = true;
                }
            }
            _ => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn write_file(path: &Path, contents: &str) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(path, contents).unwrap();
    }

    #[test]
    fn discovers_framework_and_project_node_configs() {
        let dir = tempdir().unwrap();
        write_file(&dir.path().join("configs/nodes/@mecha10/motor/config.json"), "{}");
        write_file(&dir.path().join("configs/nodes/camera/config.json"), "{}");

        let entries = discover_editable_configs(dir.path());
        let nodes: Vec<&EditableConfigEntry> = entries
            .iter()
            .filter(|e| e.category == EditableConfigCategory::Node)
            .collect();

        assert_eq!(nodes.len(), 2);
        assert!(nodes.iter().any(|e| e.label == "@mecha10/motor"));
        assert!(nodes.iter().any(|e| e.label == "camera"));
    }

    #[test]
    fn discovers_framework_and_project_behavior_configs() {
        let dir = tempdir().unwrap();
        write_file(
            &dir.path().join("configs/behaviors/@mecha10/idle_wander/config.json"),
            "{}",
        );
        write_file(&dir.path().join("configs/behaviors/patrol/config.json"), "{}");

        let entries = discover_editable_configs(dir.path());
        let behaviors: Vec<&EditableConfigEntry> = entries
            .iter()
            .filter(|e| e.category == EditableConfigCategory::Behavior)
            .collect();

        assert_eq!(behaviors.len(), 2);
        assert!(behaviors.iter().any(|e| e.label == "@mecha10/idle_wander"));
        assert!(behaviors.iter().any(|e| e.label == "patrol"));
    }

    #[test]
    fn discovers_rl_job_configs() {
        let dir = tempdir().unwrap();
        write_file(
            &dir.path().join("configs/rl/jobs/train.yml"),
            "name: train\nflow_type: train\nconfig: local\n",
        );

        let entries = discover_editable_configs(dir.path());
        let jobs: Vec<&EditableConfigEntry> = entries
            .iter()
            .filter(|e| e.category == EditableConfigCategory::RlJob)
            .collect();

        assert_eq!(jobs.len(), 1);
        assert_eq!(jobs[0].label, "train");
        assert_eq!(jobs[0].path, dir.path().join("configs/rl/jobs/train.yml"));
    }

    #[test]
    fn discovers_simulation_config_distinct_from_assets() {
        let dir = tempdir().unwrap();
        write_file(&dir.path().join("configs/simulation/config.json"), "{}");

        let entries = discover_editable_configs(dir.path());
        let sim_configs: Vec<&EditableConfigEntry> = entries
            .iter()
            .filter(|e| e.category == EditableConfigCategory::SimulationConfig)
            .collect();

        assert_eq!(sim_configs.len(), 1);
        assert_eq!(sim_configs[0].label, "Simulation config");
    }

    #[test]
    fn includes_mecha10_json_as_project_config() {
        let dir = tempdir().unwrap();
        write_file(
            &dir.path().join("mecha10.json"),
            r#"{"name": "proj", "version": "0.1.0", "robot_id": "r"}"#,
        );

        let entries = discover_editable_configs(dir.path());
        let project: Vec<&EditableConfigEntry> = entries
            .iter()
            .filter(|e| e.category == EditableConfigCategory::ProjectConfig)
            .collect();

        assert_eq!(project.len(), 1);
        assert_eq!(project[0].label, "mecha10.json (project config)");
        assert_eq!(project[0].path, dir.path().join("mecha10.json"));
    }

    #[test]
    fn discovers_simulation_assets_across_models_environments_and_tasks() {
        let dir = tempdir().unwrap();
        write_file(&dir.path().join("configs/simulation/models/rover/model.json"), "{}");
        write_file(
            &dir.path()
                .join("configs/simulation/environments/basic_arena/environment.json"),
            "{}",
        );
        write_file(&dir.path().join("configs/simulation/tasks/task1/task.json"), "{}");

        let entries = discover_editable_configs(dir.path());
        let assets: Vec<&EditableConfigEntry> = entries
            .iter()
            .filter(|e| e.category == EditableConfigCategory::SimulationAsset)
            .collect();

        assert_eq!(assets.len(), 3);
        assert!(assets.iter().any(|e| e.label == "rover"));
        assert!(assets.iter().any(|e| e.label == "basic_arena"));
        assert!(assets.iter().any(|e| e.label == "task1"));
    }

    #[test]
    fn simulation_asset_directory_without_canonical_file_is_skipped() {
        let dir = tempdir().unwrap();
        write_file(&dir.path().join("configs/simulation/models/broken/readme.txt"), "n/a");

        let entries = discover_editable_configs(dir.path());
        assert!(entries
            .iter()
            .all(|e| e.category != EditableConfigCategory::SimulationAsset));
    }

    #[test]
    fn returns_empty_when_nothing_editable_exists() {
        let dir = tempdir().unwrap();
        let entries = discover_editable_configs(dir.path());
        assert!(entries.is_empty());
    }
}