# CLI Architecture

The Provisioning CLI provides a unified command-line interface for all infrastructure
operations. It features 111+ commands organized into 7 domain-focused modules with 80+
shortcuts for improved productivity. The modular architecture achieved 84% code reduction
while improving maintainability and extensibility.

## Overview

The CLI architecture uses domain-driven design, separating concerns across modules. This
refactoring reduced the main entry point from monolithic code to 211 lines. The architecture
improves discoverability and enables rapid feature development.

<p align="center">
    <img src="../resources/diagrams/features/cli-architecture.svg"
         alt="CLI Architecture Modular Design Decentralized Command Registration" width="750"/>
</p>

### Key Metrics

| Metric | Before | After | Improvement |
| ------ | ------ | ----- | ----------- |
| Main CLI lines | 1,329 | 211 | 84% reduction |
| Command domains | 1 (monolithic) | 7 (modular) | 7x organization |
| Commands | ~50 | 111+ | 122% increase |
| Shortcuts | 0 | 80+ | New capability |
| Help categories | 0 | 7 | Improved discovery |

## Domain Architecture

The CLI is organized into 7 domain-focused modules:

### 1. Infrastructure Domain

**Commands**: Server, TaskServ, Cluster, Infra management

```bash
# Server operations
provisioning server create
provisioning server list
provisioning server delete
provisioning server ssh <hostname>

# Task service operations
provisioning taskserv install kubernetes
provisioning taskserv list
provisioning taskserv remove kubernetes

# Cluster operations
provisioning cluster deploy my-cluster
provisioning cluster status my-cluster
provisioning cluster scale my-cluster --nodes 5
```

**Shortcuts**: `s` (server), `t`/`task` (taskserv), `cl` (cluster), `i` (infra)

### 2. Orchestration Domain

**Commands**: Workflow, Batch, Orchestrator management

```bash
# Workflow operations
provisioning workflow list
provisioning workflow status <id>
provisioning workflow cancel <id>

# Batch operations
provisioning batch submit infra/batch-workflows.ncl
provisioning batch monitor <workflow-id>
provisioning batch list

# Orchestrator management
provisioning orchestrator start
provisioning orchestrator status
provisioning orchestrator logs
```

**Shortcuts**: `wf`/`flow` (workflow), `bat` (batch), `orch` (orchestrator)

### 3. Development Domain

**Commands**: Module, Layer, Version, Pack management

```bash
# Module operations
provisioning module create my-module
provisioning module list
provisioning module test my-module

# Layer operations
provisioning layer add <name>
provisioning layer list

# Versioning
provisioning version bump minor
provisioning version list

# Packaging
provisioning pack create my-extension
provisioning pack publish my-extension
```

**Shortcuts**: `mod` (module), `l` (layer), `v` (version), `p` (pack)

### 4. Workspace Domain

**Commands**: Workspace management, templates

```bash
# Workspace operations
provisioning workspace init my-project
provisioning workspace list
provisioning workspace switch my-project
provisioning workspace delete old-project

# Template operations
provisioning workspace template list
provisioning workspace template show kubernetes-ha
```

**Shortcuts**: `ws` (workspace)

### 5. Configuration Domain

**Commands**: Config, Environment, Validate, Setup

```bash
# Configuration operations
provisioning config get servers.default_plan
provisioning config set servers.default_plan large
provisioning config validate

# Environment operations
provisioning env
provisioning allenv

# Setup operations
provisioning setup profile --profile developer
provisioning setup versions

# Validation
provisioning validate config
provisioning validate infra
provisioning validate nickel workspace/infra/my-cluster.ncl
```

**Shortcuts**: `cfg` (config), `val` (validate), `st` (setup)

### 6. Utilities Domain

**Commands**: SSH, SOPS, Cache, Plugin management

```bash
# SSH operations
provisioning ssh server-01
provisioning ssh server-01 -- uptime

# SOPS operations
provisioning sops encrypt config.yaml
provisioning sops decrypt config.enc.yaml

# Cache operations
provisioning cache clear
provisioning cache stats

# Plugin operations
provisioning plugin list
provisioning plugin install nu_plugin_auth
provisioning plugin update
```

**Shortcuts**: `sops`, `cache`, `plug` (plugin)

### 7. Generation Domain

**Commands**: Generate code, configs, docs

