mecha10-cli 0.1.21

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
# @mecha10/cli

Command-line interface for managing Mecha10 robot projects.

## Features

- **Project Scaffolding** - `init` command with templates
-**Development Mode** - `dev` with hot-reload and runtime integration
-**Production Mode** - `run` for deployment
-**Build System** - `build` with cross-compilation support
-**Simulation** - `sim` for Godot environment generation
-**Topology** - `topology` for static analysis of nodes, pub/sub topics, and ports
-**Topics** - `topics` for message introspection and real-time monitoring
-**Deployment** - `deploy` with canary/rolling strategies
-**Log Viewer** - `logs` for debugging
-**Status Display** - `status` for project overview
-**Cleanup** - `clean` for build artifacts
-**Quality Tools** - `quality`, `format`, `lint` commands
-**Library API** - Programmatic access to CLI functionality

## Status

✅ **Production-Ready** - 3-layer architecture, 392 tests passing, 70-75% coverage

## Architecture

The CLI follows a strict 3-layer architecture:

```
Commands (clap Args)     → Pure data structures
Handlers (orchestration) → Coordinate services, handle UI
Services (business logic)→ Reusable, testable logic
Mecha10 Core            → Message passing runtime
```

See [CLI_ARCHITECTURE.md](../../docs/architecture/CLI_ARCHITECTURE.md) for complete details.

## Installation

```bash
cd packages/cli
cargo install --path .
```

Verify installation:
```bash
mecha10 --version
```

## Commands

### `mecha10 init`

Initialize a new robot project:

```bash
# Interactive wizard (recommended)
mecha10 init

# Or with explicit parameters
mecha10 init my-robot --template rover
cd my-robot
```

**Interactive Mode:**

When you run `mecha10 init` without parameters, it launches an interactive wizard that prompts you for:

1. **Project name** - The name of your robot project
2. **Robot type** - Choose from:
   - `rover` - 4-wheeled mobile robot with sensors (camera, lidar, imu)
   - `humanoid` - Bipedal walking robot
   - `arm` - 6-DOF robotic arm manipulator
   - `basic` - Minimal starting template
3. **Simulation** - Whether to generate Godot RL simulation environments

**Example Interactive Session:**
```
🤖 Mecha10 Project Initialization Wizard

? Project name: my-rover
? What type of robot are you building?
  ❯ Rover - 4-wheeled mobile robot with sensors
    Humanoid - Bipedal walking robot
    Robotic Arm - 6-DOF manipulator
    Basic - Minimal starting template

? Generate simulation environments? Yes

📋 Configuration Summary:
  Project: my-rover
  Robot Type: rover
  Simulation: Yes
```

**Command-line Flags:**

You can also use command-line flags to skip the interactive prompts:

```bash
# Skip interactive mode with all parameters
mecha10 init my-robot --template rover

# Provide only the name, prompt for robot type
mecha10 init my-robot

# Provide only robot type, prompt for name
mecha10 init --template rover

# Skip simulation generation
mecha10 init --skip-sim
```

**Templates:**
- `basic` - Minimal project structure
- `rover` - Ground robot with navigation (camera, lidar, imu, motor controller)
- `arm` - Manipulation robot
- `humanoid` - Bipedal walker

**What it creates:**
```
my-robot/
├── .mecha10/          # Framework config
├── config/             # Robot configurations
├── nodes/              # Your node implementations
├── models/             # RL models (ONNX files)
├── environments/       # Simulation environments
├── tests/              # Integration tests
├── logs/               # Runtime logs
└── mecha10.json       # Project manifest
```

### `mecha10 dev`

Start development mode with hot-reload:

```bash
mecha10 dev
```

**Options:**
- `--env <ENV>` - Environment (dev, staging, production)
- `--config <PATH>` - Custom config path
- `--log-level <LEVEL>` - Log level (debug, info, warn, error)

**What it does:**
1. Load `.mecha10/config.json` and `mecha10.json`
2. Start all configured nodes
3. Monitor health and auto-restart on crash
4. Watch for config changes (hot-reload)
5. Run until Ctrl+C

### `mecha10 run`

Run in production mode:

```bash
mecha10 run --env production
```

**Options:**
- `--env <ENV>` - Environment (default: production)
- `--nodes <LIST>` - Specific nodes to run (comma-separated)
- `--config <PATH>` - Custom config path

**Example:**
```bash
# Run only camera and SLAM nodes
mecha10 run --nodes camera,slam
```

### `mecha10 build`

Build the project:

```bash
# Debug build
mecha10 build

# Release build (optimized)
mecha10 build --release

# Cross-compile for Raspberry Pi
mecha10 build --release --target aarch64-unknown-linux-gnu
```

**Options:**
- `--release` - Build with optimizations
- `--target <ARCH>` - Cross-compile target

### `mecha10 deploy`

