# Component Architecture

Detailed architecture of each major Provisioning component.

## Core Components Map

```text
User Interface
  ├─ CLI (Nushell dispatcher)
  ├─ Web Dashboard (Control Center UI)
  ├─ REST API (Control Center)
  └─ MCP Server (AI Integration)
       ↓
Core Engine (54 Nushell libraries)
  ├─ Configuration Management
  ├─ Provider Abstraction
  ├─ Workspace Management
  ├─ Infrastructure Validation
  ├─ Secrets Management
  └─ Command Utilities
       ↓
Platform Services (12 Rust microservices)
  ├─ Orchestrator (Workflow execution)
  ├─ Control Center (API + Auth)
  ├─ Control Center UI (Web dashboard)
  ├─ MCP Server (AI integration)
  ├─ Vault Service (Secrets backend)
  ├─ Extension Registry (OCI distribution)
  ├─ AI Service (LLM features)
  ├─ Detector (Anomaly detection)
  ├─ RAG (Knowledge retrieval)
  ├─ Provisioning Daemon (Background service)
  ├─ Platform Config (Configuration management)
  └─ Service Clients (API clients)
       ↓
Extensions (Modular infrastructure)
  ├─ Providers (5 cloud providers)
  ├─ Task Services (50+ services)
  ├─ Clusters (9 templates)
  └─ Workflows (Automation)
       ↓
Infrastructure (Running resources)
  ├─ Cloud Compute
  ├─ Networks & Storage
  ├─ Services
  └─ Monitoring
```

## 1. CLI Layer

**Location**: `provisioning/core/cli/`

### Main Entry Point (`provisioning`)

Bash wrapper that:
1. Detects Nushell installation
2. Loads environment variables
3. Validates workspace requirement
4. Routes command to dispatcher
5. Handles error reporting

### Command Dispatcher

**Location**: `provisioning/core/nulib/main_provisioning/dispatcher.nu`

Supports:
- **111+ commands** across 7 domains
- **80+ shortcuts** for productivity
- **Bi-directional help** (help workspace / workspace help)
- **Dynamic loading** of command modules

## 2. Core Engine Components

### Configuration Management

**Location**: `provisioning/core/nulib/lib_provisioning/config/`

**Key Features**:
- Load merged configuration from 5 layers
- 476+ accessors for config values
- Variable interpolation & TOML merging
- Schema validation
- Configuration caching

### Provider Abstraction

**Location**: `provisioning/core/nulib/lib_provisioning/providers/`

**Supported Providers** (5):
- UpCloud - Primary European cloud
- AWS - Amazon Web Services
- Hetzner - Baremetal & cloud
- Local - Development environment
- Demo - Testing & mocking

**Features**:
- Unified cloud provider interface
- Dynamic provider loading
- Credential management
- Provider state tracking

### Workspace Management

**Location**: `provisioning/core/nulib/lib_provisioning/workspace/`

**Responsibilities**:
- Workspace registry tracking
- Atomic workspace switching
- Configuration isolation
- Extension inheritance
- State management

**Workspace Registry**:
```yaml
workspaces:
  active: "my-project"
  registry:
    my-project:
      path: ~/.provisioning/workspaces/workspace_my_project
      created: 2026-01-16T10:30:00Z
      template: default
```

### Infrastructure Validation

**Location**: `provisioning/core/nulib/lib_provisioning/infra_validator/`

**Validation Stages**:
1. Syntax check - Valid Nickel syntax
2. Type check - Type correctness
3. Schema check - Matches expected schema
4. Constraint check - Business rule validation
5. Dependency check - Infrastructure dependencies
6. Security check - Security policies

### Secrets Management

**Location**: `provisioning/core/nulib/lib_provisioning/secrets/`

**Backends**:
- SOPS + Age (default)
- Cosmian KMS (enterprise)
- AWS KMS (AWS)
- Local KMS (development)

## 3. Platform Services

### Orchestrator

**Location**: `provisioning/platform/crates/orchestrator/`

**Technology**: Rust + Nushell

**Key Features**:
- High-performance workflow execution
- File-based persistence
- Checkpoint recovery
- Parallel execution with dependencies
- REST API (83+ endpoints)
- Priority-based task scheduling

**State Persistence**:
```text
~/.provisioning/
├── queue/           # Task queue
├── checkpoints/     # Workflow checkpoints
└── state/           # Infrastructure state
```

### Control Center

**Location**: `provisioning/platform/crates/control-center/`

**Technology**: Rust (Axum)

**Features**:
- JWT authentication
- Cedar policy authorization
- RBAC system
- Audit logging
- REST API for all operations

**Authorization Model**:
- User roles (admin, user, viewer)
- Fine-grained permissions
- Cedar policy enforcement
- Attribute-based access control

### Control Center UI

**Location**: `provisioning/platform/crates/control-center-ui/`

**Features**:
- Real-time infrastructure view
- Workflow visualization
- Configuration management
- Resource monitoring
- Audit log viewer

### MCP Server

