Przeglądaj źródła

docs: add comprehensive project documentation #1

- Add README.md with project overview, features, and quick start guide
- Add docs/ARCHITECTURE.md with detailed system architecture and design
- Add docs/DEVELOPMENT.md with development setup and building instructions
- Add docs/API.md with complete REST API endpoint documentation
- Add docs/DEPLOYMENT.md with production deployment and operations guide

This addresses the missing documentation for the project, providing:
- Clear project introduction and feature list
- Architecture overview with component details
- Development environment setup instructions
- Complete API reference for all endpoints
- Production deployment and maintenance procedures

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Claude 2 tygodni temu
rodzic
commit
6d9589714a
5 zmienionych plików z 3530 dodań i 0 usunięć
  1. 189 0
      README.md
  2. 1410 0
      docs/API.md
  3. 578 0
      docs/ARCHITECTURE.md
  4. 823 0
      docs/DEPLOYMENT.md
  5. 530 0
      docs/DEVELOPMENT.md

+ 189 - 0
README.md

@@ -0,0 +1,189 @@
+# Smartbotic Microbit
+
+Smartbotic Microbit is a comprehensive workspace management and AI assistant platform that enables organizations to manage teams, schedule appointments, and deploy AI-powered voice assistants for customer interaction.
+
+## Features
+
+- **Multi-Workspace Management**: Support for multiple workspaces with team collaboration
+- **User Authentication & Authorization**: JWT-based authentication with role-based access control (Owner, Admin, Member, Guest)
+- **Calendar & Appointment System**: Manage calendars, time slots, and appointments with availability tracking
+- **AI Voice Assistants**: Integration with CallerAI for creating and managing AI-powered voice assistants
+- **Team Collaboration**: Invite members, manage roles, and collaborate across workspaces
+- **Email Notifications**: SMTP integration for invitation emails and notifications
+- **RESTful API**: Comprehensive REST API for all platform features
+- **Web UI**: React-based modern web interface built with TypeScript and Tailwind CSS
+
+## Architecture
+
+Smartbotic Microbit consists of three main components:
+
+1. **Backend Service** (`smartbotic-microbit`): C++20-based HTTP service with RESTful API
+2. **Database Service** (`smartbotic-database`): Custom database service for persistent storage
+3. **Web UI**: React + TypeScript frontend application
+
+For detailed architecture information, see [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
+
+## Quick Start
+
+### Prerequisites
+
+- Linux (Debian/Ubuntu recommended)
+- CMake 3.20+
+- C++20 compatible compiler (GCC 11+ or Clang 14+)
+- Node.js 18+ and npm (for WebUI development)
+- Git
+
+### Installation
+
+The easiest way to install Smartbotic Microbit is using the pre-built packages:
+
+```bash
+# Download the latest release packages
+# Install using the provided installer
+sudo ./packaging/scripts/install.sh smartbotic-*.tar.gz
+
+# Configure the service
+sudo cp /etc/smartbotic/smartbotic.env.default /etc/smartbotic/smartbotic.env
+sudo nano /etc/smartbotic/smartbotic.env  # Set JWT_SECRET, SMTP, and CallerAI settings
+
+# Start the services
+sudo systemctl enable smartbotic-database smartbotic-microbit
+sudo systemctl start smartbotic-database
+sudo systemctl start smartbotic-microbit
+```
+
+For detailed installation and deployment instructions, see [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md).
+
+### Development Setup
+
+For development and building from source:
+
+```bash
+# Clone the repository with submodules
+git clone --recursive https://github.com/fszontagh/smartbotic-microbit.git
+cd smartbotic-microbit
+
+# Build the backend
+mkdir build && cd build
+cmake ..
+make -j$(nproc)
+
+# Build the WebUI
+cd ../webui
+npm install
+npm run build
+```
+
+For complete development setup instructions, see [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md).
+
+## Configuration
+
+The main configuration file is located at `/etc/smartbotic/microbit.json` (or `config/microbit.json` for development).
+
+Key configuration sections:
+
+- **Database**: Connection settings for the database service
+- **HTTP**: Server bind address, port, and static file serving
+- **Auth**: JWT settings and password policy
+- **SMTP**: Email server configuration for notifications
+- **CallerAI**: API credentials for AI assistant integration
+- **CORS**: Cross-origin resource sharing settings
+- **Rate Limiting**: API rate limiting configuration
+
+Environment variables can be used to override configuration values using the `${VAR_NAME:default}` syntax.
+
+## API Documentation
+
+The platform provides a comprehensive RESTful API. Key endpoint groups:
+
+- `/api/v1/auth/*` - Authentication (register, login, refresh tokens)
+- `/api/v1/users/*` - User management
+- `/api/v1/workspaces/*` - Workspace CRUD and member management
+- `/api/v1/workspaces/:id/assistants/*` - AI assistant management
+- `/api/v1/workspaces/:id/calendars/*` - Calendar and appointment management
+- `/api/v1/invitations/*` - Workspace invitations
+- `/api/v1/settings/*` - Global and workspace settings
+
+For complete API documentation, see [docs/API.md](docs/API.md).
+
+## Usage
+
+### Creating a Workspace
+
+After registering and logging in, create your first workspace:
+
+```bash
+curl -X POST http://localhost:8090/api/v1/workspaces \
+  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
+  -H "Content-Type: application/json" \
+  -d '{
+    "name": "My Company",
+    "company_name": "Acme Corp",
+    "address": "123 Main St",
+    "phone": "+1-555-0100"
+  }'
+```
+
+### Inviting Team Members
+
+```bash
+curl -X POST http://localhost:8090/api/v1/workspaces/WORKSPACE_ID/invitations \
+  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
+  -H "Content-Type: application/json" \
+  -d '{
+    "email": "colleague@example.com",
+    "role": "member"
+  }'
+```
+
+### Creating an AI Assistant
+
+```bash
+curl -X POST http://localhost:8090/api/v1/workspaces/WORKSPACE_ID/assistants \
+  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
+  -H "Content-Type: application/json" \
+  -d '{
+    "name": "Customer Support Bot",
+    "phone_number": "+1-555-0200",
+    "instructions": "You are a helpful customer support assistant..."
+  }'
+```
+
+## Documentation
+
+- [Architecture Overview](docs/ARCHITECTURE.md) - System design and component interaction
+- [Development Guide](docs/DEVELOPMENT.md) - Building and developing the project
+- [API Reference](docs/API.md) - Complete API endpoint documentation
+- [Deployment Guide](docs/DEPLOYMENT.md) - Installation and deployment instructions
+
+## Technology Stack
+
+**Backend:**
+- C++20
+- httplib (HTTP server)
+- nlohmann/json (JSON parsing)
+- spdlog (Logging)
+- JWT-CPP (JWT tokens)
+- BCrypt (Password hashing)
+- gRPC (Database communication)
+
+**Frontend:**
+- React 19
+- TypeScript
+- Tailwind CSS 4
+- React Router
+- TanStack Query
+- Zustand (State management)
+- Vite (Build tool)
+
+**Database:**
+- Custom smartbotic-database service
+- Protocol Buffers (gRPC interface)
+
+## License
+
+Copyright © 2024 Smartbotics AI
+
+## Support
+
+For issues and questions, please use the GitHub issue tracker or contact support@smartbotics.ai.

+ 1410 - 0
docs/API.md

@@ -0,0 +1,1410 @@
+# API Reference
+
+This document describes the Smartbotic Microbit REST API.
+
+## Base URL
+
+```
+http://localhost:8090/api/v1
+```
+
+In production, use your configured domain with HTTPS.
+
+## Authentication
+
+Most endpoints require authentication using JWT (JSON Web Tokens).
+
+### Authorization Header
+
+Include the access token in the `Authorization` header:
+
+```
+Authorization: Bearer YOUR_ACCESS_TOKEN
+```
+
+### Token Lifecycle
+
+- **Access Token**: Short-lived (default: 15 minutes), used for API requests
+- **Refresh Token**: Long-lived (default: 7 days), used to obtain new access tokens
+
+## Common Response Codes
+
+| Code | Description |
+|------|-------------|
+| 200 | Success |
+| 201 | Created successfully |
+| 400 | Bad request (invalid input) |
+| 401 | Unauthorized (missing or invalid token) |
+| 403 | Forbidden (insufficient permissions) |
+| 404 | Not found |
+| 500 | Internal server error |
+
+## Error Response Format
+
+```json
+{
+  "error": "Error message describing the problem"
+}
+```
+
+---
+
+## Authentication Endpoints
+
+### Register User
+
+Create a new user account.
+
+**Endpoint:** `POST /api/v1/auth/register`
+
+**Authentication:** Not required
+
+**Request Body:**
+
+```json
+{
+  "email": "user@example.com",
+  "password": "SecurePass123",
+  "display_name": "John Doe",
+  "invite_token": "optional-invite-token"
+}
+```
+
+**Response:** `201 Created`
+
+```json
+{
+  "user": {
+    "id": "usr_abc123",
+    "email": "user@example.com",
+    "display_name": "John Doe",
+    "status": "active",
+    "created_at": "2024-01-15T10:30:00Z",
+    "updated_at": "2024-01-15T10:30:00Z"
+  },
+  "access_token": "eyJhbGc...",
+  "refresh_token": "eyJhbGc...",
+  "token_type": "Bearer",
+  "expires_in": 900
+}
+```
+
+**Notes:**
+- Password must meet policy requirements (min 8 chars, contains number by default)
+- If `invite_token` is provided, pending invitations for this email will be processed
+
+### Login
+
+Authenticate and receive access tokens.
+
+**Endpoint:** `POST /api/v1/auth/login`
+
+**Authentication:** Not required
+
+**Request Body:**
+
+```json
+{
+  "email": "user@example.com",
+  "password": "SecurePass123"
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "user": {
+    "id": "usr_abc123",
+    "email": "user@example.com",
+    "display_name": "John Doe",
+    "status": "active"
+  },
+  "access_token": "eyJhbGc...",
+  "refresh_token": "eyJhbGc...",
+  "token_type": "Bearer",
+  "expires_in": 900
+}
+```
+
+### Refresh Token
+
+Obtain a new access token using a refresh token.
+
+**Endpoint:** `POST /api/v1/auth/refresh`
+
+**Authentication:** Not required
+
+**Request Body:**
+
+```json
+{
+  "refresh_token": "eyJhbGc..."
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "access_token": "eyJhbGc...",
+  "token_type": "Bearer",
+  "expires_in": 900
+}
+```
+
+### Logout
+
+Invalidate the current session.
+
+**Endpoint:** `POST /api/v1/auth/logout`
+
+**Authentication:** Required
+
+**Response:** `200 OK`
+
+```json
+{
+  "message": "Logged out successfully"
+}
+```
+
+### Get Current User
+
+Get information about the authenticated user.
+
+**Endpoint:** `GET /api/v1/auth/me`
+
+**Authentication:** Required
+
+**Response:** `200 OK`
+
+```json
+{
+  "user": {
+    "id": "usr_abc123",
+    "email": "user@example.com",
+    "display_name": "John Doe",
+    "status": "active"
+  }
+}
+```
+
+### Change Password
+
+Change the current user's password.
+
+**Endpoint:** `POST /api/v1/auth/change-password`
+
+**Authentication:** Required
+
+**Request Body:**
+
+```json
+{
+  "old_password": "OldPass123",
+  "new_password": "NewPass456"
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "message": "Password changed successfully"
+}
+```
+
+---
+
+## User Endpoints
+
+### Update Current User
+
+Update the authenticated user's profile.
+
+**Endpoint:** `PUT /api/v1/users/me`
+
+**Authentication:** Required
+
+**Request Body:**
+
+```json
+{
+  "display_name": "Jane Doe"
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "user": {
+    "id": "usr_abc123",
+    "email": "user@example.com",
+    "display_name": "Jane Doe",
+    "status": "active"
+  }
+}
+```
+
+---
+
+## Workspace Endpoints
+
+### List Workspaces
+
+List all workspaces the user is a member of.
+
+**Endpoint:** `GET /api/v1/workspaces`
+
+**Authentication:** Required
+
+**Response:** `200 OK`
+
+```json
+{
+  "workspaces": [
+    {
+      "id": "ws_xyz789",
+      "name": "My Company",
+      "company_name": "Acme Corp",
+      "address": "123 Main St",
+      "phone": "+1-555-0100",
+      "created_at": "2024-01-10T08:00:00Z",
+      "updated_at": "2024-01-10T08:00:00Z"
+    }
+  ]
+}
+```
+
+### Create Workspace
+
+Create a new workspace.
+
+**Endpoint:** `POST /api/v1/workspaces`
+
+**Authentication:** Required
+
+**Request Body:**
+
+```json
+{
+  "name": "My Company",
+  "company_name": "Acme Corp",
+  "address": "123 Main St",
+  "phone": "+1-555-0100"
+}
+```
+
+**Response:** `201 Created`
+
+```json
+{
+  "workspace": {
+    "id": "ws_xyz789",
+    "name": "My Company",
+    "company_name": "Acme Corp",
+    "address": "123 Main St",
+    "phone": "+1-555-0100"
+  }
+}
+```
+
+**Notes:**
+- The creator becomes the workspace owner automatically
+
+### Get Workspace
+
+Get details of a specific workspace.
+
+**Endpoint:** `GET /api/v1/workspaces/:id`
+
+**Authentication:** Required
+
+**Authorization:** Member+
+
+**Response:** `200 OK`
+
+```json
+{
+  "workspace": {
+    "id": "ws_xyz789",
+    "name": "My Company",
+    "company_name": "Acme Corp",
+    "address": "123 Main St",
+    "phone": "+1-555-0100"
+  }
+}
+```
+
+### Update Workspace
+
+Update workspace details.
+
+**Endpoint:** `PUT /api/v1/workspaces/:id`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Request Body:**
+
+```json
+{
+  "name": "Updated Name",
+  "company_name": "New Corp Name",
+  "address": "456 Oak Ave",
+  "phone": "+1-555-0200"
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "workspace": { /* updated workspace */ }
+}
+```
+
+### Delete Workspace
+
+Delete a workspace permanently.
+
+**Endpoint:** `DELETE /api/v1/workspaces/:id`
+
+**Authentication:** Required
+
+**Authorization:** Owner only
+
+**Response:** `200 OK`
+
+```json
+{
+  "message": "Workspace deleted"
+}
+```
+
+### List Workspace Members
+
+Get all members of a workspace.
+
+**Endpoint:** `GET /api/v1/workspaces/:id/members`
+
+**Authentication:** Required
+
+**Authorization:** Member+
+
+**Response:** `200 OK`
+
+```json
+{
+  "members": [
+    {
+      "id": "wm_mem123",
+      "workspace_id": "ws_xyz789",
+      "user_id": "usr_abc123",
+      "role": "owner",
+      "user": {
+        "email": "owner@example.com",
+        "display_name": "Owner Name"
+      }
+    }
+  ]
+}
+```
+
+### Update Member Role
+
+Change a member's role in the workspace.
+
+**Endpoint:** `PUT /api/v1/workspaces/:wsId/members/:memberId/role`
+
+**Authentication:** Required
+
+**Authorization:** Admin+ (cannot change owner role)
+
+**Request Body:**
+
+```json
+{
+  "role": "admin"
+}
+```
+
+**Valid roles:** `owner`, `admin`, `member`, `guest`
+
+**Response:** `200 OK`
+
+```json
+{
+  "member": { /* updated member */ }
+}
+```
+
+### Remove Member
+
+Remove a member from the workspace.
+
+**Endpoint:** `DELETE /api/v1/workspaces/:wsId/members/:memberId`
+
+**Authentication:** Required
+
+**Authorization:** Admin+ (cannot remove owner)
+
+**Response:** `200 OK`
+
+```json
+{
+  "message": "Member removed"
+}
+```
+
+---
+
+## Invitation Endpoints
+
+### Create Invitation
+
+Invite a user to join a workspace.
+
+**Endpoint:** `POST /api/v1/workspaces/:id/invitations`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Request Body:**
+
+```json
+{
+  "email": "newuser@example.com",
+  "role": "member"
+}
+```
+
+**Response:** `201 Created`
+
+```json
+{
+  "invitation": {
+    "id": "inv_token123",
+    "workspace_id": "ws_xyz789",
+    "email": "newuser@example.com",
+    "role": "member",
+    "token": "secure-token-here",
+    "status": "pending"
+  }
+}
+```
+
+**Notes:**
+- If SMTP is configured, an invitation email will be sent
+
+### List Workspace Invitations
+
+Get all pending invitations for a workspace.
+
+**Endpoint:** `GET /api/v1/workspaces/:id/invitations`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Response:** `200 OK`
+
+```json
+{
+  "invitations": [
+    {
+      "id": "inv_token123",
+      "workspace_id": "ws_xyz789",
+      "email": "newuser@example.com",
+      "role": "member",
+      "status": "pending"
+    }
+  ]
+}
+```
+
+### Cancel Invitation
+
+Cancel a pending invitation.
+
+**Endpoint:** `DELETE /api/v1/workspaces/:wsId/invitations/:invId`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Response:** `200 OK`
+
+```json
+{
+  "message": "Invitation cancelled"
+}
+```
+
+### List My Pending Invitations
+
+Get all pending invitations for the authenticated user.
+
+**Endpoint:** `GET /api/v1/invitations/pending`
+
+**Authentication:** Required
+
+**Response:** `200 OK`
+
+```json
+{
+  "invitations": [
+    {
+      "id": "inv_token123",
+      "workspace_id": "ws_xyz789",
+      "email": "user@example.com",
+      "role": "member",
+      "status": "pending",
+      "workspace": {
+        "name": "Company Name"
+      }
+    }
+  ]
+}
+```
+
+### Accept Invitation
+
+Accept a workspace invitation.
+
+**Endpoint:** `POST /api/v1/invitations/:id/accept`
+
+**Authentication:** Required
+
+**Response:** `200 OK`
+
+```json
+{
+  "message": "Invitation accepted",
+  "workspace_id": "ws_xyz789"
+}
+```
+
+### Decline Invitation
+
+Decline a workspace invitation.
+
+**Endpoint:** `POST /api/v1/invitations/:id/decline`
+
+**Authentication:** Required
+
+**Response:** `200 OK`
+
+```json
+{
+  "message": "Invitation declined"
+}
+```
+
+---
+
+## Assistant Endpoints
+
+AI voice assistant management.
+
+### List Assistants
+
+List all assistants in a workspace.
+
+**Endpoint:** `GET /api/v1/workspaces/:id/assistants`
+
+**Authentication:** Required
+
+**Authorization:** Member+
+
+**Response:** `200 OK`
+
+```json
+{
+  "assistants": [
+    {
+      "id": "ast_ai123",
+      "workspace_id": "ws_xyz789",
+      "name": "Support Bot",
+      "phone_number": "+1-555-0300",
+      "instructions": "You are a helpful assistant...",
+      "callerai_id": "callerai_ext_id",
+      "status": "active"
+    }
+  ]
+}
+```
+
+### Create Assistant
+
+Create a new AI assistant.
+
+**Endpoint:** `POST /api/v1/workspaces/:id/assistants`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Request Body:**
+
+```json
+{
+  "name": "Support Bot",
+  "phone_number": "+1-555-0300",
+  "instructions": "You are a helpful customer support assistant for Acme Corp...",
+  "voice": "en-US-Neural2-J",
+  "provider": "twilio",
+  "provider_config": {
+    "account_sid": "AC...",
+    "auth_token": "..."
+  }
+}
+```
+
+**Response:** `201 Created`
+
+```json
+{
+  "assistant": {
+    "id": "ast_ai123",
+    "workspace_id": "ws_xyz789",
+    "name": "Support Bot",
+    "phone_number": "+1-555-0300",
+    "callerai_id": "callerai_ext_id",
+    "status": "active"
+  }
+}
+```
+
+### Get Assistant
+
+Get details of a specific assistant.
+
+**Endpoint:** `GET /api/v1/workspaces/:wsId/assistants/:id`
+
+**Authentication:** Required
+
+**Authorization:** Member+
+
+**Response:** `200 OK`
+
+```json
+{
+  "assistant": { /* assistant object */ }
+}
+```
+
+### Update Assistant
+
+Update assistant configuration.
+
+**Endpoint:** `PUT /api/v1/workspaces/:wsId/assistants/:id`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Request Body:**
+
+```json
+{
+  "name": "Updated Name",
+  "instructions": "New instructions...",
+  "status": "active"
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "assistant": { /* updated assistant */ }
+}
+```
+
+### Update Assistant Voice
+
+Update assistant voice settings.
+
+**Endpoint:** `PUT /api/v1/workspaces/:wsId/assistants/:id/voice`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Request Body:**
+
+```json
+{
+  "voice": "en-US-Neural2-C",
+  "language": "en-US"
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "assistant": { /* updated assistant */ }
+}
+```
+
+### Delete Assistant
+
+Delete an assistant.
+
+**Endpoint:** `DELETE /api/v1/workspaces/:wsId/assistants/:id`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Response:** `200 OK`
+
+```json
+{
+  "message": "Assistant deleted"
+}
+```
+
+### Get Available Phone Numbers
+
+Get available phone numbers from CallerAI.
+
+**Endpoint:** `GET /api/v1/callerai/phone-numbers`
+
+**Authentication:** Required
+
+**Query Parameters:**
+- `country_code`: ISO country code (e.g., "US")
+
+**Response:** `200 OK`
+
+```json
+{
+  "phone_numbers": [
+    {
+      "number": "+1-555-0100",
+      "friendly_name": "+1 (555) 010-0100",
+      "capabilities": ["voice", "sms"]
+    }
+  ]
+}
+```
+
+### Get Available Voices
+
+Get available voices for a language.
+
+**Endpoint:** `GET /api/v1/callerai/voices/:language`
+
+**Authentication:** Required
+
+**Path Parameters:**
+- `language`: Language code (e.g., "en-US")
+
+**Response:** `200 OK`
+
+```json
+{
+  "voices": [
+    {
+      "id": "en-US-Neural2-J",
+      "name": "English (US) - Neural2 J",
+      "gender": "male"
+    }
+  ]
+}
+```
+
+### Get Provider Configurations
+
+Get available telephony provider configurations.
+
+**Endpoint:** `GET /api/v1/callerai/provider-configs`
+
+**Authentication:** Required
+
+**Response:** `200 OK`
+
+```json
+{
+  "providers": [
+    {
+      "id": "twilio",
+      "name": "Twilio",
+      "fields": [
+        {"name": "account_sid", "type": "string", "required": true},
+        {"name": "auth_token", "type": "password", "required": true}
+      ]
+    }
+  ]
+}
+```
+
+---
+
+## Calendar Endpoints
+
+### List Calendars
+
+List all calendars in a workspace.
+
+**Endpoint:** `GET /api/v1/workspaces/:id/calendars`
+
+**Authentication:** Required
+
+**Authorization:** Member+
+
+**Response:** `200 OK`
+
+```json
+{
+  "calendars": [
+    {
+      "id": "cal_cal123",
+      "workspace_id": "ws_xyz789",
+      "name": "Support Calendar",
+      "assistant_id": "ast_ai123"
+    }
+  ]
+}
+```
+
+### Create Calendar
+
+Create a new calendar.
+
+**Endpoint:** `POST /api/v1/workspaces/:id/calendars`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Request Body:**
+
+```json
+{
+  "name": "Support Calendar",
+  "assistant_id": "ast_ai123"
+}
+```
+
+**Response:** `201 Created`
+
+```json
+{
+  "calendar": {
+    "id": "cal_cal123",
+    "workspace_id": "ws_xyz789",
+    "name": "Support Calendar",
+    "assistant_id": "ast_ai123"
+  }
+}
+```
+
+### Get Calendar
+
+Get calendar details.
+
+**Endpoint:** `GET /api/v1/workspaces/:wsId/calendars/:id`
+
+**Authentication:** Required
+
+**Authorization:** Member+
+
+**Response:** `200 OK`
+
+```json
+{
+  "calendar": { /* calendar object */ }
+}
+```
+
+### Update Calendar
+
+Update calendar details.
+
+**Endpoint:** `PUT /api/v1/workspaces/:wsId/calendars/:id`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Request Body:**
+
+```json
+{
+  "name": "Updated Calendar Name",
+  "assistant_id": "ast_ai456"
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "calendar": { /* updated calendar */ }
+}
+```
+
+### Delete Calendar
+
+Delete a calendar.
+
+**Endpoint:** `DELETE /api/v1/workspaces/:wsId/calendars/:id`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Response:** `200 OK`
+
+```json
+{
+  "message": "Calendar deleted"
+}
+```
+
+---
+
+## Time Slot Endpoints
+
+### List Time Slots
+
+Get all time slots for a calendar.
+
+**Endpoint:** `GET /api/v1/calendars/:id/time-slots`
+
+**Authentication:** Required
+
+**Response:** `200 OK`
+
+```json
+{
+  "time_slots": [
+    {
+      "id": "ts_slot123",
+      "calendar_id": "cal_cal123",
+      "day_of_week": 1,
+      "start_time": "09:00",
+      "end_time": "17:00"
+    }
+  ]
+}
+```
+
+**Note:** `day_of_week`: 0=Sunday, 1=Monday, ..., 6=Saturday
+
+### Create Time Slot
+
+Add a time slot to a calendar.
+
+**Endpoint:** `POST /api/v1/calendars/:id/time-slots`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Request Body:**
+
+```json
+{
+  "day_of_week": 1,
+  "start_time": "09:00",
+  "end_time": "17:00"
+}
+```
+
+**Response:** `201 Created`
+
+```json
+{
+  "time_slot": {
+    "id": "ts_slot123",
+    "calendar_id": "cal_cal123",
+    "day_of_week": 1,
+    "start_time": "09:00",
+    "end_time": "17:00"
+  }
+}
+```
+
+### Update Time Slot
+
+Update a time slot.
+
+**Endpoint:** `PUT /api/v1/calendars/:calId/time-slots/:id`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Request Body:**
+
+```json
+{
+  "day_of_week": 2,
+  "start_time": "10:00",
+  "end_time": "18:00"
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "time_slot": { /* updated time slot */ }
+}
+```
+
+### Delete Time Slot
+
+Remove a time slot.
+
+**Endpoint:** `DELETE /api/v1/calendars/:calId/time-slots/:id`
+
+**Authentication:** Required
+
+**Authorization:** Admin+
+
+**Response:** `200 OK`
+
+```json
+{
+  "message": "Time slot deleted"
+}
+```
+
+### Get Available Slots
+
+Get available appointment slots for a date range.
+
+**Endpoint:** `GET /api/v1/calendars/:id/available-slots`
+
+**Authentication:** Not required (public endpoint)
+
+**Query Parameters:**
+- `start_date`: Start date (YYYY-MM-DD)
+- `end_date`: End date (YYYY-MM-DD)
+- `duration_minutes`: Appointment duration (default: 30)
+
+**Response:** `200 OK`
+
+```json
+{
+  "available_slots": [
+    {
+      "date": "2024-01-20",
+      "start_time": "09:00",
+      "end_time": "09:30"
+    }
+  ]
+}
+```
+
+---
+
+## Appointment Endpoints
+
+### List Workspace Appointments
+
+List all appointments in a workspace.
+
+**Endpoint:** `GET /api/v1/workspaces/:id/appointments`
+
+**Authentication:** Required
+
+**Authorization:** Member+
+
+**Query Parameters:**
+- `start_date`: Filter by start date (YYYY-MM-DD)
+- `end_date`: Filter by end date (YYYY-MM-DD)
+- `status`: Filter by status (pending, confirmed, cancelled)
+
+**Response:** `200 OK`
+
+```json
+{
+  "appointments": [
+    {
+      "id": "apt_appt123",
+      "calendar_id": "cal_cal123",
+      "start_time": "2024-01-20T09:00:00Z",
+      "end_time": "2024-01-20T09:30:00Z",
+      "customer_name": "John Smith",
+      "customer_phone": "+1-555-1234",
+      "customer_email": "john@example.com",
+      "notes": "Consultation call",
+      "status": "confirmed"
+    }
+  ]
+}
+```
+
+### Create Appointment
+
+Book a new appointment.
+
+**Endpoint:** `POST /api/v1/calendars/:id/appointments`
+
+**Authentication:** Not required (public endpoint for customer booking)
+
+**Request Body:**
+
+```json
+{
+  "start_time": "2024-01-20T09:00:00Z",
+  "end_time": "2024-01-20T09:30:00Z",
+  "customer_name": "John Smith",
+  "customer_phone": "+1-555-1234",
+  "customer_email": "john@example.com",
+  "notes": "Need help with product setup"
+}
+```
+
+**Response:** `201 Created`
+
+```json
+{
+  "appointment": {
+    "id": "apt_appt123",
+    "calendar_id": "cal_cal123",
+    "start_time": "2024-01-20T09:00:00Z",
+    "end_time": "2024-01-20T09:30:00Z",
+    "customer_name": "John Smith",
+    "status": "pending"
+  }
+}
+```
+
+### Cancel Appointment
+
+Cancel an existing appointment.
+
+**Endpoint:** `PUT /api/v1/appointments/:id/cancel`
+
+**Authentication:** Not required (public endpoint)
+
+**Response:** `200 OK`
+
+```json
+{
+  "appointment": {
+    "id": "apt_appt123",
+    "status": "cancelled"
+  }
+}
+```
+
+---
+
+## Settings Endpoints
+
+### Get Global Settings
+
+Get global platform settings.
+
+**Endpoint:** `GET /api/v1/settings`
+
+**Authentication:** Required
+
+**Response:** `200 OK`
+
+```json
+{
+  "settings": {
+    "smtp_configured": true,
+    "callerai_configured": true,
+    "registration_enabled": true
+  }
+}
+```
+
+### Update Global Settings
+
+Update platform settings.
+
+**Endpoint:** `PUT /api/v1/settings`
+
+**Authentication:** Required
+
+**Authorization:** System admin (future feature)
+
+**Request Body:**
+
+```json
+{
+  "registration_enabled": false
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "settings": { /* updated settings */ }
+}
+```
+
+### Test SMTP Configuration
+
+Test SMTP email sending.
+
+**Endpoint:** `POST /api/v1/settings/test-smtp`
+
+**Authentication:** Required
+
+**Request Body:**
+
+```json
+{
+  "to_email": "test@example.com"
+}
+```
+
+**Response:** `200 OK`
+
+```json
+{
+  "success": true,
+  "message": "Test email sent successfully"
+}
+```
+
+### Test CallerAI Configuration
+
+Test CallerAI API connection.
+
+**Endpoint:** `POST /api/v1/settings/test-callerai`
+
+**Authentication:** Required
+
+**Response:** `200 OK`
+
+```json
+{
+  "success": true,
+  "message": "CallerAI connection successful"
+}
+```
+
+---
+
+## Data Models
+
+### User Object
+
+```json
+{
+  "id": "usr_abc123",
+  "email": "user@example.com",
+  "display_name": "John Doe",
+  "status": "active",
+  "created_at": "2024-01-15T10:30:00Z",
+  "updated_at": "2024-01-15T10:30:00Z"
+}
+```
+
+### Workspace Object
+
+```json
+{
+  "id": "ws_xyz789",
+  "name": "My Company",
+  "company_name": "Acme Corp",
+  "address": "123 Main St",
+  "phone": "+1-555-0100",
+  "created_at": "2024-01-10T08:00:00Z",
+  "updated_at": "2024-01-10T08:00:00Z"
+}
+```
+
+### Role Hierarchy
+
+From highest to lowest permission:
+
+1. **Owner**: Full control, can delete workspace, manage all members
+2. **Admin**: Manage members (except owner), assistants, calendars, settings
+3. **Member**: View and use workspace resources, book appointments
+4. **Guest**: Read-only access
+
+---
+
+## Rate Limiting
+
+Rate limiting is configurable and applies per IP address:
+
+- Default: 200 requests per minute
+- Configuration: `rate_limit.requests_per_minute` in config
+
+When rate limited, the API returns:
+
+```
+HTTP 429 Too Many Requests
+{
+  "error": "Rate limit exceeded"
+}
+```
+
+---
+
+## WebSocket Support
+
+WebSocket support is planned for future releases to enable:
+- Real-time appointment notifications
+- Assistant status updates
+- Live call monitoring
+
+---
+
+## Versioning
+
+The API version is included in the URL path (`/api/v1/`). Future versions will maintain backward compatibility or introduce new version paths (e.g., `/api/v2/`).
+
+---
+
+## Additional Notes
+
+### Date/Time Format
+
+All timestamps use ISO 8601 format in UTC:
+- `2024-01-20T09:00:00Z`
+
+### Phone Number Format
+
+Phone numbers should be in E.164 format:
+- `+1-555-0100` (recommended)
+- `+15550100` (also accepted)
+
+### ID Prefixes
+
+Entity IDs use prefixes for easy identification:
+- `usr_`: User
+- `ws_`: Workspace
+- `wm_`: Workspace Member
+- `ast_`: Assistant
+- `cal_`: Calendar
+- `ts_`: Time Slot
+- `apt_`: Appointment
+- `inv_`: Invitation
+- `ses_`: Session
+
+### CORS
+
+CORS is configurable in `config/microbit.json`:
+
+```json
+{
+  "cors": {
+    "enabled": true,
+    "origins": ["*"],
+    "methods": ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
+    "headers": ["Authorization", "Content-Type"]
+  }
+}
+```

+ 578 - 0
docs/ARCHITECTURE.md

@@ -0,0 +1,578 @@
+# Smartbotic Microbit Architecture
+
+This document describes the architecture and design of the Smartbotic Microbit platform.
+
+## System Overview
+
+Smartbotic Microbit is a multi-tier application consisting of three primary components:
+
+```
+┌─────────────────┐
+│   Web Browser   │  (React/TypeScript SPA)
+└────────┬────────┘
+         │ HTTP/REST
+         ▼
+┌─────────────────┐
+│ Microbit Service│  (C++ HTTP Server)
+└────────┬────────┘
+         │ gRPC
+         ▼
+┌─────────────────┐
+│ Database Service│  (Custom Storage Engine)
+└─────────────────┘
+```
+
+## Component Architecture
+
+### 1. Microbit Service (Backend)
+
+The main application server implemented in C++20, providing RESTful API endpoints and business logic.
+
+#### Core Components
+
+**App (`src/app.cpp`)**
+- Main application entry point
+- Manages component lifecycle
+- Initializes all services, stores, and routes
+- HTTP server configuration
+
+**HTTP Layer**
+- Uses `cpp-httplib` for HTTP server
+- RESTful API endpoints organized by feature
+- JWT-based authentication middleware
+- CORS support
+- Request/response handling
+
+#### Module Structure
+
+```
+src/
+├── main.cpp              # Application entry point
+├── app.{hpp,cpp}         # Main app class
+├── routes/               # HTTP route handlers
+│   ├── auth_routes       # Authentication endpoints
+│   ├── user_routes       # User management
+│   ├── workspace_routes  # Workspace CRUD
+│   ├── assistant_routes  # AI assistant management
+│   ├── calendar_routes   # Calendar & appointments
+│   ├── invitation_routes # Team invitations
+│   └── settings_routes   # Settings management
+├── services/             # Business logic layer
+│   ├── auth_service      # Authentication logic
+│   ├── workspace_service # Workspace operations
+│   ├── invitation_service# Invitation workflow
+│   ├── assistant_service # Assistant management
+│   └── calendar_service  # Calendar operations
+└── stores/               # Data access layer
+    ├── user_store        # User data operations
+    ├── workspace_store   # Workspace data
+    ├── assistant_store   # Assistant data
+    ├── calendar_store    # Calendar data
+    ├── invitation_store  # Invitation data
+    └── settings_store    # Settings data
+```
+
+#### Library Modules
+
+```
+lib/
+├── auth/                 # Authentication & authorization
+│   ├── jwt_utils         # JWT token generation/validation
+│   ├── bcrypt_utils      # Password hashing
+│   └── auth_middleware   # Request authentication
+├── common/               # Common utilities
+│   ├── config_loader     # Configuration parsing
+│   ├── logging           # Logging utilities
+│   └── utils             # General utilities
+├── smtp/                 # Email sending
+│   └── smtp_client       # SMTP client implementation
+└── callerai/             # CallerAI integration
+    └── callerai_client   # CallerAI API client
+```
+
+### 2. Database Service
+
+Custom database service providing persistent storage via gRPC interface.
+
+**Location**: `external/smartbotic-database` (git submodule)
+
+**Key Features**:
+- Collection-based storage model
+- Document-oriented (JSON documents)
+- Query and indexing support
+- Migration system
+- gRPC API
+
+**Client Interface**: `smartbotic::database::Client`
+- CRUD operations on collections
+- Query execution
+- Transaction support
+
+### 3. Web UI
+
+Modern single-page application built with React and TypeScript.
+
+```
+webui/
+├── src/
+│   ├── main.tsx          # Application entry point
+│   ├── App.tsx           # Root component & routing
+│   ├── api/              # Backend API client
+│   ├── pages/            # Page components
+│   │   ├── auth/         # Login, Register
+│   │   ├── dashboard/    # Main dashboard
+│   │   ├── members/      # Team member management
+│   │   ├── invitations/  # Invitation management
+│   │   ├── assistants/   # AI assistant pages
+│   │   └── calendar/     # Calendar & appointments
+│   ├── components/       # Reusable UI components
+│   └── stores/           # Client-side state (Zustand)
+├── package.json
+└── vite.config.ts
+```
+
+**Key Technologies**:
+- **React 19**: UI framework
+- **TypeScript**: Type safety
+- **Tailwind CSS**: Styling
+- **React Router**: Client-side routing
+- **TanStack Query**: Server state management
+- **Zustand**: Client state management
+- **Vite**: Build tool and dev server
+
+## Data Model
+
+### Core Entities
+
+**User**
+- `id`: Unique identifier (usr_xxx)
+- `email`: User email (unique)
+- `password_hash`: BCrypt hashed password
+- `display_name`: User's display name
+- `status`: Account status (active, suspended)
+
+**Workspace**
+- `id`: Unique identifier (ws_xxx)
+- `name`: Workspace name
+- `company_name`: Company name
+- `address`: Physical address
+- `phone`: Contact phone number
+
+**WorkspaceMember**
+- `id`: Unique identifier (wm_xxx)
+- `workspace_id`: Reference to workspace
+- `user_id`: Reference to user
+- `role`: Member role (owner, admin, member, guest)
+
+**Assistant** (AI Voice Assistant)
+- `id`: Unique identifier (ast_xxx)
+- `workspace_id`: Owning workspace
+- `name`: Assistant name
+- `phone_number`: Phone number for calls
+- `instructions`: AI behavior instructions
+- `callerai_id`: CallerAI platform ID
+- `status`: Active/inactive status
+
+**Calendar**
+- `id`: Unique identifier (cal_xxx)
+- `workspace_id`: Owning workspace
+- `name`: Calendar name
+- `assistant_id`: Associated assistant (optional)
+
+**TimeSlot**
+- `id`: Unique identifier (ts_xxx)
+- `calendar_id`: Parent calendar
+- `day_of_week`: Day (0=Sunday, 6=Saturday)
+- `start_time`: Slot start time (HH:MM)
+- `end_time`: Slot end time (HH:MM)
+
+**Appointment**
+- `id`: Unique identifier (apt_xxx)
+- `calendar_id`: Associated calendar
+- `start_time`: Appointment start (ISO 8601)
+- `end_time`: Appointment end (ISO 8601)
+- `customer_name`, `customer_phone`, `customer_email`: Customer info
+- `notes`: Appointment notes
+- `status`: pending, confirmed, cancelled
+
+**Invitation**
+- `id`: Unique identifier (inv_xxx)
+- `workspace_id`: Target workspace
+- `email`: Invitee email
+- `role`: Intended role
+- `token`: Unique invitation token
+- `status`: pending, accepted, rejected
+
+**Session**
+- `id`: Unique identifier (ses_xxx)
+- `user_id`: Associated user
+- Used for refresh token validation
+
+## Authentication & Authorization
+
+### Authentication Flow
+
+1. **Registration**: `POST /api/v1/auth/register`
+   - Validate password policy
+   - Hash password with BCrypt
+   - Create user record
+   - Create session
+   - Return JWT tokens (access + refresh)
+
+2. **Login**: `POST /api/v1/auth/login`
+   - Validate credentials
+   - Delete old sessions
+   - Create new session
+   - Return JWT tokens
+
+3. **Token Refresh**: `POST /api/v1/auth/refresh`
+   - Validate refresh token
+   - Check session validity
+   - Issue new access token
+
+### Authorization Model
+
+**JWT Claims**:
+- `sub`: User ID
+- `email`: User email
+- `role`: Global role (currently "user")
+- `exp`: Expiration timestamp
+
+**Workspace Roles** (per workspace):
+- **Owner**: Full control, can delete workspace
+- **Admin**: Manage members, assistants, calendars
+- **Member**: View and use workspace resources
+- **Guest**: Read-only access
+
+**Role Hierarchy**:
+```
+Owner > Admin > Member > Guest
+```
+
+### Middleware Flow
+
+```
+Request → Auth Middleware → Route Handler
+           │
+           ├─ Extract JWT from Authorization header
+           ├─ Validate token signature
+           ├─ Check expiration
+           ├─ Store AuthContext (user_id, email, role)
+           └─ Continue or reject (401)
+```
+
+Route handlers check workspace membership and roles as needed.
+
+## Configuration System
+
+### Configuration File Structure
+
+JSON-based configuration with environment variable substitution:
+
+```json
+{
+  "database": {
+    "rpc_address": "${DB_ADDRESS:localhost:9004}"
+  },
+  "auth": {
+    "jwt_secret": "${JWT_SECRET:change-me-in-production}"
+  }
+}
+```
+
+**Syntax**: `${VAR_NAME:default_value}`
+
+### Configuration Loading
+
+`ConfigLoader` class:
+- Loads JSON configuration file
+- Resolves environment variables at runtime
+- Provides type-safe getters with defaults
+
+### Configuration Files
+
+- **Development**: `config/microbit.json`
+- **Production**: `/etc/smartbotic/microbit.json`
+- **Environment**: `/etc/smartbotic/smartbotic.env` (sourced by systemd)
+
+## External Integrations
+
+### CallerAI Integration
+
+**Purpose**: Create and manage AI-powered voice assistants
+
+**Client**: `callerai::CallerAIClient`
+
+**Operations**:
+- Create assistant with phone number
+- Update assistant configuration
+- Delete assistant
+- List assistants
+
+**Configuration**:
+- `callerai.api_url`: CallerAI API endpoint
+- `callerai.api_key`: API authentication key
+- `callerai.timeout_sec`: Request timeout
+
+### SMTP Integration
+
+**Purpose**: Send email notifications (invitations, etc.)
+
+**Client**: `smtp::SmtpClient`
+
+**Operations**:
+- Send invitation emails
+- Configurable templates
+
+**Configuration**:
+- `smtp.host`: SMTP server hostname
+- `smtp.port`: SMTP server port (default 587)
+- `smtp.username`: SMTP authentication username
+- `smtp.password`: SMTP authentication password
+- `smtp.from_address`: Sender email address
+- `smtp.use_tls`: Enable TLS (recommended)
+
+## HTTP Server Architecture
+
+### Request Flow
+
+```
+HTTP Request
+    │
+    ├─ CORS Middleware (if enabled)
+    │    └─ Add CORS headers
+    │
+    ├─ Rate Limiting (if enabled)
+    │    └─ Check request count
+    │
+    ├─ Auth Middleware (protected routes)
+    │    └─ Validate JWT token
+    │
+    └─ Route Handler
+         ├─ Parse request body
+         ├─ Validate input
+         ├─ Check authorization (workspace roles)
+         ├─ Call service layer
+         ├─ Access data via stores
+         └─ Return JSON response
+```
+
+### Error Handling
+
+Standard error responses:
+
+```json
+{
+  "error": "Error message"
+}
+```
+
+HTTP Status Codes:
+- `200` OK - Success
+- `201` Created - Resource created
+- `400` Bad Request - Invalid input
+- `401` Unauthorized - Missing/invalid token
+- `403` Forbidden - Insufficient permissions
+- `404` Not Found - Resource not found
+- `500` Internal Server Error - Server error
+
+### Static File Serving
+
+The HTTP server can serve the WebUI static files:
+
+```json
+{
+  "http": {
+    "static_files": {
+      "enabled": true,
+      "path": "webui/dist"
+    }
+  }
+}
+```
+
+When enabled, all non-API routes serve static files from the configured path.
+
+## Build System
+
+### CMake Structure
+
+```
+CMakeLists.txt              # Root build configuration
+├── cmake/
+│   ├── CompilerFlags.cmake # Compiler settings
+│   ├── FindPackages.cmake  # External package detection
+│   └── Dependencies.cmake  # Dependency management
+├── lib/CMakeLists.txt      # Library builds
+│   ├── auth/
+│   ├── common/
+│   ├── smtp/
+│   └── callerai/
+└── src/CMakeLists.txt      # Main application build
+```
+
+### Build Options
+
+- `CMAKE_BUILD_TYPE`: Release|Debug (default: Release)
+- `BUILD_TESTS`: Build tests (default: OFF)
+- `BUNDLE_DATABASE`: Include database service in build (default: OFF)
+
+### Dependencies
+
+**System Libraries**:
+- OpenSSL (libssl-dev)
+- gRPC and Protobuf
+- Abseil (from gRPC/Protobuf)
+
+**Bundled Libraries** (via CMake FetchContent):
+- cpp-httplib
+- nlohmann/json
+- spdlog
+- jwt-cpp
+- bcrypt (custom implementation)
+
+## Deployment Architecture
+
+### Systemd Services
+
+Two systemd services run the platform:
+
+1. **smartbotic-database.service**
+   - Runs the database service
+   - Port: 9004 (gRPC)
+   - Data: `/var/lib/smartbotic/database/`
+
+2. **smartbotic-microbit.service**
+   - Runs the main application
+   - Port: 8090 (HTTP)
+   - Depends on database service
+
+### File System Layout
+
+```
+/opt/smartbotic/
+├── bin/
+│   ├── smartbotic-database
+│   └── smartbotic-microbit
+└── share/smartbotic/
+    └── nginx/
+        └── smartbotic.conf.template
+
+/etc/smartbotic/
+├── database.json
+├── microbit.json
+└── smartbotic.env
+
+/var/lib/smartbotic/
+├── database/
+│   ├── storage/
+│   └── migrations/
+└── microbit/
+    └── webui/
+
+/var/log/smartbotic/
+├── database.log
+└── microbit.log
+```
+
+### Nginx Reverse Proxy (Optional)
+
+```
+Browser → Nginx (443) → Microbit Service (8090)
+```
+
+Nginx provides:
+- TLS termination
+- Reverse proxy to backend
+- Static file serving (WebUI)
+- Request logging
+
+Configuration template: `packaging/nginx/smartbotic.conf.template`
+
+## Security Considerations
+
+### Password Security
+- BCrypt hashing with salt
+- Configurable password policy (minimum length, character requirements)
+- Passwords never logged or returned in responses
+
+### Token Security
+- JWT with HMAC-SHA256 signature
+- Short-lived access tokens (default: 15 minutes)
+- Long-lived refresh tokens (default: 7 days)
+- Refresh tokens tied to sessions (revocable)
+
+### API Security
+- All protected endpoints require valid JWT
+- Workspace operations check membership
+- Role-based authorization enforced
+- Rate limiting available
+
+### Configuration Security
+- Sensitive values via environment variables
+- Config files readable only by service user
+- Database connections over localhost or private network
+
+## Logging
+
+### Logging Framework: spdlog
+
+**Log Levels**:
+- `trace`: Detailed debug information
+- `debug`: Debug information
+- `info`: General information (default)
+- `warn`: Warning messages
+- `error`: Error conditions
+- `critical`: Critical errors
+
+**Configuration**: `log_level` in config file
+
+**Output**:
+- Development: Console output
+- Production: File output (`/var/log/smartbotic/microbit.log`)
+
+## Performance Considerations
+
+### Database Access
+- Connection pooling (managed by database client)
+- Efficient queries with indexes
+- Minimal round-trips per request
+
+### HTTP Server
+- Single-threaded event loop (cpp-httplib)
+- Non-blocking I/O where possible
+- Keep-alive connections supported
+
+### Caching
+- JWT validation caching (implicit in middleware)
+- No application-level caching currently implemented
+
+### Rate Limiting
+- In-memory rate limiting per IP
+- Configurable limits: `rate_limit.requests_per_minute`
+
+## Future Considerations
+
+### Scalability
+- Horizontal scaling requires session store (Redis)
+- Database service already supports clustering
+- Load balancing via Nginx
+
+### Monitoring
+- Prometheus metrics endpoint (planned)
+- Health check endpoints
+- Performance metrics
+
+### Testing
+- Unit tests (planned: `BUILD_TESTS`)
+- Integration tests
+- API endpoint tests
+
+## Conclusion
+
+The Smartbotic Microbit platform follows a layered architecture with clear separation of concerns:
+- **Routes**: HTTP request handling
+- **Services**: Business logic
+- **Stores**: Data access
+
+This design promotes maintainability, testability, and extensibility while providing a robust foundation for workspace management and AI assistant deployment.

+ 823 - 0
docs/DEPLOYMENT.md

@@ -0,0 +1,823 @@
+# Deployment Guide
+
+This guide covers deploying Smartbotic Microbit in production environments.
+
+## Table of Contents
+
+- [System Requirements](#system-requirements)
+- [Installation Methods](#installation-methods)
+- [Configuration](#configuration)
+- [Service Management](#service-management)
+- [Nginx Setup](#nginx-setup)
+- [Security Considerations](#security-considerations)
+- [Monitoring and Logs](#monitoring-and-logs)
+- [Backup and Recovery](#backup-and-recovery)
+- [Troubleshooting](#troubleshooting)
+- [Upgrading](#upgrading)
+
+## System Requirements
+
+### Hardware Requirements
+
+**Minimum:**
+- CPU: 2 cores
+- RAM: 2 GB
+- Disk: 10 GB free space
+- Network: Stable internet connection
+
+**Recommended:**
+- CPU: 4 cores
+- RAM: 4 GB
+- Disk: 20 GB SSD
+- Network: 100 Mbps+
+
+### Software Requirements
+
+**Operating System:**
+- Debian 12 (Bookworm) - recommended
+- Ubuntu 22.04 LTS or later
+- Other Linux distributions (may require adjustments)
+
+**System Packages:**
+- systemd (for service management)
+- Nginx or Apache (for reverse proxy)
+- OpenSSL (for TLS)
+
+## Installation Methods
+
+### Method 1: Using Pre-built Packages (Recommended)
+
+This is the easiest method for production deployment.
+
+#### Step 1: Download Packages
+
+Download the latest release packages:
+- `smartbotic-database-*.tar.gz`
+- `smartbotic-microbit-*.tar.gz`
+
+```bash
+# Example download (replace with actual URLs)
+wget https://releases.smartbotics.ai/smartbotic-database-0.1.0-debian12.tar.gz
+wget https://releases.smartbotics.ai/smartbotic-microbit-0.1.0-debian12.tar.gz
+```
+
+#### Step 2: Run Installer
+
+```bash
+# Install both packages
+sudo ./packaging/scripts/install.sh smartbotic-*.tar.gz
+
+# Or for verbose output
+sudo ./packaging/scripts/install.sh -v smartbotic-*.tar.gz
+```
+
+**Installer Options:**
+- `--prefix DIR`: Install location (default: `/opt/smartbotic`)
+- `--confdir DIR`: Config directory (default: `/etc/smartbotic`)
+- `--user USER`: Service user (default: `smartbotic`)
+- `--no-systemd`: Skip systemd service installation
+- `--dry-run`: Show what would be done without making changes
+- `-v, --verbose`: Show detailed output
+
+#### Step 3: Directory Structure
+
+After installation:
+
+```
+/opt/smartbotic/
+├── bin/
+│   ├── smartbotic-database
+│   └── smartbotic-microbit
+└── share/smartbotic/
+    └── nginx/
+
+/etc/smartbotic/
+├── database.json
+├── microbit.json
+└── smartbotic.env.default
+
+/var/lib/smartbotic/
+├── database/
+│   ├── storage/
+│   └── migrations/
+└── microbit/
+    └── webui/
+
+/var/log/smartbotic/
+├── database.log
+└── microbit.log
+```
+
+### Method 2: Building from Source
+
+For custom builds or development deployment, see [DEVELOPMENT.md](DEVELOPMENT.md).
+
+## Configuration
+
+### Environment Configuration
+
+Create the main environment file:
+
+```bash
+sudo cp /etc/smartbotic/smartbotic.env.default /etc/smartbotic/smartbotic.env
+sudo chmod 640 /etc/smartbotic/smartbotic.env
+sudo chown root:smartbotic /etc/smartbotic/smartbotic.env
+sudo nano /etc/smartbotic/smartbotic.env
+```
+
+**Required settings in `/etc/smartbotic/smartbotic.env`:**
+
+```bash
+# JWT Secret (REQUIRED - generate a strong random secret)
+JWT_SECRET="your-secret-key-change-this-to-random-string"
+
+# Database connection
+DB_ADDRESS="localhost:9004"
+
+# SMTP Settings (for email notifications)
+SMTP_HOST="smtp.example.com"
+SMTP_PORT="587"
+SMTP_USER="noreply@example.com"
+SMTP_PASSWORD="smtp-password"
+SMTP_FROM="noreply@example.com"
+
+# CallerAI Integration (for AI assistants)
+CALLERAI_API_URL="https://api.caller.ai"
+CALLERAI_API_KEY="your-callerai-api-key"
+
+# WebUI Path
+WEBUI_PATH="/var/lib/smartbotic/microbit/webui"
+```
+
+**Generating a secure JWT secret:**
+
+```bash
+# Generate a random 64-character secret
+openssl rand -hex 32
+```
+
+### Database Configuration
+
+Edit `/etc/smartbotic/database.json` if needed:
+
+```json
+{
+  "log_level": "info",
+  "grpc": {
+    "bind_address": "127.0.0.1",
+    "port": 9004
+  },
+  "storage": {
+    "path": "/var/lib/smartbotic/database/storage",
+    "migrations_path": "/var/lib/smartbotic/database/migrations"
+  }
+}
+```
+
+**Important:**
+- Keep `bind_address` as `127.0.0.1` for security (database should not be exposed)
+- Ensure storage paths exist and are writable by `smartbotic` user
+
+### Microbit Service Configuration
+
+Edit `/etc/smartbotic/microbit.json`:
+
+```json
+{
+  "log_level": "info",
+  "database": {
+    "rpc_address": "${DB_ADDRESS:localhost:9004}",
+    "timeout_ms": 5000,
+    "max_retries": 3
+  },
+  "http": {
+    "bind_address": "127.0.0.1",
+    "port": 8090,
+    "static_files": {
+      "enabled": true,
+      "path": "${WEBUI_PATH:/var/lib/smartbotic/microbit/webui}"
+    }
+  },
+  "auth": {
+    "enabled": true,
+    "jwt_secret": "${JWT_SECRET:change-me-in-production}",
+    "access_token_lifetime_sec": 900,
+    "refresh_token_lifetime_sec": 604800,
+    "password_policy": {
+      "min_length": 8,
+      "require_number": true,
+      "require_special": false
+    }
+  },
+  "smtp": {
+    "host": "${SMTP_HOST:}",
+    "port": "${SMTP_PORT:587}",
+    "username": "${SMTP_USER:}",
+    "password": "${SMTP_PASSWORD:}",
+    "from_address": "${SMTP_FROM:noreply@smartbotics.ai}",
+    "from_name": "Smartbotic",
+    "use_tls": true
+  },
+  "callerai": {
+    "api_url": "${CALLERAI_API_URL:http://localhost:8080}",
+    "api_key": "${CALLERAI_API_KEY:}",
+    "timeout_sec": 30
+  },
+  "cors": {
+    "enabled": true,
+    "origins": ["*"],
+    "methods": ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
+    "headers": ["Authorization", "Content-Type", "X-Requested-With"]
+  },
+  "rate_limit": {
+    "enabled": true,
+    "requests_per_minute": 200
+  }
+}
+```
+
+**Production Settings:**
+- Set `http.bind_address` to `127.0.0.1` (use Nginx for external access)
+- Adjust `rate_limit.requests_per_minute` based on expected traffic
+- Configure `cors.origins` to specific domains for security
+
+## Service Management
+
+### Systemd Services
+
+Two systemd services are installed:
+
+1. **smartbotic-database.service**: Database service
+2. **smartbotic-microbit.service**: Main application service
+
+#### Enable Services
+
+```bash
+# Enable services to start on boot
+sudo systemctl enable smartbotic-database
+sudo systemctl enable smartbotic-microbit
+```
+
+#### Start Services
+
+```bash
+# Start database first
+sudo systemctl start smartbotic-database
+
+# Wait a moment, then start microbit
+sleep 2
+sudo systemctl start smartbotic-microbit
+```
+
+Or start both:
+
+```bash
+sudo systemctl start smartbotic-database smartbotic-microbit
+```
+
+#### Check Status
+
+```bash
+# Check service status
+sudo systemctl status smartbotic-database
+sudo systemctl status smartbotic-microbit
+
+# View recent logs
+sudo journalctl -u smartbotic-database -n 50 --no-pager
+sudo journalctl -u smartbotic-microbit -n 50 --no-pager
+
+# Follow logs in real-time
+sudo journalctl -u smartbotic-microbit -f
+```
+
+#### Stop Services
+
+```bash
+sudo systemctl stop smartbotic-microbit
+sudo systemctl stop smartbotic-database
+```
+
+#### Restart Services
+
+```bash
+# After configuration changes
+sudo systemctl restart smartbotic-microbit
+
+# Or restart both
+sudo systemctl restart smartbotic-database smartbotic-microbit
+```
+
+### Service Configuration Files
+
+Service files are located at:
+- `/etc/systemd/system/smartbotic-database.service`
+- `/etc/systemd/system/smartbotic-microbit.service`
+
+**Example microbit service file:**
+
+```ini
+[Unit]
+Description=Smartbotic Microbit Service
+After=network.target smartbotic-database.service
+Requires=smartbotic-database.service
+
+[Service]
+Type=simple
+User=smartbotic
+Group=smartbotic
+WorkingDirectory=/var/lib/smartbotic/microbit
+EnvironmentFile=/etc/smartbotic/smartbotic.env
+ExecStart=/opt/smartbotic/bin/smartbotic-microbit --config /etc/smartbotic/microbit.json
+Restart=on-failure
+RestartSec=5
+StandardOutput=journal
+StandardError=journal
+
+[Install]
+WantedBy=multi-user.target
+```
+
+## Nginx Setup
+
+### Automatic Setup (Recommended)
+
+Use the provided setup script:
+
+```bash
+# Install Nginx if not already installed
+sudo apt install nginx certbot python3-certbot-nginx
+
+# Run the setup script
+sudo /opt/smartbotic/bin/smartbotic-setup-nginx \
+  --domain smartbotic.example.com \
+  --email admin@example.com
+```
+
+This script:
+- Creates Nginx configuration
+- Obtains Let's Encrypt SSL certificate
+- Enables and reloads Nginx
+
+### Manual Nginx Configuration
+
+Create `/etc/nginx/sites-available/smartbotic`:
+
+```nginx
+# Redirect HTTP to HTTPS
+server {
+    listen 80;
+    listen [::]:80;
+    server_name smartbotic.example.com;
+
+    location /.well-known/acme-challenge/ {
+        root /var/www/html;
+    }
+
+    location / {
+        return 301 https://$server_name$request_uri;
+    }
+}
+
+# HTTPS server
+server {
+    listen 443 ssl http2;
+    listen [::]:443 ssl http2;
+    server_name smartbotic.example.com;
+
+    # SSL certificates (use certbot to obtain)
+    ssl_certificate /etc/letsencrypt/live/smartbotic.example.com/fullchain.pem;
+    ssl_certificate_key /etc/letsencrypt/live/smartbotic.example.com/privkey.pem;
+
+    # SSL configuration
+    ssl_protocols TLSv1.2 TLSv1.3;
+    ssl_ciphers HIGH:!aNULL:!MD5;
+    ssl_prefer_server_ciphers on;
+
+    # Security headers
+    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
+    add_header X-Frame-Options "SAMEORIGIN" always;
+    add_header X-Content-Type-Options "nosniff" always;
+
+    # Logging
+    access_log /var/log/nginx/smartbotic_access.log;
+    error_log /var/log/nginx/smartbotic_error.log;
+
+    # Proxy settings
+    client_max_body_size 10M;
+
+    # API endpoints
+    location /api/ {
+        proxy_pass http://127.0.0.1:8090;
+        proxy_http_version 1.1;
+        proxy_set_header Upgrade $http_upgrade;
+        proxy_set_header Connection 'upgrade';
+        proxy_set_header Host $host;
+        proxy_set_header X-Real-IP $remote_addr;
+        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+        proxy_set_header X-Forwarded-Proto $scheme;
+        proxy_cache_bypass $http_upgrade;
+    }
+
+    # Static files (WebUI)
+    location / {
+        proxy_pass http://127.0.0.1:8090;
+        proxy_set_header Host $host;
+        proxy_set_header X-Real-IP $remote_addr;
+        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+        proxy_set_header X-Forwarded-Proto $scheme;
+    }
+}
+```
+
+**Enable the site:**
+
+```bash
+sudo ln -s /etc/nginx/sites-available/smartbotic /etc/nginx/sites-enabled/
+sudo nginx -t  # Test configuration
+sudo systemctl reload nginx
+```
+
+### SSL Certificate with Let's Encrypt
+
+```bash
+# Install certbot
+sudo apt install certbot python3-certbot-nginx
+
+# Obtain certificate
+sudo certbot --nginx -d smartbotic.example.com --email admin@example.com --agree-tos
+
+# Certbot will automatically configure Nginx for HTTPS
+# Certificates auto-renew via cron
+```
+
+## Security Considerations
+
+### Firewall Configuration
+
+```bash
+# Allow SSH, HTTP, and HTTPS
+sudo ufw allow ssh
+sudo ufw allow http
+sudo ufw allow https
+
+# Enable firewall
+sudo ufw enable
+
+# Verify rules
+sudo ufw status
+```
+
+**Do NOT expose these ports:**
+- 9004 (database gRPC)
+- 8090 (microbit HTTP - use Nginx proxy instead)
+
+### File Permissions
+
+Ensure proper permissions:
+
+```bash
+# Configuration files (readable by service user)
+sudo chown root:smartbotic /etc/smartbotic/*.json
+sudo chmod 640 /etc/smartbotic/*.json
+sudo chmod 640 /etc/smartbotic/smartbotic.env
+
+# Data directories (writable by service user)
+sudo chown -R smartbotic:smartbotic /var/lib/smartbotic
+sudo chmod 750 /var/lib/smartbotic
+
+# Log directories
+sudo chown -R smartbotic:smartbotic /var/log/smartbotic
+sudo chmod 750 /var/log/smartbotic
+```
+
+### Secret Management
+
+**Important secrets to protect:**
+- `JWT_SECRET`: Used for token signing
+- `SMTP_PASSWORD`: Email server password
+- `CALLERAI_API_KEY`: CallerAI API key
+
+**Best practices:**
+- Use strong random values
+- Never commit secrets to version control
+- Rotate secrets periodically
+- Use environment variables or secret management tools
+
+### Database Security
+
+- Database listens only on localhost (127.0.0.1)
+- No external access to database port
+- Regular backups with encryption
+- Access controlled by systemd user permissions
+
+## Monitoring and Logs
+
+### Log Locations
+
+```bash
+# Application logs
+/var/log/smartbotic/database.log
+/var/log/smartbotic/microbit.log
+
+# Systemd journal
+sudo journalctl -u smartbotic-database
+sudo journalctl -u smartbotic-microbit
+
+# Nginx logs
+/var/log/nginx/smartbotic_access.log
+/var/log/nginx/smartbotic_error.log
+```
+
+### Log Rotation
+
+Configure log rotation in `/etc/logrotate.d/smartbotic`:
+
+```
+/var/log/smartbotic/*.log {
+    daily
+    rotate 14
+    compress
+    delaycompress
+    missingok
+    notifempty
+    create 0640 smartbotic smartbotic
+    sharedscripts
+    postrotate
+        systemctl reload smartbotic-microbit > /dev/null 2>&1 || true
+    endscript
+}
+```
+
+### Health Checks
+
+Check service health:
+
+```bash
+# Check if services are running
+sudo systemctl is-active smartbotic-database
+sudo systemctl is-active smartbotic-microbit
+
+# Test API endpoint
+curl -f http://localhost:8090/api/v1/settings || echo "Service unhealthy"
+
+# Check database connection
+sudo journalctl -u smartbotic-microbit | grep "Connected to database"
+```
+
+### Monitoring Tools (Optional)
+
+Consider integrating:
+- **Prometheus**: Metrics collection (future feature)
+- **Grafana**: Metrics visualization
+- **Uptime Kuma**: Uptime monitoring
+- **Fail2ban**: Intrusion prevention
+
+## Backup and Recovery
+
+### Backup Strategy
+
+**What to backup:**
+1. Database storage: `/var/lib/smartbotic/database/storage`
+2. Configuration: `/etc/smartbotic/`
+3. Environment file: `/etc/smartbotic/smartbotic.env`
+
+**Backup script example:**
+
+```bash
+#!/bin/bash
+BACKUP_DIR="/backup/smartbotic"
+DATE=$(date +%Y%m%d-%H%M%S)
+
+# Stop services for consistent backup
+sudo systemctl stop smartbotic-microbit
+sudo systemctl stop smartbotic-database
+
+# Create backup
+sudo mkdir -p "$BACKUP_DIR"
+sudo tar -czf "$BACKUP_DIR/smartbotic-$DATE.tar.gz" \
+    /var/lib/smartbotic/database/storage \
+    /etc/smartbotic/
+
+# Restart services
+sudo systemctl start smartbotic-database
+sudo systemctl start smartbotic-microbit
+
+# Clean old backups (keep last 30 days)
+find "$BACKUP_DIR" -name "smartbotic-*.tar.gz" -mtime +30 -delete
+```
+
+**Automated backups with cron:**
+
+```bash
+# Add to crontab: daily backup at 2 AM
+0 2 * * * /usr/local/bin/smartbotic-backup.sh
+```
+
+### Recovery
+
+**To restore from backup:**
+
+```bash
+# Stop services
+sudo systemctl stop smartbotic-microbit smartbotic-database
+
+# Restore files
+sudo tar -xzf /backup/smartbotic/smartbotic-YYYYMMDD-HHMMSS.tar.gz -C /
+
+# Fix permissions
+sudo chown -R smartbotic:smartbotic /var/lib/smartbotic
+
+# Start services
+sudo systemctl start smartbotic-database smartbotic-microbit
+```
+
+## Troubleshooting
+
+### Service Won't Start
+
+**Check logs:**
+
+```bash
+sudo journalctl -u smartbotic-microbit -n 100 --no-pager
+```
+
+**Common issues:**
+
+1. **Database not running:**
+   ```bash
+   sudo systemctl start smartbotic-database
+   ```
+
+2. **Configuration error:**
+   ```bash
+   # Validate JSON config
+   jq . /etc/smartbotic/microbit.json
+   ```
+
+3. **Port already in use:**
+   ```bash
+   sudo netstat -tuln | grep 8090
+   # Change port in config or stop conflicting service
+   ```
+
+4. **Permission errors:**
+   ```bash
+   sudo chown -R smartbotic:smartbotic /var/lib/smartbotic
+   ```
+
+### Database Connection Failed
+
+**Check database service:**
+
+```bash
+sudo systemctl status smartbotic-database
+sudo journalctl -u smartbotic-database -n 50
+```
+
+**Verify port is listening:**
+
+```bash
+sudo netstat -tuln | grep 9004
+```
+
+### WebUI Not Loading
+
+**Check static files:**
+
+```bash
+ls -la /var/lib/smartbotic/microbit/webui/
+```
+
+**Verify Nginx configuration:**
+
+```bash
+sudo nginx -t
+sudo systemctl status nginx
+```
+
+### Email Not Sending
+
+**Test SMTP configuration:**
+
+```bash
+# Use API endpoint
+curl -X POST http://localhost:8090/api/v1/settings/test-smtp \
+  -H "Authorization: Bearer TOKEN" \
+  -H "Content-Type: application/json" \
+  -d '{"to_email":"test@example.com"}'
+```
+
+**Check logs for SMTP errors:**
+
+```bash
+sudo journalctl -u smartbotic-microbit | grep -i smtp
+```
+
+## Upgrading
+
+### Upgrade Process
+
+1. **Backup current installation:**
+
+   ```bash
+   sudo /usr/local/bin/smartbotic-backup.sh
+   ```
+
+2. **Download new packages:**
+
+   ```bash
+   wget https://releases.smartbotics.ai/smartbotic-microbit-NEW_VERSION.tar.gz
+   ```
+
+3. **Stop services:**
+
+   ```bash
+   sudo systemctl stop smartbotic-microbit smartbotic-database
+   ```
+
+4. **Install new packages:**
+
+   ```bash
+   sudo ./packaging/scripts/install.sh smartbotic-*.tar.gz
+   ```
+
+5. **Review configuration changes:**
+
+   ```bash
+   # Check for new .new config files
+   ls -la /etc/smartbotic/*.new
+
+   # Merge changes if needed
+   diff /etc/smartbotic/microbit.json /etc/smartbotic/microbit.json.new
+   ```
+
+6. **Restart services:**
+
+   ```bash
+   sudo systemctl start smartbotic-database smartbotic-microbit
+   ```
+
+7. **Verify upgrade:**
+
+   ```bash
+   sudo journalctl -u smartbotic-microbit -n 50
+   curl -f http://localhost:8090/api/v1/settings
+   ```
+
+### Rollback
+
+If upgrade fails:
+
+```bash
+# Stop services
+sudo systemctl stop smartbotic-microbit smartbotic-database
+
+# Restore from backup
+sudo tar -xzf /backup/smartbotic/smartbotic-YYYYMMDD.tar.gz -C /
+
+# Start services
+sudo systemctl start smartbotic-database smartbotic-microbit
+```
+
+## Performance Tuning
+
+### System Limits
+
+Increase file descriptor limits for the service user:
+
+```bash
+# Edit /etc/security/limits.conf
+smartbotic soft nofile 65536
+smartbotic hard nofile 65536
+```
+
+### Database Tuning
+
+For high-traffic deployments, consider:
+- Dedicated database server
+- SSD storage for database
+- Increased memory allocation
+
+### Nginx Tuning
+
+For high concurrency:
+
+```nginx
+worker_processes auto;
+worker_connections 2048;
+```
+
+## Getting Help
+
+- **Documentation**: Check other docs in this directory
+- **Logs**: Always check logs first
+- **Support**: support@smartbotics.ai
+- **GitHub Issues**: Report bugs on the issue tracker
+
+## Additional Resources
+
+- [Architecture Documentation](ARCHITECTURE.md)
+- [Development Guide](DEVELOPMENT.md)
+- [API Reference](API.md)
+- [Nginx Documentation](https://nginx.org/en/docs/)
+- [Systemd Service Documentation](https://www.freedesktop.org/software/systemd/man/systemd.service.html)

+ 530 - 0
docs/DEVELOPMENT.md

@@ -0,0 +1,530 @@
+# Development Guide
+
+This guide covers setting up a development environment for Smartbotic Microbit and building the project from source.
+
+## Prerequisites
+
+### Operating System
+
+- Linux (Debian 12+, Ubuntu 22.04+, or similar)
+- macOS (with Homebrew) - experimental
+- Windows WSL2 - experimental
+
+### Required Tools
+
+**Build Tools:**
+- CMake 3.20 or later
+- C++20 compatible compiler:
+  - GCC 11+ (recommended)
+  - Clang 14+ (alternative)
+- Make or Ninja build system
+- Git with submodule support
+
+**Development Tools (recommended):**
+- clangd or ccls (LSP for IDE integration)
+- gdb or lldb (debugging)
+- valgrind (memory debugging)
+
+### System Dependencies
+
+**Debian/Ubuntu:**
+
+```bash
+sudo apt update
+sudo apt install -y \
+    build-essential \
+    cmake \
+    git \
+    pkg-config \
+    libssl-dev \
+    libcurl4-openssl-dev \
+    libprotobuf-dev \
+    protobuf-compiler \
+    libgrpc++-dev \
+    libspdlog-dev \
+    nlohmann-json3-dev
+```
+
+**Optional dependencies:**
+
+```bash
+# For systemd integration
+sudo apt install -y libsystemd-dev
+
+# For development tools
+sudo apt install -y clangd gdb valgrind
+```
+
+### Node.js (for WebUI)
+
+```bash
+# Install Node.js 18+ (using NodeSource)
+curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
+sudo apt install -y nodejs
+
+# Verify installation
+node --version  # Should be v20.x or later
+npm --version
+```
+
+## Getting the Source Code
+
+### Clone the Repository
+
+```bash
+# Clone with submodules (important!)
+git clone --recursive https://github.com/fszontagh/smartbotic-microbit.git
+cd smartbotic-microbit
+```
+
+If you already cloned without `--recursive`:
+
+```bash
+git submodule update --init --recursive
+```
+
+### Submodule Structure
+
+The project includes the following submodule:
+
+- `external/smartbotic-database`: Custom database service
+
+## Building the Backend
+
+### Configure with CMake
+
+```bash
+# Create build directory
+mkdir build
+cd build
+
+# Configure (Release build)
+cmake .. -DCMAKE_BUILD_TYPE=Release
+
+# Or configure for Debug build with tests
+cmake .. -DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTS=ON
+```
+
+**CMake Options:**
+
+| Option | Default | Description |
+|--------|---------|-------------|
+| `CMAKE_BUILD_TYPE` | `Release` | Build type: `Release`, `Debug`, `RelWithDebInfo` |
+| `BUILD_TESTS` | `OFF` | Build test suite |
+| `BUNDLE_DATABASE` | `OFF` | Include database service in build |
+| `CMAKE_INSTALL_PREFIX` | `/usr/local` | Installation prefix |
+
+### Build
+
+```bash
+# Build with all CPU cores
+make -j$(nproc)
+
+# Or use ninja for faster builds
+# cmake .. -GNinja
+# ninja
+```
+
+**Build artifacts:**
+
+```
+build/
+├── src/smartbotic-microbit           # Main executable
+├── lib/                               # Compiled libraries
+└── external/smartbotic-database/      # Database service (if BUNDLE_DATABASE=ON)
+```
+
+### Run the Backend
+
+```bash
+# From the build directory
+cd build
+
+# Run with default config (from source tree)
+./src/smartbotic-microbit --config ../config/microbit.json
+
+# The server will start on http://localhost:8090
+```
+
+**Environment Variables:**
+
+Set these before running for proper configuration:
+
+```bash
+export JWT_SECRET="your-secret-key-change-this"
+export DB_ADDRESS="localhost:9004"
+export SMTP_HOST=""  # Leave empty to disable email
+export CALLERAI_API_URL="http://localhost:8080"
+export CALLERAI_API_KEY=""
+export WEBUI_PATH="../webui/dist"
+```
+
+## Building the WebUI
+
+### Install Dependencies
+
+```bash
+cd webui
+npm install
+```
+
+### Development Server
+
+```bash
+# Start Vite dev server (with hot reload)
+npm run dev
+
+# The dev server will start on http://localhost:5173
+# It proxies API requests to the backend
+```
+
+The dev server features:
+- Hot module replacement (HMR)
+- Fast refresh for React components
+- TypeScript type checking
+- Automatic browser reload
+
+### Build for Production
+
+```bash
+# Build optimized production bundle
+npm run build
+
+# Output will be in webui/dist/
+```
+
+### Preview Production Build
+
+```bash
+npm run preview
+```
+
+## Running the Complete Stack
+
+### Terminal 1: Database Service
+
+```bash
+# Build the database service
+cd build
+cmake .. -DBUNDLE_DATABASE=ON
+make -j$(nproc)
+
+# Run the database
+cd external/smartbotic-database/src
+./smartbotic-database --config ../../../../config/storage.json
+```
+
+### Terminal 2: Backend Service
+
+```bash
+cd build
+export JWT_SECRET="dev-secret-key"
+export WEBUI_PATH="../webui/dist"
+./src/smartbotic-microbit --config ../config/microbit.json
+```
+
+### Terminal 3: WebUI Development Server
+
+```bash
+cd webui
+npm run dev
+```
+
+Now access:
+- **WebUI**: http://localhost:5173 (development) or http://localhost:8090 (production)
+- **API**: http://localhost:8090/api/v1/*
+
+## Development Workflow
+
+### Code Style
+
+**C++ Code Style:**
+- Follow Google C++ Style Guide
+- Use `clang-format` for formatting (config in `.clang-format`)
+- Use meaningful variable and function names
+- Add comments for complex logic
+
+**TypeScript/React:**
+- Use ESLint and Prettier (configs in webui)
+- Functional components with hooks
+- TypeScript strict mode enabled
+
+### Building Incrementally
+
+After making changes:
+
+```bash
+# Backend
+cd build
+make -j$(nproc)
+
+# WebUI (in dev mode, automatically rebuilds)
+# Just save your files
+```
+
+### Debugging
+
+**Backend Debugging with GDB:**
+
+```bash
+# Build with debug symbols
+cd build
+cmake .. -DCMAKE_BUILD_TYPE=Debug
+make -j$(nproc)
+
+# Run with debugger
+gdb ./src/smartbotic-microbit
+(gdb) run --config ../config/microbit.json
+```
+
+**WebUI Debugging:**
+- Use browser DevTools
+- React Developer Tools extension
+- Source maps enabled in dev mode
+
+### Testing
+
+Tests are currently under development. To enable test building:
+
+```bash
+cd build
+cmake .. -DBUILD_TESTS=ON
+make -j$(nproc)
+
+# Run tests
+ctest --output-on-failure
+```
+
+## IDE Setup
+
+### Visual Studio Code
+
+**Recommended Extensions:**
+- C/C++ (Microsoft)
+- clangd (LLVM)
+- CMake Tools
+- ESLint
+- Prettier
+- Tailwind CSS IntelliSense
+
+**Configuration (.vscode/settings.json):**
+
+```json
+{
+  "cmake.buildDirectory": "${workspaceFolder}/build",
+  "cmake.configureOnOpen": true,
+  "clangd.arguments": [
+    "--compile-commands-dir=${workspaceFolder}/build"
+  ],
+  "editor.formatOnSave": true,
+  "C_Cpp.intelliSenseEngine": "disabled"
+}
+```
+
+### CLion
+
+CLion has built-in CMake support:
+
+1. Open the project root directory
+2. CLion will automatically detect CMakeLists.txt
+3. Configure build profiles in Settings → Build, Execution, Deployment → CMake
+
+## Common Development Tasks
+
+### Adding a New API Endpoint
+
+1. **Define the route handler** in `src/routes/{feature}_routes.cpp`:
+
+```cpp
+void setupMyRoutes(httplib::Server& svr, App& app) {
+    svr.Get("/api/v1/my-endpoint", [&app](const httplib::Request& req, httplib::Response& res) {
+        // Handle request
+    });
+}
+```
+
+2. **Register routes** in `src/app.cpp`:
+
+```cpp
+#include "routes/my_routes.hpp"
+
+void App::setupRoutes() {
+    // ...
+    setupMyRoutes(*httpServer_, *this);
+}
+```
+
+3. **Rebuild**:
+
+```bash
+cd build && make
+```
+
+### Adding a New Data Store
+
+1. **Create store files**: `src/stores/my_store.{hpp,cpp}`
+2. **Define data model** (struct with `toJson()`, `fromJson()`)
+3. **Implement CRUD operations** using database client
+4. **Add to App class** in `src/app.{hpp,cpp}`
+
+### Modifying the Database Schema
+
+1. **Edit migration files** in `config/migrations/`
+2. **Update store queries** as needed
+3. **Restart database service** to apply migrations
+
+### Adding a WebUI Page
+
+1. **Create page component** in `webui/src/pages/`
+2. **Add route** in `webui/src/App.tsx`
+3. **Create API client methods** in `webui/src/api/client.ts`
+4. **Rebuild**: Files auto-reload in dev mode
+
+## Troubleshooting
+
+### Build Issues
+
+**Problem**: CMake can't find packages
+
+```bash
+# Make sure all dependencies are installed
+sudo apt install -y libprotobuf-dev libgrpc++-dev libssl-dev libcurl4-openssl-dev
+
+# Clear CMake cache
+rm -rf build
+mkdir build && cd build
+cmake ..
+```
+
+**Problem**: Submodule errors
+
+```bash
+# Update submodules
+git submodule update --init --recursive
+```
+
+### Runtime Issues
+
+**Problem**: Database connection failed
+
+```
+# Ensure database service is running
+ps aux | grep smartbotic-database
+
+# Check the port
+netstat -tuln | grep 9004
+```
+
+**Problem**: WebUI can't connect to API
+
+- Check CORS configuration in `config/microbit.json`
+- Verify backend is running on port 8090
+- Check browser console for errors
+
+**Problem**: JWT errors
+
+```bash
+# Make sure JWT_SECRET is set
+export JWT_SECRET="your-secret-key"
+```
+
+## Performance Profiling
+
+### Using Valgrind
+
+```bash
+# Check for memory leaks
+valgrind --leak-check=full ./src/smartbotic-microbit --config ../config/microbit.json
+
+# Profile performance
+valgrind --tool=callgrind ./src/smartbotic-microbit --config ../config/microbit.json
+kcachegrind callgrind.out.*
+```
+
+### Using perf
+
+```bash
+# Record performance
+perf record -g ./src/smartbotic-microbit --config ../config/microbit.json
+
+# View report
+perf report
+```
+
+## Code Coverage
+
+```bash
+# Build with coverage flags
+cd build
+cmake .. -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_FLAGS="--coverage"
+make -j$(nproc)
+
+# Run tests
+ctest
+
+# Generate coverage report
+lcov --capture --directory . --output-file coverage.info
+genhtml coverage.info --output-directory coverage_html
+```
+
+## Continuous Integration
+
+The project can be integrated with CI/CD pipelines:
+
+**GitHub Actions Example:**
+
+```yaml
+name: Build
+
+on: [push, pull_request]
+
+jobs:
+  build:
+    runs-on: ubuntu-22.04
+    steps:
+      - uses: actions/checkout@v3
+        with:
+          submodules: recursive
+
+      - name: Install dependencies
+        run: |
+          sudo apt update
+          sudo apt install -y build-essential cmake libssl-dev \
+            libcurl4-openssl-dev libprotobuf-dev protobuf-compiler \
+            libgrpc++-dev libspdlog-dev nlohmann-json3-dev
+
+      - name: Build
+        run: |
+          mkdir build && cd build
+          cmake .. -DCMAKE_BUILD_TYPE=Release
+          make -j$(nproc)
+
+      - name: Test
+        run: cd build && ctest --output-on-failure
+```
+
+## Contributing
+
+When contributing to the project:
+
+1. **Create a feature branch** from `main`
+2. **Write clear commit messages**
+3. **Follow the code style** guidelines
+4. **Add tests** for new features
+5. **Update documentation** as needed
+6. **Submit a pull request** for review
+
+## Additional Resources
+
+- [Architecture Documentation](ARCHITECTURE.md)
+- [API Documentation](API.md)
+- [Deployment Guide](DEPLOYMENT.md)
+- [CMake Documentation](https://cmake.org/documentation/)
+- [gRPC C++ Guide](https://grpc.io/docs/languages/cpp/)
+- [React Documentation](https://react.dev/)
+
+## Getting Help
+
+- **Issues**: Report bugs on the GitHub issue tracker
+- **Questions**: Contact the development team
+- **Email**: support@smartbotics.ai