Deploy to production:

```bash
mecha10 deploy --env production --strategy canary
```

**Options:**
- `--env <ENV>` - Environment (staging, production)
- `--strategy <STRATEGY>` - Deployment strategy (canary, rolling, blue-green)

**Strategies:**
- `canary` - Gradual rollout (10% → 50% → 100%)
- `rolling` - Node-by-node replacement
- `blue-green` - Instant switchover with rollback

**Note:** Requires platform API integration (stub implementation)

### `mecha10 train`

Submit a training job:

```bash
mecha10 train training/navigation-policy.yaml --wait
```

**Options:**
- `--wait` - Wait for job to complete

**Note:** Requires platform API integration (stub implementation)

### `mecha10 logs`

View node logs:

```bash
# All nodes
mecha10 logs

# Specific node
mecha10 logs camera

# Follow logs (tail -f)
mecha10 logs --follow
```

**Note:** Stub implementation

### `mecha10 status`

Show project status:

```bash
mecha10 status
```

**Output:**
```
Project Status:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Robot: my-robot
Platform: rover
Nodes: 3
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

### `mecha10 topology`

Static analysis of project topology - visualize nodes, pub/sub topics, and service ports:

```bash
# Show nodes and their topic connections
mecha10 topology

# Group by topics instead of nodes
mecha10 topology --group-by topics

# Export to JSON
mecha10 topology --format json > topology.json

# ASCII graph view
mecha10 topology --format graph
```

**Features:**
- No runtime required (static code analysis)
- Multiple views (nodes, topics, graph)
- Shows Redis and service ports
- Analyzes pub/sub relationships from source code

See [CLI Guide](../../docs/CLI_GUIDE.md#mecha10-topology) for complete documentation.

---

### `mecha10 topics`

Discover and monitor Redis stream topics:

```bash
# List all topics (interactive browser)
mecha10 topics list

# List topics matching a pattern
mecha10 topics list --pattern "sensor/*"

# Verbose output with topic details
mecha10 topics list --verbose
```

**Features:**
- Interactive terminal-based topic browser
- Real-time topic monitoring
- Keyboard navigation (↑/↓ arrows, Enter to select)
- Live message streaming from selected topics
- Pattern matching support

**Example Session:**
```
📋 Mecha10 Topics
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Scanning Redis for topics matching: *

Found 3 topic(s)

Use ↑/↓ arrows to navigate, Enter to select, Esc to exit

❯ sensor/camera
  sensor/lidar
  control/motor
```

### `mecha10 models`

Manage AI models from HuggingFace Hub:

```bash
# List available models from catalog
mecha10 models list

# Show only recommended models
mecha10 models list --recommended

# Download a model from catalog
mecha10 models pull mobilenet-v2

# Download all recommended models
mecha10 models pull --all

# Download custom model from HuggingFace
mecha10 models pull --repo user/model --file model.onnx --name my-model

# List installed models
mecha10 models installed

# Show model details
mecha10 models info mobilenet-v2

# Remove cached model
mecha10 models remove mobilenet-v2
```

**Features:**
- Curated catalog of robotics/vision models
- Automatic downloads from HuggingFace Hub
- **Automatic INT8 quantization** for 2x faster inference
- Dual caching (HF cache + project models/)
- Offline support after first download
- Model metadata (size, task, input format)

**Model Catalog:**
- `yolov8n-face` (6.3MB) - Fast face detection
- `mobilenet-v2` (2.5MB) - Image classification, ImageNet-1000
- Custom models via `--repo` flag

**Integration:**
Nodes reference models by name (auto-downloads if missing):
```toml
# config/image_classifier.toml
[model]
name = "mobilenet-v2"  # Auto-downloads from catalog
```

**Auto-download:**
- `mecha10 setup` downloads recommended models
- Nodes auto-download on first use if model missing
- Works offline once cached

**INT8 Quantization:**
Some models (like `yolov8n`) automatically generate optimized INT8 versions during download for 2x faster inference. See [MODEL_QUANTIZATION.md](docs/MODEL_QUANTIZATION.md) for details.

### `mecha10 clean`

Clean build artifacts:

```bash
# Clean build directories
mecha10 clean