**Location**: `provisioning/platform/crates/mcp-server/`

**Technology**: Rust

**Features**:
- AI-powered assistance via MCP
- Natural language command parsing
- Auto-completion of configurations
- 7 configuration tools for LLM
- Context-aware recommendations

### Vault Service

**Location**: `provisioning/platform/crates/vault-service/`

**Features**:
- Encrypted credential storage
- KMS integration (5 backends)
- SOPS + Age encryption
- Secure credential injection
- Audit logging for secret access

### Extension Registry

**Location**: `provisioning/platform/crates/extension-registry/`

**Features**:
- OCI-compliant distribution
- Provider/taskserv packaging
- Semantic version management
- Content addressable storage
- Registry API endpoints

### AI Service

**Location**: `provisioning/platform/crates/ai-service/`

**Features**:
- LLM integration platform
- Infrastructure request parsing
- Workspace context enrichment
- Configuration suggestion generation
- Multi-provider LLM support

### Detector

**Location**: `provisioning/platform/crates/detector/`

**Features**:
- System health monitoring
- Anomaly pattern detection
- Infrastructure issue identification
- Real-time surveillance
- Alerting system integration

### RAG Service

**Location**: `provisioning/platform/crates/rag/`

**Features**:
- Retrieval Augmented Generation
- Document semantic embedding
- Knowledge base integration
- Context-aware answer generation
- Multi-source knowledge synthesis

### Provisioning Daemon

**Location**: `provisioning/platform/crates/provisioning-daemon/`

**Features**:
- Background service operation
- System event monitoring
- Background job execution
- Infrastructure state synchronization
- Event-driven architecture

### Platform Config

**Location**: `provisioning/platform/crates/platform-config/`

**Features**:
- Centralized configuration loading
- Schema-based validation
- Multi-environment support
- System-wide default settings
- Configuration hot-reload support

### Service Clients

**Location**: `provisioning/platform/crates/service-clients/`

**Features**:
- Platform service client SDKs
- Cloud provider API clients
- HTTP/RPC request handling
- Connection pooling and management
- Retry logic and error handling

## 4. Extension Components

### Providers

**Location**: `provisioning/extensions/providers/`

**Structure**:
```text
providers/
├── upcloud/        # UpCloud provider
├── aws/            # AWS provider
├── hetzner/        # Hetzner provider
├── local/          # Local dev provider
├── demo/           # Demo/test provider
└── prov_lib/       # Shared utilities
```

**Provider Interface**:
- Create/delete resources
- List resources
- Query resource status
- Network/storage management
- Credential validation

### Task Services

**Location**: `provisioning/extensions/taskservs/`

**50+ Services** in 18 categories:
- Container runtimes (containerd, podman, crio)
- Kubernetes (etcd, coredns, cilium, calico)
- Storage (rook-ceph, mayastor, nfs)
- Databases (postgres, redis, mongodb)
- Networking (ip-aliases, proxy, kms)
- Security (webhook, kms, oras)
- Observability (prometheus, grafana, loki)
- Development (gitea, coder, buildkit)
- Hypervisor (kvm, qemu, libvirt)

### Clusters

**Location**: `provisioning/extensions/clusters/`

**9 Pre-built Templates**:
- **web** - Web service cluster
- **oci-reg** - Container registry
- **git** - Git hosting (Gitea)
- **buildkit** - Build infrastructure
- **k8s-ha** - HA Kubernetes
- **postgresql** - HA PostgreSQL
- **cicd-argocd** - GitOps CI/CD
- **cicd-tekton** - Tekton pipelines

## 5. Configuration Layer

### Nickel Schemas

**Location**: `provisioning/schemas/`

**Structure** (27 directories):
```text
schemas/
├── main.ncl             # Entry point
├── lib/                 # Utilities
├── config/              # Settings
├── infrastructure/      # Servers, networks
├── operations/          # Workflows
├── deployment/          # Kubernetes
├── services/            # Service defs
└── versions.ncl         # Tool versions
```

**3-File Pattern**:

1. **contracts.ncl** - Type definitions
2. **defaults.ncl** - Default values
3. **main.ncl** - Entry point + makers

## Component Dependencies

```text
CLI
  ├─ Configuration
  ├─ Workspace
  ├─ Validation
  ├─ Secrets
  └─ Providers

Providers
  └─ Orchestrator

Orchestrator
  ├─ Task Services
  ├─ Control Center
  └─ State Manager

Control Center
  ├─ Authorization
  ├─ Audit Logging
  └─ State Manager
```

## Communication Patterns

### Synchronous (Request-Response)
```text
CLI → Orchestrator → Provider → Cloud API
```

### Asynchronous (Queue)
```text
CLI → Orchestrator (queue) → [Background execution]
```

### Event-Driven
```text
Provider Event → Orchestrator → State Update
                            → Control Center
                            → Monitoring
```

## Related Documentation

- [System Overview](system-overview.md)
- [Design Principles](design-principles.md)
- [Integration Patterns](integration-patterns.md)