```bash
# Code generation
provisioning generate provider upcloud-new
provisioning generate taskserv postgresql
provisioning generate cluster k8s-ha

# Config generation
provisioning generate config --profile production
provisioning generate nickel --template kubernetes

# Documentation generation
provisioning generate docs
```

**Shortcuts**: `g`/`gen` (generate)

## Command Shortcuts

The CLI provides 80+ shortcuts for improved productivity:

### Infrastructure Shortcuts

| Full Command | Shortcuts | Example |
| ------------ | --------- | ------- |
| `server` | `s` | `provisioning s list` |
| `taskserv` | `t`, `task` | `provisioning t install kubernetes` |
| `cluster` | `cl` | `provisioning cl deploy my-cluster` |
| `infrastructure` | `i`, `infra` | `provisioning i list` |

### Orchestration Shortcuts

| Full Command | Shortcuts | Example |
| ------------ | --------- | ------- |
| `workflow` | `wf`, `flow` | `provisioning wf list` |
| `batch` | `bat` | `provisioning bat submit workflow.ncl` |
| `orchestrator` | `orch` | `provisioning orch status` |

### Development Shortcuts

| Full Command | Shortcuts | Example |
| ------------ | --------- | ------- |
| `module` | `mod` | `provisioning mod list` |
| `layer` | `l` | `provisioning l add base` |
| `version` | `v` | `provisioning v bump minor` |
| `pack` | `p` | `provisioning p create extension` |

### Configuration Shortcuts

| Full Command | Shortcuts | Example |
| ------------ | --------- | ------- |
| `workspace` | `ws` | `provisioning ws switch prod` |
| `config` | `cfg` | `provisioning cfg get servers.plan` |
| `validate` | `val` | `provisioning val config` |
| `setup` | `st` | `provisioning st profile --profile dev` |
| `environment` | `env` | `provisioning env` |

### Utility Shortcuts

| Full Command | Shortcuts | Example |
| ------------ | --------- | ------- |
| `generate` | `g`, `gen` | `provisioning g provider aws-new` |
| `plugin` | `plug` | `provisioning plug list` |

### Quick Reference Shortcuts

| Full Command | Shortcuts | Purpose |
| ------------ | --------- | ------- |
| `shortcuts` | `sc` | Show shortcuts reference |
| `guide` | - | Interactive guides |
| `howto` | - | Quick how-to guides |

## Bi-Directional Help System

The CLI features a bi-directional help system that works in both directions:

```bash
# Both of these work identically
provisioning help workspace
provisioning workspace help

# Shortcuts also work
provisioning help ws
provisioning ws help

# Category help
provisioning help infrastructure
provisioning help orchestration
```

This flexibility improves discoverability and aligns with natural user expectations.

## Centralized Flag Handling

All global flags are handled consistently across all commands:

### Global Flags

| Flag | Short | Purpose | Example |
| ---- | ----- | ------- | ------- |
| `--debug` | `-d` | Enable debug mode | `provisioning --debug server create` |
| `--check` | `-c` | Dry-run mode (no changes) | `provisioning --check server delete` |
| `--yes` | `-y` | Auto-confirm operations | `provisioning --yes cluster delete` |
| `--infra` | `-i` | Specify infrastructure | `provisioning --infra my-cluster server list` |
| `--verbose` | `-v` | Verbose output | `provisioning --verbose workflow list` |
| `--quiet` | `-q` | Minimal output | `provisioning --quiet batch submit` |
| `--format` | `-f` | Output format (json/yaml/table) | `provisioning --format json server list` |

### Command-Specific Flags

```bash
# Server creation flags
provisioning server create --plan large --region us-east-1 --zone a

# TaskServ installation flags
provisioning taskserv install kubernetes --version 1.29.0 --ha

# Cluster deployment flags
provisioning cluster deploy --replicas 3 --storage 100GB

# Batch workflow flags
provisioning batch submit workflow.ncl --parallel 5 --timeout 3600
```

## Command Discovery

### Categorized Help

The help system organizes commands by domain:

```bash
provisioning help

# Output shows categorized commands:
Infrastructure Commands:
  server        Manage servers (shortcuts: s)
  taskserv      Manage task services (shortcuts: t, task)
  cluster       Manage clusters (shortcuts: cl)

Orchestration Commands:
  workflow      Manage workflows (shortcuts: wf, flow)
  batch         Batch operations (shortcuts: bat)
  orchestrator  Orchestrator management (shortcuts: orch)

Configuration Commands:
  workspace     Workspace management (shortcuts: ws)
  config        Configuration management (shortcuts: cfg)
  validate      Validation operations (shortcuts: val)
  setup         System setup (shortcuts: st)
```

### Quick Reference

```bash
# Fastest command reference
provisioning sc

# Shows comprehensive shortcuts table with examples
```

### Interactive Guides

```bash
# Step-by-step guides
provisioning guide from-scratch      # Complete deployment guide
provisioning guide quickstart         # Command shortcuts reference
provisioning guide customize          # Customization patterns
```

## Command Routing

The CLI uses a sophisticated dispatcher for command routing:

```nushell
# provisioning/core/nulib/main_provisioning/dispatcher.nu

# Route command to appropriate handler
export def dispatch [
    command: string
    args: list<string>
] {
    match $command {
        # Infrastructure domain
        "server" | "s" => { route-to-handler "infrastructure" "server" $args }
        "taskserv" | "t" | "task" => { route-to-handler "infrastructure" "taskserv" $args }
        "cluster" | "cl" => { route-to-handler "infrastructure" "cluster" $args }

        # Orchestration domain
        "workflow" | "wf" | "flow" => { route-to-handler "orchestration" "workflow" $args }
        "batch" | "bat" => { route-to-handler "orchestration" "batch" $args }

        # Configuration domain
        "workspace" | "ws" => { route-to-handler "configuration" "workspace" $args }
        "config" | "cfg" => { route-to-handler "configuration" "config" $args }
    }
}
```

This routing enables:

- Consistent error handling
- Centralized logging
- Workspace enforcement
- Permission checks
- Audit trail

## Command Implementation Pattern

All commands follow a consistent implementation pattern:

```nushell
# Example: provisioning/core/nulib/main_provisioning/commands/server.nu

# Main command handler
export def main [
    operation: string    # create, list, delete, etc.
    --check             # Dry-run mode
    --yes               # Auto-confirm
] {
    # 1. Validate workspace requirement
    enforce-workspace-requirement "server" $operation

    # 2. Load configuration
    let config = load-config

    # 3. Parse operation
    match $operation {
        "create" => { create-server $args $config --check=$check --yes=$yes }
        "list" => { list-servers $config }
        "delete" => { delete-server $args $config --yes=$yes }
        "ssh" => { ssh-to-server $args $config }
        _ => { error $"Unknown server operation: ($operation)" }
    }

    # 4. Log operation (audit trail)
    log-operation "server" $operation $args
}
```

This pattern ensures:

- Consistent behavior
- Proper error handling
- Configuration integration
- Workspace enforcement
- Audit logging

## Modular Structure

The CLI codebase is organized for maintainability:

```bash
provisioning/core/
├── cli/
│   └── provisioning           # Main CLI entry point (211 lines)
│
├── nulib/
│   ├── main_provisioning/
│   │   ├── dispatcher.nu      # Command routing (central dispatch)
│   │   ├── flags.nu           # Centralized flag handling
│   │   ├── help_system_fluent.nu  # Categorized help with i18n
│   │   │
│   │   └── commands/          # Domain-specific command handlers
│   │       ├── infrastructure/
│   │       │   ├── server.nu
│   │       │   ├── taskserv.nu
│   │       │   └── cluster.nu
│   │       │
│   │       ├── orchestration/
│   │       │   ├── workflow.nu
│   │       │   ├── batch.nu
│   │       │   └── orchestrator.nu
│   │       │
│   │       ├── configuration/
│   │       │   ├── workspace.nu
│   │       │   ├── config.nu
│   │       │   └── validate.nu
│   │       │
│   │       └── utilities/
│   │           ├── ssh.nu
│   │           ├── sops.nu
│   │           └── cache.nu
│   │
│   └── lib_provisioning/      # Core libraries (used by commands)
│       ├── config/
│       ├── providers/
│       ├── workspace/
│       └── utils/
```

This structure enables:

- Clear separation of concerns
- Easy addition of new commands
- Testable command handlers
- Reusable core libraries

## Internationalization

The CLI supports multiple languages via Fluent catalog:

```bash
# Automatic locale detection
export LANG=es_ES.UTF-8
provisioning help    # Shows Spanish help if es-ES catalog exists

# Supported locales
en-US (default)      # English
es-ES                # Spanish
fr-FR                # French
de-DE                # German
```

Catalog structure:

```text
provisioning/locales/
├── en-US/
│   └── help.ftl      # English help strings
├── es-ES/
│   └── help.ftl      # Spanish help strings
└── de-DE/
    └── help.ftl      # German help strings
```

## Extension Points

The modular architecture provides clean extension points:

### Adding New Commands

```bash
# 1. Create command handler
provisioning/core/nulib/main_provisioning/commands/my_new_command.nu

# 2. Register in dispatcher
# provisioning/core/nulib/main_provisioning/dispatcher.nu
"my-command" | "mc" => { route-to-handler "utilities" "my-command" $args }

# 3. Add help entry
# provisioning/locales/en-US/help.ftl
my-command-help = Manage my new feature

# 4. Command is now available
provisioning my-command <operation>
provisioning mc <operation>  # Shortcut also works
```

### Adding New Domains

```bash
# 1. Create domain directory
provisioning/core/nulib/main_provisioning/commands/my_domain/

# 2. Add domain commands
my_domain/
├── command1.nu
├── command2.nu
└── command3.nu

# 3. Register domain in dispatcher

# 4. Add domain help category

# Domain is now available with all commands
```

## Command Aliases

The CLI supports command aliases for common operations:

```bash
# Defined in user configuration
# ~/.config/provisioning/user_config.yaml
aliases:
  deploy: "cluster deploy"
  list-all: "server list && taskserv list && cluster list"
  quick-test: "test quick kubernetes"

# Usage
provisioning deploy my-cluster     # Expands to: cluster deploy my-cluster
provisioning list-all              # Runs multiple commands
provisioning quick-test            # Runs test with preset
```

## Best Practices

### Using Shortcuts Effectively

```bash
# Development workflow (frequent commands)
provisioning ws switch dev          # Switch to dev workspace
provisioning s list                 # Quick server list
provisioning t install postgres     # Install task service
provisioning cl status my-cluster   # Check cluster status

# Production workflow (explicit commands for clarity)
provisioning workspace switch production
provisioning server create --plan large --check
provisioning cluster deploy critical-cluster --yes
```

### Dry-Run Before Execution

```bash
# Always check before dangerous operations
provisioning --check server delete old-servers
provisioning --check cluster delete test-cluster

# If output looks good, run for real
provisioning --yes server delete old-servers
```

### Using Output Formats

```bash
# JSON output for scripting
provisioning --format json server list | jq '.[] | select(.status == "running")'

# YAML output for readability
provisioning --format yaml cluster status my-cluster

# Table output for humans (default)
provisioning server list
```

## Performance Optimizations

The modular architecture enables several performance optimizations:

### Lazy Loading

Commands are loaded on-demand, reducing startup time:

```nushell
# Only loads server command module when needed
provisioning server list    # Fast startup (loads server.nu only)
```

### Command Caching

Frequently-used commands benefit from caching:

```bash
# First run: ~200ms (loads modules, config)
provisioning server list

# Subsequent runs: ~50ms (cached config, loaded modules)
provisioning server list
```

### Parallel Execution

Batch operations execute in parallel:

```bash
# Executes server creation in parallel (up to configured limit)
provisioning batch submit multi-server-workflow.ncl --parallel 10
```

## Troubleshooting

### Command Not Found

```text
Error: Unknown command 'servr'
Did you mean: server (s)
```

The CLI provides helpful suggestions for typos.

### Missing Workspace

```text
Error: No active workspace
Please activate or create a workspace:
  provisioning workspace init <name>
  provisioning workspace switch <name>
```

Workspace enforcement prevents accidental operations.

### Permission Denied

```text
Error: Operation requires admin permissions
Please run with elevated privileges or contact administrator
```

Permission system prevents unauthorized operations.

## See Also

- [Workspace Management](workspace-management.md) - Workspace-first approach
- [Configuration System](configuration-system.md) - Hierarchical configuration
- [Interactive Guides](interactive-guides.md) - Step-by-step walkthroughs
- [Batch Workflows](batch-workflows.md) - Multi-cloud orchestration