# Also clean model cache
mecha10 clean --cache
```

**Removes:**
- `build/`
- `target/`
- `.mecha10/cache/` (if `--cache` specified)

## Global Options

All commands support:

- `--log-level <LEVEL>` - Set log level (debug, info, warn, error)
- `--config <PATH>` - Custom config file path

**Example:**
```bash
mecha10 dev --log-level debug
```

## Configuration

### Project Config (mecha10.json)

```json
{
  "$schema": "https://mecha10.dev/schemas/mecha10.schema.json",
  "robot": {
    "id": "my-robot",
    "name": "My Robot",
    "platform": "rover",
    "version": "0.1.0"
  },
  "runtime": {
    "hot_reload": true,
    "health_check_interval_s": 5
  },
  "nodes": {
    "camera": {
      "executable": "./nodes/camera_node",
      "args": ["--resolution=1080p"],
      "mode": "local",
      "auto_restart": true
    }
  },
  "platform": {
    "api_url": "${MECHA10_API_URL:-http://localhost:3006}",
    "fleet_id": "${FLEET_ID:-dev-fleet}"
  }
}
```

### Environment Variables (.env)

```bash
# Mecha10 Platform
MECHA10_API_URL=https://api.mecha10.dev
MECHA10_API_KEY=your-api-key

# Redis
REDIS_URL=redis://localhost:6379

# Fleet ID
FLEET_ID=production-fleet

# Development
DEV_MODE=false
LOG_LEVEL=info
```

## Workflow

### Development Workflow

```bash
# 1. Create project
mecha10 init my-robot
cd my-robot

# 2. Configure environment
cp .env.example .env
# Edit .env with your values

# 3. Implement nodes
# Write your node code in nodes/

# 4. Start development
mecha10 dev

# 5. View status
mecha10 status

# 6. Clean up
mecha10 clean
```

### Production Workflow

```bash
# 1. Build for release
mecha10 build --release

# 2. Test locally
mecha10 run --env staging

# 3. Deploy to production
mecha10 deploy --env production --strategy canary
```

### Training Workflow

```bash
# 1. Create training config
# Edit training/my-policy.yaml

# 2. Submit training job
mecha10 train training/my-policy.yaml --wait

# 3. Download model
# Model automatically deployed to .mecha10/cache/models/
```

## Integration

**With @mecha10/config:**
```rust
let mut config_manager = ConfigManager::new(".mecha10")?;
let config = config_manager.load("mecha10.json").await?;
```

**With @mecha10/core:**
```rust
let mut runtime = Runtime::new("robot-1").await?;
runtime.start_node(node_config).await?;
runtime.run().await?;
```

## Logging

Uses `tracing` for structured logging:

```
INFO  mecha10_cli: Starting development mode (env: dev)
INFO  mecha10_cli: Loading config from: "mecha10.json"
INFO  mecha10_core: Started node: camera
INFO  mecha10_core: Started node: slam
```

Enable debug logging:
```bash
mecha10 dev --log-level debug
```

## Error Handling

The CLI provides clear error messages:

```
Error: mecha10.json not found
Run 'mecha10 init <name>' to create a new project.
```

```
Error: Failed to start node 'camera'
No such file or directory: ./nodes/camera_node
Build the node first with: mecha10 build
```

## Architecture

```
┌─────────────────┐
│  mecha10 CLI   │
└────────┬────────┘
         ├──> ConfigManager (load configs)
         ├──> Runtime (start/monitor nodes)
         └──> Platform API (deploy/train)
```

## Examples

See [QUICKSTART.md](../../QUICKSTART.md) for complete examples.

## Library Usage

The CLI can also be used as a library for programmatic access:

```rust
use mecha10_cli::{CliContext, CliContextBuilder, services::ProjectService};
use std::path::Path;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Detect existing project
    let project = ProjectService::detect(Path::new("."))?;
    println!("Project: {} v{}", project.name()?, project.version()?);

    // Or use context for complex operations
    let ctx = CliContextBuilder::new()
        .redis_url("redis://localhost:6379".to_string())
        .verbose(true)
        .build()?;

    // Access services
    let docker = ctx.docker();
    docker.check_installation()?;
    docker.compose_up(true).await?;

    Ok(())
}
```

See [lib.rs documentation](src/lib.rs) for complete API examples.

### Available Services

All services are accessible through `CliContext`:

- `DockerService` - Container and compose operations
- `RedisService` - Redis connection management
- `ConfigService` - Project configuration
- `ProjectService` - Project structure and validation
- `SimulationService` - Godot simulation generation
- `ProcessService` - Child process management
- `TemplateService` - Code generation
- `ComponentCatalogService` - Component discovery
- `DiscoveryService` - Network node discovery
- `DeploymentService` - Deployment operations
- `PackageService` - Package management

## Development

```bash
# Build CLI
cd packages/cli
cargo build --release

# Run directly
cargo run -- init test-robot

# Install locally
cargo install --path .

# Run tests
cargo test --lib          # Unit tests
cargo test                # All tests

# Check code quality
cargo clippy --all-targets -- -D warnings
cargo fmt --all -- --check
```

## Testing

The CLI has comprehensive test coverage:

- **392 tests** passing
- **70-75%** coverage across services
- All services have dedicated unit tests
- Integration tests for key workflows

See [CLI_ARCHITECTURE.md](../../docs/architecture/CLI_ARCHITECTURE.md#testing-strategy) for testing patterns.

## License

MIT