# @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
